8344078: Remove security manager dependency in java.nio

Reviewed-by: alanb, rriggs
This commit is contained in:
Brian Burkhalter 2024-11-18 19:17:14 +00:00
parent 2649406323
commit 922b12f30c
67 changed files with 285 additions and 1480 deletions

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -25,20 +25,12 @@
package sun.nio.ch; package sun.nio.ch;
import java.security.AccessController;
import java.security.PrivilegedAction;
/** /**
* Creates this platform's default SelectorProvider * Creates this platform's default SelectorProvider
*/ */
@SuppressWarnings("removal")
public class DefaultSelectorProvider { public class DefaultSelectorProvider {
private static final SelectorProviderImpl INSTANCE; private static final SelectorProviderImpl INSTANCE = new PollSelectorProvider();
static {
PrivilegedAction<SelectorProviderImpl> pa = PollSelectorProvider::new;
INSTANCE = AccessController.doPrivileged(pa);
}
/** /**
* Prevent instantiation. * Prevent instantiation.
@ -51,4 +43,4 @@ public class DefaultSelectorProvider {
public static SelectorProviderImpl get() { public static SelectorProviderImpl get() {
return INSTANCE; return INSTANCE;
} }
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -25,20 +25,12 @@
package sun.nio.ch; package sun.nio.ch;
import java.security.AccessController;
import java.security.PrivilegedAction;
/** /**
* Creates this platform's default SelectorProvider * Creates this platform's default SelectorProvider
*/ */
@SuppressWarnings("removal")
public class DefaultSelectorProvider { public class DefaultSelectorProvider {
private static final SelectorProviderImpl INSTANCE; private static final SelectorProviderImpl INSTANCE = new EPollSelectorProvider();
static {
PrivilegedAction<SelectorProviderImpl> pa = EPollSelectorProvider::new;
INSTANCE = AccessController.doPrivileged(pa);
}
/** /**
* Prevent instantiation. * Prevent instantiation.

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -115,8 +115,6 @@ class LinuxDosFileAttributeView
@Override @Override
public DosFileAttributes readAttributes() throws IOException { public DosFileAttributes readAttributes() throws IOException {
file.checkRead();
int fd = -1; int fd = -1;
try { try {
fd = file.openForAttributeAccess(followLinks); fd = file.openForAttributeAccess(followLinks);
@ -249,8 +247,6 @@ class LinuxDosFileAttributeView
* Updates the value of the user.DOSATTRIB extended attribute * Updates the value of the user.DOSATTRIB extended attribute
*/ */
private void updateDosAttribute(int flag, boolean enable) throws IOException { private void updateDosAttribute(int flag, boolean enable) throws IOException {
file.checkWrite();
int fd = -1; int fd = -1;
try { try {
fd = file.openForAttributeAccess(followLinks); fd = file.openForAttributeAccess(followLinks);

View file

@ -25,20 +25,12 @@
package sun.nio.ch; package sun.nio.ch;
import java.security.AccessController;
import java.security.PrivilegedAction;
/** /**
* Creates this platform's default SelectorProvider * Creates this platform's default SelectorProvider
*/ */
@SuppressWarnings("removal")
public class DefaultSelectorProvider { public class DefaultSelectorProvider {
private static final SelectorProviderImpl INSTANCE; private static final SelectorProviderImpl INSTANCE = new KQueueSelectorProvider();
static {
PrivilegedAction<SelectorProviderImpl> pa = KQueueSelectorProvider::new;
INSTANCE = AccessController.doPrivileged(pa);
}
/** /**
* Prevent instantiation. * Prevent instantiation.

View file

@ -50,9 +50,6 @@ class BsdFileAttributeViews {
return; return;
} }
// permission check
path.checkWrite();
// use a file descriptor if possible to avoid a race due to accessing // use a file descriptor if possible to avoid a race due to accessing
// a path more than once as the file at that path could change. // a path more than once as the file at that path could change.
// if path is a symlink, then the open should fail with ELOOP and // if path is a symlink, then the open should fail with ELOOP and

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -28,13 +28,11 @@ package sun.nio.fs;
import java.io.IOException; import java.io.IOException;
import java.nio.file.FileStore; import java.nio.file.FileStore;
import java.nio.file.WatchService; import java.nio.file.WatchService;
import java.security.AccessController;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import sun.nio.ch.IOStatus; import sun.nio.ch.IOStatus;
import sun.security.action.GetPropertyAction;
import static sun.nio.fs.UnixConstants.*; import static sun.nio.fs.UnixConstants.*;
import static sun.nio.fs.UnixNativeDispatcher.chown; import static sun.nio.fs.UnixNativeDispatcher.chown;

View file

@ -31,8 +31,6 @@ import java.util.Iterator;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import java.util.ServiceConfigurationError; import java.util.ServiceConfigurationError;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
/** /**
* Service-provider class for asynchronous channels. * Service-provider class for asynchronous channels.
@ -62,20 +60,15 @@ public abstract class AsynchronousChannelProvider {
private static class ProviderHolder { private static class ProviderHolder {
static final AsynchronousChannelProvider provider = load(); static final AsynchronousChannelProvider provider = load();
@SuppressWarnings("removal")
private static AsynchronousChannelProvider load() { private static AsynchronousChannelProvider load() {
return AccessController AsynchronousChannelProvider p;
.doPrivileged(new PrivilegedAction<>() { p = loadProviderFromProperty();
public AsynchronousChannelProvider run() { if (p != null)
AsynchronousChannelProvider p; return p;
p = loadProviderFromProperty(); p = loadProviderAsService();
if (p != null) if (p != null)
return p; return p;
p = loadProviderAsService(); return sun.nio.ch.DefaultAsynchronousChannelProvider.create();
if (p != null)
return p;
return sun.nio.ch.DefaultAsynchronousChannelProvider.create();
}});
} }
private static AsynchronousChannelProvider loadProviderFromProperty() { private static AsynchronousChannelProvider loadProviderFromProperty() {
@ -87,7 +80,7 @@ public abstract class AsynchronousChannelProvider {
Object tmp = Class.forName(cn, true, Object tmp = Class.forName(cn, true,
ClassLoader.getSystemClassLoader()).newInstance(); ClassLoader.getSystemClassLoader()).newInstance();
return (AsynchronousChannelProvider)tmp; return (AsynchronousChannelProvider)tmp;
} catch (ClassNotFoundException | SecurityException | } catch (ClassNotFoundException |
InstantiationException | IllegalAccessException x) { InstantiationException | IllegalAccessException x) {
throw new ServiceConfigurationError(null, x); throw new ServiceConfigurationError(null, x);
} }
@ -98,17 +91,7 @@ public abstract class AsynchronousChannelProvider {
ServiceLoader.load(AsynchronousChannelProvider.class, ServiceLoader.load(AsynchronousChannelProvider.class,
ClassLoader.getSystemClassLoader()); ClassLoader.getSystemClassLoader());
Iterator<AsynchronousChannelProvider> i = sl.iterator(); Iterator<AsynchronousChannelProvider> i = sl.iterator();
for (;;) { return sl.findFirst().orElse(null);
try {
return (i.hasNext()) ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
} }
} }

View file

@ -33,8 +33,6 @@ import java.nio.channels.DatagramChannel;
import java.nio.channels.Pipe; import java.nio.channels.Pipe;
import java.nio.channels.ServerSocketChannel; import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Iterator; import java.util.Iterator;
import java.util.Objects; import java.util.Objects;
import java.util.ServiceLoader; import java.util.ServiceLoader;
@ -81,17 +79,13 @@ public abstract class SelectorProvider {
private static class Holder { private static class Holder {
static final SelectorProvider INSTANCE = provider(); static final SelectorProvider INSTANCE = provider();
@SuppressWarnings("removal")
static SelectorProvider provider() { static SelectorProvider provider() {
PrivilegedAction<SelectorProvider> pa = () -> { SelectorProvider sp;
SelectorProvider sp; if ((sp = loadProviderFromProperty()) != null)
if ((sp = loadProviderFromProperty()) != null) return sp;
return sp; if ((sp = loadProviderAsService()) != null)
if ((sp = loadProviderAsService()) != null) return sp;
return sp; return sun.nio.ch.DefaultSelectorProvider.get();
return sun.nio.ch.DefaultSelectorProvider.get();
};
return AccessController.doPrivileged(pa);
} }
private static SelectorProvider loadProviderFromProperty() { private static SelectorProvider loadProviderFromProperty() {
@ -105,8 +99,7 @@ public abstract class SelectorProvider {
NoSuchMethodException | NoSuchMethodException |
IllegalAccessException | IllegalAccessException |
InvocationTargetException | InvocationTargetException |
InstantiationException | InstantiationException x) {
SecurityException x) {
throw new ServiceConfigurationError(null, x); throw new ServiceConfigurationError(null, x);
} }
} }
@ -116,17 +109,7 @@ public abstract class SelectorProvider {
ServiceLoader.load(SelectorProvider.class, ServiceLoader.load(SelectorProvider.class,
ClassLoader.getSystemClassLoader()); ClassLoader.getSystemClassLoader());
Iterator<SelectorProvider> i = sl.iterator(); Iterator<SelectorProvider> i = sl.iterator();
for (;;) { return sl.findFirst().orElse(null);
try {
return i.hasNext() ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
} }
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -34,15 +34,12 @@ import sun.nio.cs.ThreadLocalCoders;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.CharBuffer; import java.nio.CharBuffer;
import java.nio.charset.spi.CharsetProvider; import java.nio.charset.spi.CharsetProvider;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import java.util.Set; import java.util.Set;
import java.util.SortedMap; import java.util.SortedMap;
@ -346,9 +343,7 @@ public abstract class Charset
cache1 = new Object[] { charsetName, cs }; cache1 = new Object[] { charsetName, cs };
} }
// Creates an iterator that walks over the available providers, ignoring // Creates an iterator that walks over the available providers
// those whose lookup or instantiation causes a security exception to be
// thrown. Should be invoked with full privileges.
// //
private static Iterator<CharsetProvider> providers() { private static Iterator<CharsetProvider> providers() {
return new Iterator<>() { return new Iterator<>() {
@ -360,17 +355,9 @@ public abstract class Charset
private boolean getNext() { private boolean getNext() {
while (next == null) { while (next == null) {
try { if (!i.hasNext())
if (!i.hasNext()) return false;
return false; next = i.next();
next = i.next();
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore security exceptions
continue;
}
throw sce;
}
} }
return true; return true;
} }
@ -406,7 +393,6 @@ public abstract class Charset
ThreadTrackHolder.TRACKER.end(key); ThreadTrackHolder.TRACKER.end(key);
} }
@SuppressWarnings("removal")
private static Charset lookupViaProviders(final String charsetName) { private static Charset lookupViaProviders(final String charsetName) {
// The runtime startup sequence looks up standard charsets as a // The runtime startup sequence looks up standard charsets as a
@ -426,20 +412,13 @@ public abstract class Charset
return null; return null;
} }
try { try {
return AccessController.doPrivileged( for (Iterator<CharsetProvider> i = providers(); i.hasNext();) {
new PrivilegedAction<>() { CharsetProvider cp = i.next();
public Charset run() { Charset cs = cp.charsetForName(charsetName);
for (Iterator<CharsetProvider> i = providers(); if (cs != null)
i.hasNext();) { return cs;
CharsetProvider cp = i.next(); }
Charset cs = cp.charsetForName(charsetName); return null;
if (cs != null)
return cs;
}
return null;
}
});
} finally { } finally {
endLookup(key); endLookup(key);
} }
@ -449,22 +428,18 @@ public abstract class Charset
private static class ExtendedProviderHolder { private static class ExtendedProviderHolder {
static final CharsetProvider[] extendedProviders = extendedProviders(); static final CharsetProvider[] extendedProviders = extendedProviders();
// returns ExtendedProvider, if installed // returns ExtendedProvider, if installed
@SuppressWarnings("removal")
private static CharsetProvider[] extendedProviders() { private static CharsetProvider[] extendedProviders() {
return AccessController.doPrivileged(new PrivilegedAction<>() { CharsetProvider[] cps = new CharsetProvider[1];
public CharsetProvider[] run() { int n = 0;
CharsetProvider[] cps = new CharsetProvider[1]; ServiceLoader<CharsetProvider> sl =
int n = 0; ServiceLoader.loadInstalled(CharsetProvider.class);
ServiceLoader<CharsetProvider> sl = for (CharsetProvider cp : sl) {
ServiceLoader.loadInstalled(CharsetProvider.class); if (n + 1 > cps.length) {
for (CharsetProvider cp : sl) { cps = Arrays.copyOf(cps, cps.length << 1);
if (n + 1 > cps.length) { }
cps = Arrays.copyOf(cps, cps.length << 1); cps[n++] = cp;
} }
cps[n++] = cp; return n == cps.length ? cps : Arrays.copyOf(cps, n);
}
return n == cps.length ? cps : Arrays.copyOf(cps, n);
}});
} }
} }
@ -628,26 +603,20 @@ public abstract class Charset
* @return An immutable, case-insensitive map from canonical charset names * @return An immutable, case-insensitive map from canonical charset names
* to charset objects * to charset objects
*/ */
@SuppressWarnings("removal")
public static SortedMap<String,Charset> availableCharsets() { public static SortedMap<String,Charset> availableCharsets() {
return AccessController.doPrivileged( TreeMap<String,Charset> m =
new PrivilegedAction<>() { new TreeMap<>(
public SortedMap<String,Charset> run() { String.CASE_INSENSITIVE_ORDER);
TreeMap<String,Charset> m = put(standardProvider.charsets(), m);
new TreeMap<>( CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders;
String.CASE_INSENSITIVE_ORDER); for (CharsetProvider ecp :ecps) {
put(standardProvider.charsets(), m); put(ecp.charsets(), m);
CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders; }
for (CharsetProvider ecp :ecps) { for (Iterator<CharsetProvider> i = providers(); i.hasNext();) {
put(ecp.charsets(), m); CharsetProvider cp = i.next();
} put(cp.charsets(), m);
for (Iterator<CharsetProvider> i = providers(); i.hasNext();) { }
CharsetProvider cp = i.next(); return Collections.unmodifiableSortedMap(m);
put(cp.charsets(), m);
}
return Collections.unmodifiableSortedMap(m);
}
});
} }
private @Stable static Charset defaultCharset; private @Stable static Charset defaultCharset;

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -116,13 +116,9 @@ class CopyMoveHelper {
// attributes of source file // attributes of source file
BasicFileAttributes sourceAttrs = null; BasicFileAttributes sourceAttrs = null;
if (sourcePosixView != null) { if (sourcePosixView != null) {
try { sourceAttrs = Files.readAttributes(source,
sourceAttrs = Files.readAttributes(source, PosixFileAttributes.class,
PosixFileAttributes.class, linkOptions);
linkOptions);
} catch (SecurityException ignored) {
// okay to continue if RuntimePermission("accessUserInformation") not granted
}
} }
if (sourceAttrs == null) if (sourceAttrs == null)
sourceAttrs = Files.readAttributes(source, sourceAttrs = Files.readAttributes(source,
@ -173,11 +169,7 @@ class CopyMoveHelper {
if (sourceAttrs instanceof PosixFileAttributes sourcePosixAttrs && if (sourceAttrs instanceof PosixFileAttributes sourcePosixAttrs &&
targetView instanceof PosixFileAttributeView targetPosixView) { targetView instanceof PosixFileAttributeView targetPosixView) {
try { targetPosixView.setPermissions(sourcePosixAttrs.permissions());
targetPosixView.setPermissions(sourcePosixAttrs.permissions());
} catch (SecurityException ignored) {
// okay to continue if RuntimePermission("accessUserInformation") not granted
}
} }
} catch (Throwable x) { } catch (Throwable x) {
// rollback // rollback

View file

@ -25,12 +25,10 @@
package java.nio.file; package java.nio.file;
import java.nio.file.spi.FileSystemProvider;
import java.net.URI;
import java.io.IOException; import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.net.URI;
import java.nio.file.spi.FileSystemProvider;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.ServiceConfigurationError; import java.util.ServiceConfigurationError;
@ -96,13 +94,7 @@ public final class FileSystems {
// returns default file system // returns default file system
private static FileSystem defaultFileSystem() { private static FileSystem defaultFileSystem() {
// load default provider // load default provider
@SuppressWarnings("removal") FileSystemProvider provider = getDefaultProvider();
FileSystemProvider provider = AccessController
.doPrivileged(new PrivilegedAction<>() {
public FileSystemProvider run() {
return getDefaultProvider();
}
});
// return file system // return file system
return provider.getFileSystem(URI.create("file:///")); return provider.getFileSystem(URI.create("file:///"));

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -58,8 +58,6 @@ class FileTreeIterator implements Iterator<Event>, Closeable {
* if {@code maxDepth} is negative * if {@code maxDepth} is negative
* @throws IOException * @throws IOException
* if an I/O errors occurs opening the starting file * if an I/O errors occurs opening the starting file
* @throws SecurityException
* if the security manager denies access to the starting file
* @throws NullPointerException * @throws NullPointerException
* if {@code start} or {@code options} is {@code null} or * if {@code start} or {@code options} is {@code null} or
* the options array contains a {@code null} element * the options array contains a {@code null} element

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -198,16 +198,12 @@ class FileTreeWalker implements Closeable {
* the walk is following sym links is not. The {@code canUseCached} * the walk is following sym links is not. The {@code canUseCached}
* argument determines whether this method can use cached attributes. * argument determines whether this method can use cached attributes.
*/ */
@SuppressWarnings("removal")
private BasicFileAttributes getAttributes(Path file, boolean canUseCached) private BasicFileAttributes getAttributes(Path file, boolean canUseCached)
throws IOException throws IOException
{ {
// if attributes are cached then use them if possible // if attributes are cached then use them if possible
if (canUseCached && if (canUseCached && (file instanceof BasicFileAttributesHolder bfah)) {
(file instanceof BasicFileAttributesHolder) && BasicFileAttributes cached = bfah.get();
(System.getSecurityManager() == null))
{
BasicFileAttributes cached = ((BasicFileAttributesHolder)file).get();
if (cached != null && (!followLinks || !cached.isSymbolicLink())) { if (cached != null && (!followLinks || !cached.isSymbolicLink())) {
return cached; return cached;
} }
@ -250,7 +246,7 @@ class FileTreeWalker implements Closeable {
// cycle detected // cycle detected
return true; return true;
} }
} catch (IOException | SecurityException x) { } catch (IOException e) {
// ignore // ignore
} }
} }
@ -262,25 +258,16 @@ class FileTreeWalker implements Closeable {
* Visits the given file, returning the {@code Event} corresponding to that * Visits the given file, returning the {@code Event} corresponding to that
* visit. * visit.
* *
* The {@code ignoreSecurityException} parameter determines whether
* any SecurityException should be ignored or not. If a SecurityException
* is thrown, and is ignored, then this method returns {@code null} to
* mean that there is no event corresponding to a visit to the file.
*
* The {@code canUseCached} parameter determines whether cached attributes * The {@code canUseCached} parameter determines whether cached attributes
* for the file can be used or not. * for the file can be used or not.
*/ */
private Event visit(Path entry, boolean ignoreSecurityException, boolean canUseCached) { private Event visit(Path entry, boolean canUseCached) {
// need the file attributes // need the file attributes
BasicFileAttributes attrs; BasicFileAttributes attrs;
try { try {
attrs = getAttributes(entry, canUseCached); attrs = getAttributes(entry, canUseCached);
} catch (IOException ioe) { } catch (IOException ioe) {
return new Event(EventType.ENTRY, entry, ioe); return new Event(EventType.ENTRY, entry, ioe);
} catch (SecurityException se) {
if (ignoreSecurityException)
return null;
throw se;
} }
// at maximum depth or file is not a directory // at maximum depth or file is not a directory
@ -301,10 +288,6 @@ class FileTreeWalker implements Closeable {
stream = Files.newDirectoryStream(entry); stream = Files.newDirectoryStream(entry);
} catch (IOException ioe) { } catch (IOException ioe) {
return new Event(EventType.ENTRY, entry, ioe); return new Event(EventType.ENTRY, entry, ioe);
} catch (SecurityException se) {
if (ignoreSecurityException)
return null;
throw se;
} }
// push a directory node to the stack and return an event // push a directory node to the stack and return an event
@ -321,7 +304,6 @@ class FileTreeWalker implements Closeable {
throw new IllegalStateException("Closed"); throw new IllegalStateException("Closed");
Event ev = visit(file, Event ev = visit(file,
false, // ignoreSecurityException
false); // canUseCached false); // canUseCached
assert ev != null; assert ev != null;
return ev; return ev;
@ -372,7 +354,6 @@ class FileTreeWalker implements Closeable {
// visit the entry // visit the entry
ev = visit(entry, ev = visit(entry,
true, // ignoreSecurityException
true); // canUseCached true); // canUseCached
} while (ev == null); } while (ev == null);

View file

@ -58,8 +58,6 @@ import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserPrincipal; import java.nio.file.attribute.UserPrincipal;
import java.nio.file.spi.FileSystemProvider; import java.nio.file.spi.FileSystemProvider;
import java.nio.file.spi.FileTypeDetector; import java.nio.file.spi.FileTypeDetector;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@ -696,14 +694,8 @@ public final class Files {
} catch (IOException x) { } catch (IOException x) {
// parent may not exist or other reason // parent may not exist or other reason
} }
SecurityException se = null; Path absDir = dir.toAbsolutePath();
Path absDir = dir;
try {
absDir = dir.toAbsolutePath();
} catch (SecurityException x) {
// don't have permission to get absolute path
se = x;
}
// find a descendant that exists // find a descendant that exists
Path parent = absDir.getParent(); Path parent = absDir.getParent();
while (parent != null) { while (parent != null) {
@ -717,12 +709,8 @@ public final class Files {
} }
if (parent == null) { if (parent == null) {
// unable to find existing parent // unable to find existing parent
if (se == null) { throw new FileSystemException(absDir.toString(), null,
throw new FileSystemException(absDir.toString(), null, "Unable to determine if root directory exists");
"Unable to determine if root directory exists");
} else {
throw se;
}
} }
// create directories // create directories
@ -1525,29 +1513,19 @@ public final class Files {
loadInstalledDetectors(); loadInstalledDetectors();
// creates the default file type detector // creates the default file type detector
@SuppressWarnings("removal")
private static FileTypeDetector createDefaultFileTypeDetector() { private static FileTypeDetector createDefaultFileTypeDetector() {
return AccessController return sun.nio.fs.DefaultFileTypeDetector.create();
.doPrivileged(new PrivilegedAction<>() {
@Override public FileTypeDetector run() {
return sun.nio.fs.DefaultFileTypeDetector.create();
}});
} }
// loads all installed file type detectors // loads all installed file type detectors
@SuppressWarnings("removal")
private static List<FileTypeDetector> loadInstalledDetectors() { private static List<FileTypeDetector> loadInstalledDetectors() {
return AccessController List<FileTypeDetector> list = new ArrayList<>();
.doPrivileged(new PrivilegedAction<>() { ServiceLoader<FileTypeDetector> loader = ServiceLoader
@Override public List<FileTypeDetector> run() { .load(FileTypeDetector.class, ClassLoader.getSystemClassLoader());
List<FileTypeDetector> list = new ArrayList<>(); for (FileTypeDetector detector: loader) {
ServiceLoader<FileTypeDetector> loader = ServiceLoader list.add(detector);
.load(FileTypeDetector.class, ClassLoader.getSystemClassLoader()); }
for (FileTypeDetector detector: loader) { return list;
list.add(detector);
}
return list;
}});
} }
} }
@ -2863,26 +2841,16 @@ public final class Files {
} }
// attempt to delete an existing file // attempt to delete an existing file
SecurityException se = null;
if (replaceExisting) { if (replaceExisting) {
try { deleteIfExists(target);
deleteIfExists(target);
} catch (SecurityException x) {
se = x;
}
} }
// attempt to create target file. If it fails with // attempt to create target file.
// FileAlreadyExistsException then it may be because the security
// manager prevented us from deleting the file, in which case we just
// throw the SecurityException.
OutputStream ostream; OutputStream ostream;
try { try {
ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW, ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE); StandardOpenOption.WRITE);
} catch (FileAlreadyExistsException x) { } catch (FileAlreadyExistsException x) {
if (se != null)
throw se;
// someone else won the race and created the file // someone else won the race and created the file
throw x; throw x;
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -117,16 +117,12 @@ class TempFileHelper {
} }
// loop generating random names until file or directory can be created // loop generating random names until file or directory can be created
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
for (;;) { for (;;) {
Path f; Path f;
try { try {
f = generatePath(prefix, suffix, dir); f = generatePath(prefix, suffix, dir);
} catch (InvalidPathException e) { } catch (InvalidPathException e) {
// don't reveal temporary directory location // don't reveal temporary directory location
if (sm != null)
throw new IllegalArgumentException("Invalid prefix or suffix");
throw e; throw e;
} }
try { try {
@ -135,11 +131,6 @@ class TempFileHelper {
} else { } else {
return Files.createFile(f, attrs); return Files.createFile(f, attrs);
} }
} catch (SecurityException e) {
// don't reveal temporary directory location
if (dir == tmpdir && sm != null)
throw new SecurityException("Unable to create temporary file or directory");
throw e;
} catch (FileAlreadyExistsException e) { } catch (FileAlreadyExistsException e) {
// ignore // ignore
} }

View file

@ -45,7 +45,6 @@ import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems; import java.nio.file.FileSystems;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.LinkOption; import java.nio.file.LinkOption;
import java.nio.file.LinkPermission;
import java.nio.file.NoSuchFileException; import java.nio.file.NoSuchFileException;
import java.nio.file.NotDirectoryException; import java.nio.file.NotDirectoryException;
import java.nio.file.NotLinkException; import java.nio.file.NotLinkException;
@ -68,8 +67,6 @@ import java.util.ServiceConfigurationError;
import java.util.ServiceLoader; import java.util.ServiceLoader;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.nio.ch.FileChannelImpl; import sun.nio.ch.FileChannelImpl;
@ -185,13 +182,7 @@ public abstract class FileSystemProvider {
} }
loadingProviders = true; loadingProviders = true;
@SuppressWarnings("removal") List<FileSystemProvider> list = loadInstalledProviders();
List<FileSystemProvider> list = AccessController
.doPrivileged(new PrivilegedAction<>() {
@Override
public List<FileSystemProvider> run() {
return loadInstalledProviders();
}});
// insert the default provider at the start of the list // insert the default provider at the start of the list
list.add(0, defaultProvider); list.add(0, defaultProvider);

View file

@ -34,10 +34,6 @@ import java.util.Queue;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.security.PrivilegedAction;
import java.security.AccessController;
import java.security.AccessControlContext;
import sun.security.action.GetIntegerAction;
/** /**
* Base implementation of AsynchronousChannelGroup * Base implementation of AsynchronousChannelGroup
@ -48,9 +44,8 @@ abstract class AsynchronousChannelGroupImpl
{ {
// number of internal threads handling I/O events when using an unbounded // number of internal threads handling I/O events when using an unbounded
// thread pool. Internal threads do not dispatch to completion handlers. // thread pool. Internal threads do not dispatch to completion handlers.
@SuppressWarnings("removal") private static final int internalThreadCount =
private static final int internalThreadCount = AccessController.doPrivileged( Integer.getInteger("sun.nio.ch.internalThreadPoolSize", 1);
new GetIntegerAction("sun.nio.ch.internalThreadPoolSize", 1));
// associated thread pool // associated thread pool
private final ThreadPool pool; private final ThreadPool pool;
@ -115,17 +110,10 @@ abstract class AsynchronousChannelGroupImpl
}; };
} }
@SuppressWarnings("removal")
private void startInternalThread(final Runnable task) { private void startInternalThread(final Runnable task) {
AccessController.doPrivileged(new PrivilegedAction<>() { // internal threads should not be visible to application so
@Override // cannot use user-supplied thread factory
public Void run() { ThreadPool.defaultThreadFactory().newThread(task).start();
// internal threads should not be visible to application so
// cannot use user-supplied thread factory
ThreadPool.defaultThreadFactory().newThread(task).start();
return null;
}
});
} }
protected final void startThreads(Runnable task) { protected final void startThreads(Runnable task) {
@ -247,18 +235,9 @@ abstract class AsynchronousChannelGroupImpl
*/ */
abstract void shutdownHandlerTasks(); abstract void shutdownHandlerTasks();
@SuppressWarnings("removal")
private void shutdownExecutors() { private void shutdownExecutors() {
AccessController.doPrivileged( pool.executor().shutdown();
new PrivilegedAction<>() { timeoutExecutor.shutdown();
public Void run() {
pool.executor().shutdown();
timeoutExecutor.shutdown();
return null;
}
},
null,
new RuntimePermission("modifyThread"));
} }
@Override @Override
@ -320,28 +299,6 @@ abstract class AsynchronousChannelGroupImpl
*/ */
@Override @Override
public final void execute(Runnable task) { public final void execute(Runnable task) {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// when a security manager is installed then the user's task
// must be run with the current calling context
@SuppressWarnings("removal")
final AccessControlContext acc = AccessController.getContext();
final Runnable delegate = task;
task = new Runnable() {
@SuppressWarnings("removal")
@Override
public void run() {
AccessController.doPrivileged(new PrivilegedAction<>() {
@Override
public Void run() {
delegate.run();
return null;
}
}, acc);
}
};
}
executeOnPooledThread(task); executeOnPooledThread(task);
} }
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -150,10 +150,6 @@ abstract class AsynchronousServerSocketChannelImpl
{ {
InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) : InetSocketAddress isa = (local == null) ? new InetSocketAddress(0) :
Net.checkAddress(local); Net.checkAddress(local);
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkListen(isa.getPort());
try { try {
begin(); begin();
@ -175,7 +171,7 @@ abstract class AsynchronousServerSocketChannelImpl
public final SocketAddress getLocalAddress() throws IOException { public final SocketAddress getLocalAddress() throws IOException {
if (!isOpen()) if (!isOpen())
throw new ClosedChannelException(); throw new ClosedChannelException();
return Net.getRevealedLocalAddress(localAddress); return localAddress;
} }
@Override @Override
@ -257,7 +253,7 @@ abstract class AsynchronousServerSocketChannelImpl
if (localAddress == null) { if (localAddress == null) {
sb.append("unbound"); sb.append("unbound");
} else { } else {
sb.append(Net.getRevealedLocalAddressAsString(localAddress)); sb.append(localAddress.toString());
} }
} }
sb.append(']'); sb.append(']');

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -428,11 +428,6 @@ abstract class AsynchronousSocketChannelImpl
throw new AlreadyBoundException(); throw new AlreadyBoundException();
InetSocketAddress isa = (local == null) ? InetSocketAddress isa = (local == null) ?
new InetSocketAddress(0) : Net.checkAddress(local); new InetSocketAddress(0) : Net.checkAddress(local);
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkListen(isa.getPort());
}
NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort()); NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort());
Net.bind(fd, isa.getAddress(), isa.getPort()); Net.bind(fd, isa.getAddress(), isa.getPort());
localAddress = Net.localAddress(fd); localAddress = Net.localAddress(fd);
@ -447,7 +442,7 @@ abstract class AsynchronousSocketChannelImpl
public final SocketAddress getLocalAddress() throws IOException { public final SocketAddress getLocalAddress() throws IOException {
if (!isOpen()) if (!isOpen())
throw new ClosedChannelException(); throw new ClosedChannelException();
return Net.getRevealedLocalAddress(localAddress); return localAddress;
} }
@Override @Override
@ -591,8 +586,7 @@ abstract class AsynchronousSocketChannelImpl
} }
if (localAddress != null) { if (localAddress != null) {
sb.append(" local="); sb.append(" local=");
sb.append( sb.append(localAddress.toString());
Net.getRevealedLocalAddressAsString(localAddress));
} }
if (remoteAddress != null) { if (remoteAddress != null) {
sb.append(" remote="); sb.append(" remote=");

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -49,8 +49,8 @@ final class CompletedFuture<V> implements Future<V> {
} }
static <V> CompletedFuture<V> withFailure(Throwable exc) { static <V> CompletedFuture<V> withFailure(Throwable exc) {
// exception must be IOException or SecurityException // exception must be IOException
if (!(exc instanceof IOException) && !(exc instanceof SecurityException)) if (!(exc instanceof IOException))
exc = new IOException(exc); exc = new IOException(exc);
return new CompletedFuture<V>(null, exc); return new CompletedFuture<V>(null, exc);
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -27,8 +27,6 @@ package sun.nio.ch;
import java.nio.channels.*; import java.nio.channels.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.security.AccessController;
import sun.security.action.GetIntegerAction;
import jdk.internal.misc.InnocuousThread; import jdk.internal.misc.InnocuousThread;
/** /**
@ -41,9 +39,8 @@ class Invoker {
// maximum number of completion handlers that may be invoked on the current // maximum number of completion handlers that may be invoked on the current
// thread before it re-directs invocations to the thread pool. This helps // thread before it re-directs invocations to the thread pool. This helps
// avoid stack overflow and lessens the risk of starvation. // avoid stack overflow and lessens the risk of starvation.
@SuppressWarnings("removal") private static final int maxHandlerInvokeCount =
private static final int maxHandlerInvokeCount = AccessController.doPrivileged( Integer.getInteger("sun.nio.ch.maxCompletionHandlersOnStack", 16);
new GetIntegerAction("sun.nio.ch.maxCompletionHandlersOnStack", 16));
// Per-thread object with reference to channel group and a counter for // Per-thread object with reference to channel group and a counter for
// the number of completion handlers invoked. This should be reset to 0 // the number of completion handlers invoked. This should be reset to 0
@ -115,7 +112,6 @@ class Invoker {
* Invoke handler without checking the thread identity or number of handlers * Invoke handler without checking the thread identity or number of handlers
* on the thread stack. * on the thread stack.
*/ */
@SuppressWarnings("removal")
static <V,A> void invokeUnchecked(CompletionHandler<V,? super A> handler, static <V,A> void invokeUnchecked(CompletionHandler<V,? super A> handler,
A attachment, A attachment,
V value, V value,
@ -129,18 +125,6 @@ class Invoker {
// clear interrupt // clear interrupt
Thread.interrupted(); Thread.interrupted();
// clear thread locals when in default thread pool
if (System.getSecurityManager() != null) {
Thread me = Thread.currentThread();
if (me instanceof InnocuousThread) {
GroupAndInvokeCount thisGroupAndInvokeCount = myGroupAndInvokeCount.get();
((InnocuousThread)me).eraseThreadLocals();
if (thisGroupAndInvokeCount != null) {
myGroupAndInvokeCount.set(thisGroupAndInvokeCount);
}
}
}
} }
/** /**

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -45,14 +45,11 @@ import java.nio.channels.NotYetBoundException;
import java.nio.channels.NotYetConnectedException; import java.nio.channels.NotYetConnectedException;
import java.nio.channels.UnresolvedAddressException; import java.nio.channels.UnresolvedAddressException;
import java.nio.channels.UnsupportedAddressTypeException; import java.nio.channels.UnsupportedAddressTypeException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Objects; import java.util.Objects;
import sun.net.ext.ExtendedSocketOptions; import sun.net.ext.ExtendedSocketOptions;
import sun.net.util.IPAddressUtil; import sun.net.util.IPAddressUtil;
import sun.security.action.GetPropertyAction;
public class Net { public class Net {
private Net() { } private Net() { }
@ -215,34 +212,6 @@ public class Net {
translateException(x, false); translateException(x, false);
} }
/**
* Returns the local address after performing a SecurityManager#checkConnect.
*/
static InetSocketAddress getRevealedLocalAddress(SocketAddress sa) {
InetSocketAddress isa = (InetSocketAddress) sa;
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (isa != null && sm != null) {
try {
sm.checkConnect(isa.getAddress().getHostAddress(), -1);
} catch (SecurityException e) {
// Return loopback address only if security check fails
isa = getLoopbackAddress(isa.getPort());
}
}
return isa;
}
@SuppressWarnings("removal")
static String getRevealedLocalAddressAsString(SocketAddress sa) {
InetSocketAddress isa = (InetSocketAddress) sa;
if (System.getSecurityManager() == null) {
return isa.toString();
} else {
return getLoopbackAddress(isa.getPort()).toString();
}
}
private static InetSocketAddress getLoopbackAddress(int port) { private static InetSocketAddress getLoopbackAddress(int port) {
return new InetSocketAddress(InetAddress.getLoopbackAddress(), port); return new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
} }
@ -302,20 +271,15 @@ public class Net {
* Returns any IPv4 address of the given network interface, or * Returns any IPv4 address of the given network interface, or
* null if the interface does not have any IPv4 addresses. * null if the interface does not have any IPv4 addresses.
*/ */
@SuppressWarnings("removal")
static Inet4Address anyInet4Address(final NetworkInterface interf) { static Inet4Address anyInet4Address(final NetworkInterface interf) {
return AccessController.doPrivileged(new PrivilegedAction<Inet4Address>() { Enumeration<InetAddress> addrs = interf.getInetAddresses();
public Inet4Address run() { while (addrs.hasMoreElements()) {
Enumeration<InetAddress> addrs = interf.getInetAddresses(); InetAddress addr = addrs.nextElement();
while (addrs.hasMoreElements()) { if (addr instanceof Inet4Address inet4Address) {
InetAddress addr = addrs.nextElement(); return inet4Address;
if (addr instanceof Inet4Address inet4Address) {
return inet4Address;
}
}
return null;
} }
}); }
return null;
} }
/** /**
@ -500,8 +464,7 @@ public class Net {
} }
private static boolean isFastTcpLoopbackRequested() { private static boolean isFastTcpLoopbackRequested() {
String loopbackProp = GetPropertyAction String loopbackProp = System.getProperty("jdk.net.useFastTcpLoopback", "false");
.privilegedGetProperty("jdk.net.useFastTcpLoopback", "false");
return loopbackProp.isEmpty() || Boolean.parseBoolean(loopbackProp); return loopbackProp.isEmpty() || Boolean.parseBoolean(loopbackProp);
} }
@ -827,8 +790,7 @@ public class Net {
static { static {
int availLevel = isExclusiveBindAvailable(); int availLevel = isExclusiveBindAvailable();
if (availLevel >= 0) { if (availLevel >= 0) {
String exclBindProp = GetPropertyAction String exclBindProp = System.getProperty("sun.net.useExclusiveBind");
.privilegedGetProperty("sun.net.useExclusiveBind");
if (exclBindProp != null) { if (exclBindProp != null) {
EXCLUSIVE_BIND = exclBindProp.isEmpty() || Boolean.parseBoolean(exclBindProp); EXCLUSIVE_BIND = exclBindProp.isEmpty() || Boolean.parseBoolean(exclBindProp);
} else { } else {

View file

@ -145,7 +145,7 @@ final class PendingFuture<V,A> implements Future<V> {
* Sets the result, or a no-op if the result or exception is already set. * Sets the result, or a no-op if the result or exception is already set.
*/ */
void setFailure(Throwable x) { void setFailure(Throwable x) {
if (!(x instanceof IOException) && !(x instanceof SecurityException)) if (!(x instanceof IOException))
x = new IOException(x); x = new IOException(x);
synchronized (this) { synchronized (this) {
if (haveResult) if (haveResult)

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -27,8 +27,6 @@ package sun.nio.ch;
import java.io.*; import java.io.*;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
class Reflect { // package-private class Reflect { // package-private
@ -43,22 +41,13 @@ class Reflect { // package-private
} }
} }
@SuppressWarnings("removal")
private static void setAccessible(final AccessibleObject ao) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
ao.setAccessible(true);
return null;
}});
}
static Constructor<?> lookupConstructor(String className, static Constructor<?> lookupConstructor(String className,
Class<?>[] paramTypes) Class<?>[] paramTypes)
{ {
try { try {
Class<?> cl = Class.forName(className); Class<?> cl = Class.forName(className);
Constructor<?> c = cl.getDeclaredConstructor(paramTypes); Constructor<?> c = cl.getDeclaredConstructor(paramTypes);
setAccessible(c); c.setAccessible(true);
return c; return c;
} catch (ClassNotFoundException | NoSuchMethodException x) { } catch (ClassNotFoundException | NoSuchMethodException x) {
throw new ReflectionError(x); throw new ReflectionError(x);
@ -82,7 +71,7 @@ class Reflect { // package-private
try { try {
Class<?> cl = Class.forName(className); Class<?> cl = Class.forName(className);
Method m = cl.getDeclaredMethod(methodName, paramTypes); Method m = cl.getDeclaredMethod(methodName, paramTypes);
setAccessible(m); m.setAccessible(true);
return m; return m;
} catch (ClassNotFoundException | NoSuchMethodException x) { } catch (ClassNotFoundException | NoSuchMethodException x) {
throw new ReflectionError(x); throw new ReflectionError(x);
@ -115,7 +104,7 @@ class Reflect { // package-private
try { try {
Class<?> cl = Class.forName(className); Class<?> cl = Class.forName(className);
Field f = cl.getDeclaredField(fieldName); Field f = cl.getDeclaredField(fieldName);
setAccessible(f); f.setAccessible(true);
return f; return f;
} catch (ClassNotFoundException | NoSuchFieldException x) { } catch (ClassNotFoundException | NoSuchFieldException x) {
throw new ReflectionError(x); throw new ReflectionError(x);

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -37,9 +37,6 @@ import java.net.StandardSocketOptions;
import java.nio.channels.IllegalBlockingModeException; import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.ServerSocketChannel; import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Set; import java.util.Set;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
@ -61,14 +58,8 @@ class ServerSocketAdaptor // package-private
// Timeout "option" value for accepts // Timeout "option" value for accepts
private volatile int timeout; private volatile int timeout;
@SuppressWarnings("removal")
static ServerSocket create(ServerSocketChannelImpl ssc) { static ServerSocket create(ServerSocketChannelImpl ssc) {
PrivilegedExceptionAction<ServerSocket> pa = () -> new ServerSocketAdaptor(ssc); return new ServerSocketAdaptor(ssc);
try {
return AccessController.doPrivileged(pa);
} catch (PrivilegedActionException pae) {
throw new InternalError("Should not reach here", pae);
}
} }
private ServerSocketAdaptor(ServerSocketChannelImpl ssc) { private ServerSocketAdaptor(ServerSocketChannelImpl ssc) {
@ -98,7 +89,7 @@ class ServerSocketAdaptor // package-private
if (local == null) { if (local == null) {
return null; return null;
} else { } else {
return Net.getRevealedLocalAddress(local).getAddress(); return ((InetSocketAddress)local).getAddress();
} }
} }

View file

@ -202,11 +202,7 @@ class ServerSocketChannelImpl
public SocketAddress getLocalAddress() throws IOException { public SocketAddress getLocalAddress() throws IOException {
synchronized (stateLock) { synchronized (stateLock) {
ensureOpen(); ensureOpen();
if (isUnixSocket()) { return localAddress;
return UnixDomainSockets.getRevealedLocalAddress(localAddress);
} else {
return Net.getRevealedLocalAddress(localAddress);
}
} }
} }
@ -305,7 +301,6 @@ class ServerSocketChannelImpl
} }
private SocketAddress unixBind(SocketAddress local, int backlog) throws IOException { private SocketAddress unixBind(SocketAddress local, int backlog) throws IOException {
UnixDomainSockets.checkPermission();
if (local == null) { if (local == null) {
// Attempt up to 10 times to find an unused name in temp directory. // Attempt up to 10 times to find an unused name in temp directory.
// If local address supplied then bind called only once // If local address supplied then bind called only once
@ -336,10 +331,6 @@ class ServerSocketChannelImpl
} else { } else {
isa = Net.checkAddress(local, family); isa = Net.checkAddress(local, family);
} }
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkListen(isa.getPort());
NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort()); NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort());
Net.bind(family, fd, isa.getAddress(), isa.getPort()); Net.bind(family, fd, isa.getAddress(), isa.getPort());
Net.listen(fd, backlog < 1 ? 50 : backlog); Net.listen(fd, backlog < 1 ? 50 : backlog);
@ -423,7 +414,6 @@ class ServerSocketChannelImpl
throws IOException throws IOException
{ {
if (isUnixSocket()) { if (isUnixSocket()) {
UnixDomainSockets.checkPermission();
String[] pa = new String[1]; String[] pa = new String[1];
int n = UnixDomainSockets.accept(fd, newfd, pa); int n = UnixDomainSockets.accept(fd, newfd, pa);
if (n > 0) if (n > 0)
@ -495,16 +485,6 @@ class ServerSocketChannelImpl
try { try {
// newly accepted socket is initially in blocking mode // newly accepted socket is initially in blocking mode
IOUtil.configureBlocking(newfd, true); IOUtil.configureBlocking(newfd, true);
// check permitted to accept connections from the remote address
if (isNetSocket()) {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
InetSocketAddress isa = (InetSocketAddress) sa;
sm.checkAccept(isa.getAddress().getHostAddress(), isa.getPort());
}
}
return new SocketChannelImpl(provider(), family, newfd, sa); return new SocketChannelImpl(provider(), family, newfd, sa);
} catch (Exception e) { } catch (Exception e) {
nd.close(newfd); nd.close(newfd);
@ -749,9 +729,7 @@ class ServerSocketChannelImpl
if (addr == null) { if (addr == null) {
sb.append("unbound"); sb.append("unbound");
} else if (isUnixSocket()) { } else if (isUnixSocket()) {
sb.append(UnixDomainSockets.getRevealedLocalAddressAsString(addr)); sb.append(addr);
} else {
sb.append(Net.getRevealedLocalAddressAsString(addr));
} }
} }
} }

View file

@ -30,8 +30,6 @@ import jdk.internal.event.FileForceEvent;
import java.nio.channels.*; import java.nio.channels.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.io.FileDescriptor; import java.io.FileDescriptor;
import java.io.IOException; import java.io.IOException;

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2000, 2022, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -36,9 +36,6 @@ import java.net.SocketException;
import java.net.SocketOption; import java.net.SocketOption;
import java.net.StandardSocketOptions; import java.net.StandardSocketOptions;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Set; import java.util.Set;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
@ -63,16 +60,10 @@ class SocketAdaptor
this.sc = sc; this.sc = sc;
} }
@SuppressWarnings("removal")
static Socket create(SocketChannelImpl sc) { static Socket create(SocketChannelImpl sc) {
try { try {
if (System.getSecurityManager() == null) { return new SocketAdaptor(sc);
return new SocketAdaptor(sc); } catch (SocketException e) {
} else {
PrivilegedExceptionAction<Socket> pa = () -> new SocketAdaptor(sc);
return AccessController.doPrivileged(pa);
}
} catch (SocketException | PrivilegedActionException e) {
throw new InternalError(e); throw new InternalError(e);
} }
} }
@ -132,7 +123,7 @@ class SocketAdaptor
if (sc.isOpen()) { if (sc.isOpen()) {
InetSocketAddress local = localAddress(); InetSocketAddress local = localAddress();
if (local != null) { if (local != null) {
return Net.getRevealedLocalAddress(local).getAddress(); return local.getAddress();
} }
} }
return new InetSocketAddress(0).getAddress(); return new InetSocketAddress(0).getAddress();
@ -165,7 +156,7 @@ class SocketAdaptor
@Override @Override
public SocketAddress getLocalSocketAddress() { public SocketAddress getLocalSocketAddress() {
return Net.getRevealedLocalAddress(sc.localAddress()); return sc.localAddress();
} }
@Override @Override

View file

@ -243,11 +243,7 @@ class SocketChannelImpl
public SocketAddress getLocalAddress() throws IOException { public SocketAddress getLocalAddress() throws IOException {
synchronized (stateLock) { synchronized (stateLock) {
ensureOpen(); ensureOpen();
if (isUnixSocket()) { return localAddress;
return UnixDomainSockets.getRevealedLocalAddress(localAddress);
} else {
return Net.getRevealedLocalAddress(localAddress);
}
} }
} }
@ -811,7 +807,6 @@ class SocketChannelImpl
} }
private SocketAddress unixBind(SocketAddress local) throws IOException { private SocketAddress unixBind(SocketAddress local) throws IOException {
UnixDomainSockets.checkPermission();
if (local == null) { if (local == null) {
return UnixDomainSockets.unnamed(); return UnixDomainSockets.unnamed();
} else { } else {
@ -833,11 +828,6 @@ class SocketChannelImpl
} else { } else {
isa = Net.checkAddress(local, family); isa = Net.checkAddress(local, family);
} }
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkListen(isa.getPort());
}
NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort()); NetHooks.beforeTcpBind(fd, isa.getAddress(), isa.getPort());
Net.bind(family, fd, isa.getAddress(), isa.getPort()); Net.bind(family, fd, isa.getAddress(), isa.getPort());
return Net.localAddress(fd); return Net.localAddress(fd);
@ -923,15 +913,9 @@ class SocketChannelImpl
*/ */
private SocketAddress checkRemote(SocketAddress sa) { private SocketAddress checkRemote(SocketAddress sa) {
if (isUnixSocket()) { if (isUnixSocket()) {
UnixDomainSockets.checkPermission();
return UnixDomainSockets.checkAddress(sa); return UnixDomainSockets.checkAddress(sa);
} else { } else {
InetSocketAddress isa = Net.checkAddress(sa, family); InetSocketAddress isa = Net.checkAddress(sa, family);
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
}
InetAddress address = isa.getAddress(); InetAddress address = isa.getAddress();
if (address.isAnyLocalAddress()) { if (address.isAnyLocalAddress()) {
int port = isa.getPort(); int port = isa.getPort();
@ -1617,15 +1601,11 @@ class SocketChannelImpl
SocketAddress addr = localAddress(); SocketAddress addr = localAddress();
if (addr != null) { if (addr != null) {
sb.append(" local="); sb.append(" local=");
if (isUnixSocket()) { sb.append(addr);
sb.append(UnixDomainSockets.getRevealedLocalAddressAsString(addr));
} else {
sb.append(Net.getRevealedLocalAddressAsString(addr));
}
} }
if (remoteAddress() != null) { if (remoteAddress() != null) {
sb.append(" remote="); sb.append(" remote=");
sb.append(remoteAddress().toString()); sb.append(remoteAddress());
} }
} }
} }

View file

@ -26,10 +26,6 @@
package sun.nio.ch; package sun.nio.ch;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.security.action.GetPropertyAction;
import sun.security.action.GetIntegerAction;
import jdk.internal.misc.InnocuousThread; import jdk.internal.misc.InnocuousThread;
/** /**
@ -72,24 +68,12 @@ public class ThreadPool {
return poolSize; return poolSize;
} }
@SuppressWarnings("removal")
static ThreadFactory defaultThreadFactory() { static ThreadFactory defaultThreadFactory() {
if (System.getSecurityManager() == null) { return (Runnable r) -> {
return (Runnable r) -> { Thread t = new Thread(r);
Thread t = new Thread(r); t.setDaemon(true);
t.setDaemon(true); return t;
return t; };
};
} else {
return (Runnable r) -> {
PrivilegedAction<Thread> action = () -> {
Thread t = InnocuousThread.newThread(r);
t.setDaemon(true);
return t;
};
return AccessController.doPrivileged(action);
};
}
} }
private static class DefaultThreadPoolHolder { private static class DefaultThreadPoolHolder {
@ -148,9 +132,7 @@ public class ThreadPool {
} }
private static int getDefaultThreadPoolInitialSize() { private static int getDefaultThreadPoolInitialSize() {
@SuppressWarnings("removal") String propValue = System.getProperty(DEFAULT_THREAD_POOL_INITIAL_SIZE);
String propValue = AccessController.doPrivileged(new
GetPropertyAction(DEFAULT_THREAD_POOL_INITIAL_SIZE));
if (propValue != null) { if (propValue != null) {
try { try {
return Integer.parseInt(propValue); return Integer.parseInt(propValue);
@ -163,9 +145,7 @@ public class ThreadPool {
} }
private static ThreadFactory getDefaultThreadPoolThreadFactory() { private static ThreadFactory getDefaultThreadPoolThreadFactory() {
@SuppressWarnings("removal") String propValue = System.getProperty(DEFAULT_THREAD_POOL_THREAD_FACTORY);
String propValue = AccessController.doPrivileged(new
GetPropertyAction(DEFAULT_THREAD_POOL_THREAD_FACTORY));
if (propValue != null) { if (propValue != null) {
try { try {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -59,25 +59,6 @@ class UnixDomainSockets {
return supported; return supported;
} }
static void checkPermission() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(accessUnixDomainSocket);
}
static UnixDomainSocketAddress getRevealedLocalAddress(SocketAddress sa) {
UnixDomainSocketAddress addr = (UnixDomainSocketAddress) sa;
try {
checkPermission();
// Security check passed
} catch (SecurityException e) {
// Return unnamed address only if security check fails
addr = unnamed();
}
return addr;
}
static UnixDomainSocketAddress localAddress(FileDescriptor fd) throws IOException { static UnixDomainSocketAddress localAddress(FileDescriptor fd) throws IOException {
String path = new String(localAddress0(fd), UnixDomainSocketsUtil.getCharset()); String path = new String(localAddress0(fd), UnixDomainSocketsUtil.getCharset());
return UnixDomainSocketAddress.of(path); return UnixDomainSocketAddress.of(path);
@ -85,11 +66,6 @@ class UnixDomainSockets {
private static native byte[] localAddress0(FileDescriptor fd) throws IOException; private static native byte[] localAddress0(FileDescriptor fd) throws IOException;
@SuppressWarnings("removal")
static String getRevealedLocalAddressAsString(SocketAddress sa) {
return (System.getSecurityManager() != null) ? sa.toString() : "";
}
static UnixDomainSocketAddress checkAddress(SocketAddress sa) { static UnixDomainSocketAddress checkAddress(SocketAddress sa) {
if (sa == null) if (sa == null)
throw new NullPointerException(); throw new NullPointerException();

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2000, 2022, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -32,15 +32,12 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer; import java.nio.MappedByteBuffer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.Set; import java.util.Set;
import jdk.internal.misc.TerminatingThreadLocal; import jdk.internal.misc.TerminatingThreadLocal;
import jdk.internal.misc.Unsafe; import jdk.internal.misc.Unsafe;
import sun.security.action.GetPropertyAction;
public class Util { public class Util {
@ -75,7 +72,7 @@ public class Util {
* for potential future-proofing. * for potential future-proofing.
*/ */
private static long getMaxCachedBufferSize() { private static long getMaxCachedBufferSize() {
String s = GetPropertyAction.privilegedGetProperty("jdk.nio.maxCachedBufferSize"); String s = System.getProperty("jdk.nio.maxCachedBufferSize");
if (s != null) { if (s != null) {
try { try {
long m = Long.parseLong(s); long m = Long.parseLong(s);
@ -406,28 +403,23 @@ public class Util {
private static volatile Constructor<?> directByteBufferConstructor; private static volatile Constructor<?> directByteBufferConstructor;
@SuppressWarnings("removal")
private static void initDBBConstructor() { private static void initDBBConstructor() {
AccessController.doPrivileged(new PrivilegedAction<Void>() { try {
public Void run() { Class<?> cl = Class.forName("java.nio.DirectByteBuffer");
try { Constructor<?> ctor = cl.getDeclaredConstructor(
Class<?> cl = Class.forName("java.nio.DirectByteBuffer"); new Class<?>[] { int.class,
Constructor<?> ctor = cl.getDeclaredConstructor( long.class,
new Class<?>[] { int.class, FileDescriptor.class,
long.class, Runnable.class,
FileDescriptor.class, boolean.class, MemorySegment.class });
Runnable.class, ctor.setAccessible(true);
boolean.class, MemorySegment.class}); directByteBufferConstructor = ctor;
ctor.setAccessible(true); } catch (ClassNotFoundException |
directByteBufferConstructor = ctor; NoSuchMethodException |
} catch (ClassNotFoundException | IllegalArgumentException |
NoSuchMethodException | ClassCastException x) {
IllegalArgumentException | throw new InternalError(x);
ClassCastException x) { }
throw new InternalError(x);
}
return null;
}});
} }
static MappedByteBuffer newMappedByteBuffer(int size, long addr, static MappedByteBuffer newMappedByteBuffer(int size, long addr,
@ -455,28 +447,23 @@ public class Util {
private static volatile Constructor<?> directByteBufferRConstructor; private static volatile Constructor<?> directByteBufferRConstructor;
@SuppressWarnings("removal")
private static void initDBBRConstructor() { private static void initDBBRConstructor() {
AccessController.doPrivileged(new PrivilegedAction<Void>() { try {
public Void run() { Class<?> cl = Class.forName("java.nio.DirectByteBufferR");
try { Constructor<?> ctor = cl.getDeclaredConstructor(
Class<?> cl = Class.forName("java.nio.DirectByteBufferR"); new Class<?>[] { int.class,
Constructor<?> ctor = cl.getDeclaredConstructor( long.class,
new Class<?>[] { int.class, FileDescriptor.class,
long.class, Runnable.class,
FileDescriptor.class, boolean.class, MemorySegment.class });
Runnable.class, ctor.setAccessible(true);
boolean.class, MemorySegment.class }); directByteBufferRConstructor = ctor;
ctor.setAccessible(true); } catch (ClassNotFoundException |
directByteBufferRConstructor = ctor; NoSuchMethodException |
} catch (ClassNotFoundException | IllegalArgumentException |
NoSuchMethodException | ClassCastException x) {
IllegalArgumentException | throw new InternalError(x);
ClassCastException x) { }
throw new InternalError(x);
}
return null;
}});
} }
static MappedByteBuffer newMappedByteBufferR(int size, long addr, static MappedByteBuffer newMappedByteBufferR(int size, long addr,

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -28,7 +28,6 @@ package sun.nio.cs;
import java.io.InputStream; import java.io.InputStream;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import java.security.*;
public class CharsetMapping { public class CharsetMapping {
public static final char UNMAPPABLE_DECODING = '\uFFFD'; public static final char UNMAPPABLE_DECODING = '\uFFFD';
@ -129,13 +128,8 @@ public class CharsetMapping {
} }
// init the CharsetMapping object from the .dat binary file // init the CharsetMapping object from the .dat binary file
@SuppressWarnings("removal")
public static CharsetMapping get(final InputStream is) { public static CharsetMapping get(final InputStream is) {
return AccessController.doPrivileged(new PrivilegedAction<>() { return new CharsetMapping().load(is);
public CharsetMapping run() {
return new CharsetMapping().load(is);
}
});
} }
public static class Entry { public static class Entry {

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -26,8 +26,6 @@
package sun.nio.fs; package sun.nio.fs;
import java.nio.file.*; import java.nio.file.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
@ -54,22 +52,14 @@ abstract class AbstractPoller implements Runnable {
/** /**
* Starts the poller thread * Starts the poller thread
*/ */
@SuppressWarnings("removal")
public void start() { public void start() {
final Runnable thisRunnable = this; Thread thr = new Thread(null,
AccessController.doPrivileged(new PrivilegedAction<>() { this,
@Override "FileSystemWatchService",
public Object run() { 0,
Thread thr = new Thread(null, false);
thisRunnable, thr.setDaemon(true);
"FileSystemWatchService", thr.start();
0,
false);
thr.setDaemon(true);
thr.start();
return null;
}
});
} }
/** /**

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -25,9 +25,9 @@
package sun.nio.fs; package sun.nio.fs;
import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.file.attribute.UserDefinedFileAttributeView; import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.io.IOException;
import java.util.*; import java.util.*;
/** /**
@ -39,22 +39,6 @@ abstract class AbstractUserDefinedFileAttributeView
{ {
protected AbstractUserDefinedFileAttributeView() { } protected AbstractUserDefinedFileAttributeView() { }
protected void checkAccess(String file,
boolean checkRead,
boolean checkWrite)
{
assert checkRead || checkWrite;
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (checkRead)
sm.checkRead(file);
if (checkWrite)
sm.checkWrite(file);
sm.checkPermission(new RuntimePermission("accessUserDefinedAttributes"));
}
}
@Override @Override
public final String name() { public final String name() {
return "user"; return "user";

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -36,10 +36,6 @@ import java.nio.file.WatchEvent;
import java.nio.file.WatchKey; import java.nio.file.WatchKey;
import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime; import java.nio.file.attribute.FileTime;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -86,7 +82,6 @@ class PollingWatchService
/** /**
* Register the given file with this watch service * Register the given file with this watch service
*/ */
@SuppressWarnings("removal")
@Override @Override
WatchKey register(final Path path, WatchKey register(final Path path,
WatchEvent.Kind<?>[] events, WatchEvent.Kind<?>[] events,
@ -133,30 +128,9 @@ class PollingWatchService
if (!isOpen()) if (!isOpen())
throw new ClosedWatchServiceException(); throw new ClosedWatchServiceException();
// registration is done in privileged block as it requires the // registers directory returning a new key if not already registered or
// attributes of the entries in the directory. // existing key if already registered
try {
return AccessController.doPrivileged(
new PrivilegedExceptionAction<PollingWatchKey>() {
@Override
public PollingWatchKey run() throws IOException {
return doPrivilegedRegister(path, eventSet);
}
});
} catch (PrivilegedActionException pae) {
Throwable cause = pae.getCause();
if (cause instanceof IOException ioe)
throw ioe;
throw new AssertionError(pae);
}
}
// registers directory returning a new key if not already registered or
// existing key if already registered
private PollingWatchKey doPrivilegedRegister(Path path,
Set<? extends WatchEvent.Kind<?>> events)
throws IOException
{
// check file is a directory and get its file key if possible // check file is a directory and get its file key if possible
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
if (!attrs.isDirectory()) { if (!attrs.isDirectory()) {
@ -183,13 +157,12 @@ class PollingWatchService
watchKey.disable(); watchKey.disable();
} }
} }
watchKey.enable(events); watchKey.enable(eventSet);
return watchKey; return watchKey;
} }
} }
@SuppressWarnings("removal")
@Override @Override
void implClose() throws IOException { void implClose() throws IOException {
synchronized (map) { synchronized (map) {
@ -200,13 +173,7 @@ class PollingWatchService
} }
map.clear(); map.clear();
} }
AccessController.doPrivileged(new PrivilegedAction<Void>() { scheduledExecutor.shutdown();
@Override
public Void run() {
scheduledExecutor.shutdown();
return null;
}
});
} }
/** /**

View file

@ -149,18 +149,6 @@ class InheritedChannel {
} }
} }
/*
* If there's a SecurityManager then check for the appropriate
* RuntimePermission.
*/
private static void checkAccess() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("inheritedChannel"));
}
}
/* /*
* If standard inherited channel is connected to a socket then return a Channel * If standard inherited channel is connected to a socket then return a Channel
* of the appropriate type based standard input. * of the appropriate type based standard input.
@ -252,11 +240,6 @@ class InheritedChannel {
haveChannel = true; haveChannel = true;
} }
// if there is a channel then do the security check before
// returning it.
if (channel != null) {
checkAccess();
}
return channel; return channel;
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -31,9 +31,6 @@ import java.io.IOException;
import java.io.FileDescriptor; import java.io.FileDescriptor;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
/** /**
* Unix implementation of AsynchronousServerSocketChannel * Unix implementation of AsynchronousServerSocketChannel
@ -64,11 +61,6 @@ class UnixAsynchronousServerSocketChannelImpl
private Object acceptAttachment; private Object acceptAttachment;
private PendingFuture<AsynchronousSocketChannel,Object> acceptFuture; private PendingFuture<AsynchronousSocketChannel,Object> acceptFuture;
// context for permission check when security manager set
@SuppressWarnings("removal")
private AccessControlContext acceptAcc;
UnixAsynchronousServerSocketChannelImpl(Port port) UnixAsynchronousServerSocketChannelImpl(Port port)
throws IOException throws IOException
{ {
@ -165,9 +157,9 @@ class UnixAsynchronousServerSocketChannelImpl
AsynchronousSocketChannel child = null; AsynchronousSocketChannel child = null;
if (exc == null) { if (exc == null) {
try { try {
child = finishAccept(newfd, isaa[0], acceptAcc); child = finishAccept(newfd, isaa[0]);
} catch (Throwable x) { } catch (Throwable x) {
if (!(x instanceof IOException) && !(x instanceof SecurityException)) if (!(x instanceof IOException))
x = new IOException(x); x = new IOException(x);
exc = x; exc = x;
} }
@ -198,14 +190,12 @@ class UnixAsynchronousServerSocketChannelImpl
/** /**
* Completes the accept by creating the AsynchronousSocketChannel for * Completes the accept by creating the AsynchronousSocketChannel for
* the given file descriptor and remote address. If this method completes * the given file descriptor and remote address. If this method completes
* with an IOException or SecurityException then the channel/file descriptor * with an IOException then the channel/file descriptor
* will be closed. * will be closed.
*/ */
@SuppressWarnings("removal")
private AsynchronousSocketChannel finishAccept(FileDescriptor newfd, private AsynchronousSocketChannel finishAccept(FileDescriptor newfd,
final InetSocketAddress remote, final InetSocketAddress remote)
AccessControlContext acc) throws IOException
throws IOException, SecurityException
{ {
AsynchronousSocketChannel ch = null; AsynchronousSocketChannel ch = null;
try { try {
@ -215,38 +205,9 @@ class UnixAsynchronousServerSocketChannelImpl
throw x; throw x;
} }
// permission check must always be in initiator's context
try {
if (acc != null) {
AccessController.doPrivileged(new PrivilegedAction<>() {
public Void run() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkAccept(remote.getAddress().getHostAddress(),
remote.getPort());
}
return null;
}
}, acc);
} else {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkAccept(remote.getAddress().getHostAddress(),
remote.getPort());
}
}
} catch (SecurityException x) {
try {
ch.close();
} catch (Throwable suppressed) {
x.addSuppressed(suppressed);
}
throw x;
}
return ch; return ch;
} }
@SuppressWarnings("removal")
@Override @Override
Future<AsynchronousSocketChannel> implAccept(Object att, Future<AsynchronousSocketChannel> implAccept(Object att,
CompletionHandler<AsynchronousSocketChannel,Object> handler) CompletionHandler<AsynchronousSocketChannel,Object> handler)
@ -283,9 +244,6 @@ class UnixAsynchronousServerSocketChannelImpl
int n = Net.accept(this.fd, newfd, isaa); int n = Net.accept(this.fd, newfd, isaa);
if (n == IOStatus.UNAVAILABLE) { if (n == IOStatus.UNAVAILABLE) {
// need calling context when there is security manager as
// permission check may be done in a different thread without
// any application call frames on the stack
PendingFuture<AsynchronousSocketChannel,Object> result = null; PendingFuture<AsynchronousSocketChannel,Object> result = null;
synchronized (updateLock) { synchronized (updateLock) {
if (handler == null) { if (handler == null) {
@ -296,8 +254,6 @@ class UnixAsynchronousServerSocketChannelImpl
this.acceptHandler = handler; this.acceptHandler = handler;
this.acceptAttachment = att; this.acceptAttachment = att;
} }
this.acceptAcc = (System.getSecurityManager() == null) ?
null : AccessController.getContext();
this.acceptPending = true; this.acceptPending = true;
} }
@ -318,7 +274,7 @@ class UnixAsynchronousServerSocketChannelImpl
if (exc == null) { if (exc == null) {
// connection accepted immediately // connection accepted immediately
try { try {
child = finishAccept(newfd, isaa[0], null); child = finishAccept(newfd, isaa[0]);
} catch (Throwable x) { } catch (Throwable x) {
exc = x; exc = x;
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -35,7 +35,6 @@ import java.io.FileDescriptor;
import sun.net.ConnectionResetException; import sun.net.ConnectionResetException;
import sun.net.NetHooks; import sun.net.NetHooks;
import sun.net.util.SocketExceptions; import sun.net.util.SocketExceptions;
import sun.security.action.GetPropertyAction;
/** /**
* Unix implementation of AsynchronousSocketChannel * Unix implementation of AsynchronousSocketChannel
@ -49,7 +48,7 @@ class UnixAsynchronousSocketChannelImpl
private static final boolean disableSynchronousRead; private static final boolean disableSynchronousRead;
static { static {
String propValue = GetPropertyAction.privilegedGetProperty( String propValue = System.getProperty(
"sun.nio.ch.disableSynchronousRead", "false"); "sun.nio.ch.disableSynchronousRead", "false");
disableSynchronousRead = propValue.isEmpty() ? disableSynchronousRead = propValue.isEmpty() ?
true : Boolean.parseBoolean(propValue); true : Boolean.parseBoolean(propValue);
@ -309,12 +308,6 @@ class UnixAsynchronousSocketChannelImpl
InetSocketAddress isa = Net.checkAddress(remote); InetSocketAddress isa = Net.checkAddress(remote);
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
// check and set state // check and set state
boolean notifyBeforeTcpConnect; boolean notifyBeforeTcpConnect;
synchronized (stateLock) { synchronized (stateLock) {

View file

@ -26,8 +26,6 @@
package sun.nio.ch; package sun.nio.ch;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.net.NetProperties; import sun.net.NetProperties;
import jdk.internal.util.StaticProperty; import jdk.internal.util.StaticProperty;
@ -51,16 +49,12 @@ class UnixDomainSocketsUtil {
* 2. ${jdk.net.unixdomain.tmpdir} if set as net property * 2. ${jdk.net.unixdomain.tmpdir} if set as net property
* 3. ${java.io.tmpdir} system property * 3. ${java.io.tmpdir} system property
*/ */
@SuppressWarnings("removal")
static String getTempDir() { static String getTempDir() {
PrivilegedAction<String> action = () -> { String s = NetProperties.get("jdk.net.unixdomain.tmpdir");
String s = NetProperties.get("jdk.net.unixdomain.tmpdir"); if (s != null && s.length() > 0) {
if (s != null && s.length() > 0) { return s;
return s; } else {
} else { return StaticProperty.javaIoTmpDir();
return StaticProperty.javaIoTmpDir(); }
}
};
return AccessController.doPrivileged(action);
} }
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -29,8 +29,6 @@ import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -93,19 +91,13 @@ class MimeTypesFileTypeDetector extends AbstractFileTypeDetector {
if (!loaded) { if (!loaded) {
synchronized (this) { synchronized (this) {
if (!loaded) { if (!loaded) {
@SuppressWarnings("removal") List<String> lines;
List<String> lines = AccessController.doPrivileged( try {
new PrivilegedAction<>() { lines = Files.readAllLines(mimeTypesFile,
@Override Charset.defaultCharset());
public List<String> run() { } catch (IOException ignore) {
try { lines = Collections.emptyList();
return Files.readAllLines(mimeTypesFile, }
Charset.defaultCharset());
} catch (IOException ignore) {
return Collections.emptyList();
}
}
});
mimeTypeMap = HashMap.newHashMap(lines.size()); mimeTypeMap = HashMap.newHashMap(lines.size());
String entry = ""; String entry = "";

View file

@ -25,9 +25,9 @@
package sun.nio.fs; package sun.nio.fs;
import java.io.FileDescriptor;
import java.nio.file.*; import java.nio.file.*;
import java.nio.channels.*; import java.nio.channels.*;
import java.io.FileDescriptor;
import java.util.Set; import java.util.Set;
import jdk.internal.access.SharedSecrets; import jdk.internal.access.SharedSecrets;
@ -108,7 +108,6 @@ class UnixChannelFactory {
*/ */
static FileChannel newFileChannel(int dfd, static FileChannel newFileChannel(int dfd,
UnixPath path, UnixPath path,
String pathForPermissionCheck,
Set<? extends OpenOption> options, Set<? extends OpenOption> options,
int mode) int mode)
throws UnixException throws UnixException
@ -130,7 +129,7 @@ class UnixChannelFactory {
if (flags.append && flags.truncateExisting) if (flags.append && flags.truncateExisting)
throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed"); throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
FileDescriptor fdObj = open(dfd, path, pathForPermissionCheck, flags, mode); FileDescriptor fdObj = open(dfd, path, flags, mode);
return FileChannelImpl.open(fdObj, path.toString(), flags.read, flags.write, return FileChannelImpl.open(fdObj, path.toString(), flags.read, flags.write,
(flags.sync || flags.dsync), flags.direct, null); (flags.sync || flags.dsync), flags.direct, null);
} }
@ -143,7 +142,7 @@ class UnixChannelFactory {
int mode) int mode)
throws UnixException throws UnixException
{ {
return newFileChannel(-1, path, null, options, mode); return newFileChannel(-1, path, options, mode);
} }
/** /**
@ -167,7 +166,7 @@ class UnixChannelFactory {
throw new UnsupportedOperationException("APPEND not allowed"); throw new UnsupportedOperationException("APPEND not allowed");
// for now use simple implementation // for now use simple implementation
FileDescriptor fdObj = open(-1, path, null, flags, mode); FileDescriptor fdObj = open(-1, path, flags, mode);
return SimpleAsynchronousFileChannelImpl.open(fdObj, path.toString(), flags.read, flags.write, pool); return SimpleAsynchronousFileChannelImpl.open(fdObj, path.toString(), flags.read, flags.write, pool);
} }
@ -177,7 +176,6 @@ class UnixChannelFactory {
*/ */
protected static FileDescriptor open(int dfd, protected static FileDescriptor open(int dfd,
UnixPath path, UnixPath path,
String pathForPermissionCheck,
Flags flags, Flags flags,
int mode) int mode)
throws UnixException throws UnixException
@ -236,20 +234,6 @@ class UnixChannelFactory {
if (flags.direct) if (flags.direct)
oflags |= O_DIRECT; oflags |= O_DIRECT;
// permission check before we open the file
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (pathForPermissionCheck == null)
pathForPermissionCheck = path.getPathForPermissionCheck();
if (flags.read)
sm.checkRead(pathForPermissionCheck);
if (flags.write)
sm.checkWrite(pathForPermissionCheck);
if (flags.deleteOnClose)
sm.checkDelete(pathForPermissionCheck);
}
int fd; int fd;
try { try {
if (dfd >= 0) { if (dfd >= 0) {

View file

@ -25,11 +25,11 @@
package sun.nio.fs; package sun.nio.fs;
import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;
import java.nio.file.attribute.*; import java.nio.file.attribute.*;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.io.IOException;
import static sun.nio.fs.UnixConstants.*; import static sun.nio.fs.UnixConstants.*;
import static sun.nio.fs.UnixNativeDispatcher.*; import static sun.nio.fs.UnixNativeDispatcher.*;
@ -47,7 +47,6 @@ class UnixFileAttributeViews {
@Override @Override
public BasicFileAttributes readAttributes() throws IOException { public BasicFileAttributes readAttributes() throws IOException {
file.checkRead();
try { try {
UnixFileAttributes attrs = UnixFileAttributes attrs =
UnixFileAttributes.get(file, followLinks); UnixFileAttributes.get(file, followLinks);
@ -69,9 +68,6 @@ class UnixFileAttributeViews {
return; return;
} }
// permission check
file.checkWrite();
// use a file descriptor if possible to avoid a race due to // use a file descriptor if possible to avoid a race due to
// accessing a path more than once as the file at that path could // accessing a path more than once as the file at that path could
// change. // change.
@ -156,24 +152,6 @@ class UnixFileAttributeViews {
super(file, followLinks); super(file, followLinks);
} }
final void checkReadExtended() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
file.checkRead();
sm.checkPermission(new RuntimePermission("accessUserInformation"));
}
}
final void checkWriteExtended() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
file.checkWrite();
sm.checkPermission(new RuntimePermission("accessUserInformation"));
}
}
@Override @Override
public String name() { public String name() {
return "posix"; return "posix";
@ -228,7 +206,6 @@ class UnixFileAttributeViews {
@Override @Override
public UnixFileAttributes readAttributes() throws IOException { public UnixFileAttributes readAttributes() throws IOException {
checkReadExtended();
try { try {
return UnixFileAttributes.get(file, followLinks); return UnixFileAttributes.get(file, followLinks);
} catch (UnixException x) { } catch (UnixException x) {
@ -239,8 +216,6 @@ class UnixFileAttributeViews {
// chmod // chmod
final void setMode(int mode) throws IOException { final void setMode(int mode) throws IOException {
checkWriteExtended();
if (followLinks) { if (followLinks) {
try { try {
chmod(file, mode); chmod(file, mode);
@ -283,7 +258,6 @@ class UnixFileAttributeViews {
// chown // chown
final void setOwners(int uid, int gid) throws IOException { final void setOwners(int uid, int gid) throws IOException {
checkWriteExtended();
try { try {
if (followLinks) { if (followLinks) {
chown(file, uid, gid); chown(file, uid, gid);

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -34,8 +34,6 @@ import java.nio.file.attribute.*;
import java.nio.channels.*; import java.nio.channels.*;
import java.util.*; import java.util.*;
import java.io.IOException; import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
/** /**
* Base implementation of FileStore for Unix/like implementations. * Base implementation of FileStore for Unix/like implementations.
@ -269,17 +267,11 @@ abstract class UnixFileStore
/** /**
* Returns status to indicate if file system supports a given feature * Returns status to indicate if file system supports a given feature
*/ */
@SuppressWarnings("removal")
FeatureStatus checkIfFeaturePresent(String feature) { FeatureStatus checkIfFeaturePresent(String feature) {
if (props == null) { if (props == null) {
synchronized (loadLock) { synchronized (loadLock) {
if (props == null) { if (props == null) {
props = AccessController.doPrivileged( props = loadProperties();
new PrivilegedAction<>() {
@Override
public Properties run() {
return loadProperties();
}});
} }
} }
} }

View file

@ -34,7 +34,6 @@ import java.nio.file.FileStore;
import java.nio.file.FileSystem; import java.nio.file.FileSystem;
import java.nio.file.FileSystemException; import java.nio.file.FileSystemException;
import java.nio.file.LinkOption; import java.nio.file.LinkOption;
import java.nio.file.LinkPermission;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.PathMatcher; import java.nio.file.PathMatcher;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
@ -54,7 +53,6 @@ import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import sun.nio.ch.DirectBuffer; import sun.nio.ch.DirectBuffer;
import sun.nio.ch.IOStatus; import sun.nio.ch.IOStatus;
import sun.security.action.GetPropertyAction;
import static sun.nio.fs.UnixConstants.*; import static sun.nio.fs.UnixConstants.*;
import static sun.nio.fs.UnixNativeDispatcher.*; import static sun.nio.fs.UnixNativeDispatcher.*;
@ -87,8 +85,7 @@ abstract class UnixFileSystem
// if process-wide chdir is allowed or default directory is not the // if process-wide chdir is allowed or default directory is not the
// process working directory then paths must be resolved against the // process working directory then paths must be resolved against the
// default directory. // default directory.
String propValue = GetPropertyAction String propValue = System.getProperty("sun.nio.fs.chdirAllowed", "false");
.privilegedGetProperty("sun.nio.fs.chdirAllowed", "false");
boolean chdirAllowed = propValue.isEmpty() ? true : Boolean.parseBoolean(propValue); boolean chdirAllowed = propValue.isEmpty() ? true : Boolean.parseBoolean(propValue);
if (chdirAllowed) { if (chdirAllowed) {
this.needToResolveAgainstDefaultDirectory = true; this.needToResolveAgainstDefaultDirectory = true;
@ -179,20 +176,7 @@ abstract class UnixFileSystem
*/ */
@Override @Override
public final Iterable<Path> getRootDirectories() { public final Iterable<Path> getRootDirectories() {
final List<Path> allowedList = List.of(rootDirectory); return List.of(rootDirectory);
return new Iterable<>() {
public Iterator<Path> iterator() {
try {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkRead(rootDirectory.toString());
return allowedList.iterator();
} catch (SecurityException x) {
return Collections.emptyIterator(); //disallowed
}
}
};
} }
/** /**
@ -228,16 +212,6 @@ abstract class UnixFileSystem
if (entry.isIgnored()) if (entry.isIgnored())
continue; continue;
// check permission to read mount point
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkRead(Util.toString(entry.dir()));
} catch (SecurityException x) {
continue;
}
}
try { try {
return getFileStore(entry); return getFileStore(entry);
} catch (IOException ignore) { } catch (IOException ignore) {
@ -275,20 +249,7 @@ abstract class UnixFileSystem
@Override @Override
public final Iterable<FileStore> getFileStores() { public final Iterable<FileStore> getFileStores() {
@SuppressWarnings("removal") return FileStoreIterator::new;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkPermission(new RuntimePermission("getFileStoreAttributes"));
} catch (SecurityException se) {
return Collections.emptyList();
}
}
return new Iterable<>() {
public Iterator<FileStore> iterator() {
return new FileStoreIterator();
}
};
} }
@Override @Override
@ -845,14 +806,6 @@ abstract class UnixFileSystem
void move(UnixPath source, UnixPath target, CopyOption... options) void move(UnixPath source, UnixPath target, CopyOption... options)
throws IOException throws IOException
{ {
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
source.checkWrite();
target.checkWrite();
}
// translate options into flags // translate options into flags
Flags flags = Flags.fromMoveOptions(options); Flags flags = Flags.fromMoveOptions(options);
@ -988,14 +941,6 @@ abstract class UnixFileSystem
final UnixPath target, final UnixPath target,
CopyOption... options) throws IOException CopyOption... options) throws IOException
{ {
// permission checks
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
source.checkRead();
target.checkWrite();
}
// translate options into flags // translate options into flags
final Flags flags = Flags.fromCopyOptions(options); final Flags flags = Flags.fromCopyOptions(options);
@ -1009,11 +954,6 @@ abstract class UnixFileSystem
x.rethrowAsIOException(source); x.rethrowAsIOException(source);
} }
// if source file is symbolic link then we must check LinkPermission
if (sm != null && sourceAttrs.isSymbolicLink()) {
sm.checkPermission(new LinkPermission("symbolic"));
}
// ensure source can be copied // ensure source can be copied
if (!sourceAttrs.isSymbolicLink() || flags.followLinks) { if (!sourceAttrs.isSymbolicLink() || flags.followLinks) {
// the access(2) system call always follows links so it // the access(2) system call always follows links so it

View file

@ -40,7 +40,6 @@ import java.nio.file.FileStore;
import java.nio.file.FileSystem; import java.nio.file.FileSystem;
import java.nio.file.FileSystemAlreadyExistsException; import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.LinkOption; import java.nio.file.LinkOption;
import java.nio.file.LinkPermission;
import java.nio.file.NotDirectoryException; import java.nio.file.NotDirectoryException;
import java.nio.file.NotLinkException; import java.nio.file.NotLinkException;
import java.nio.file.OpenOption; import java.nio.file.OpenOption;
@ -59,7 +58,6 @@ import java.util.concurrent.ExecutorService;
import jdk.internal.util.StaticProperty; import jdk.internal.util.StaticProperty;
import sun.nio.ch.ThreadPool; import sun.nio.ch.ThreadPool;
import sun.security.util.SecurityConstants;
import static sun.nio.fs.UnixNativeDispatcher.*; import static sun.nio.fs.UnixNativeDispatcher.*;
import static sun.nio.fs.UnixConstants.*; import static sun.nio.fs.UnixConstants.*;
@ -171,7 +169,6 @@ public abstract class UnixFileSystemProvider
{ {
if (type == BasicFileAttributes.class && Util.followLinks(options)) { if (type == BasicFileAttributes.class && Util.followLinks(options)) {
UnixPath file = UnixPath.toUnixPath(path); UnixPath file = UnixPath.toUnixPath(path);
file.checkRead();
try { try {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
A attrs = (A) UnixFileAttributes.getIfExists(file); A attrs = (A) UnixFileAttributes.getIfExists(file);
@ -250,7 +247,6 @@ public abstract class UnixFileSystemProvider
@Override @Override
boolean implDelete(Path obj, boolean failIfNotExists) throws IOException { boolean implDelete(Path obj, boolean failIfNotExists) throws IOException {
UnixPath file = UnixPath.toUnixPath(obj); UnixPath file = UnixPath.toUnixPath(obj);
file.checkDelete();
// need file attributes to know if file is directory // need file attributes to know if file is directory
UnixFileAttributes attrs = null; UnixFileAttributes attrs = null;
@ -317,20 +313,12 @@ public abstract class UnixFileSystemProvider
int mode = 0; int mode = 0;
if (e || r) { if (e || r) {
file.checkRead();
mode |= (r) ? R_OK : F_OK; mode |= (r) ? R_OK : F_OK;
} }
if (w) { if (w) {
file.checkWrite();
mode |= W_OK; mode |= W_OK;
} }
if (x) { if (x) {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// not cached
sm.checkExec(file.getPathForPermissionCheck());
}
mode |= X_OK; mode |= X_OK;
} }
int errno = access(file, mode); int errno = access(file, mode);
@ -341,26 +329,18 @@ public abstract class UnixFileSystemProvider
@Override @Override
public boolean isReadable(Path path) { public boolean isReadable(Path path) {
UnixPath file = UnixPath.toUnixPath(path); UnixPath file = UnixPath.toUnixPath(path);
file.checkRead();
return access(file, R_OK) == 0; return access(file, R_OK) == 0;
} }
@Override @Override
public boolean isWritable(Path path) { public boolean isWritable(Path path) {
UnixPath file = UnixPath.toUnixPath(path); UnixPath file = UnixPath.toUnixPath(path);
file.checkWrite();
return access(file, W_OK) == 0; return access(file, W_OK) == 0;
} }
@Override @Override
public boolean isExecutable(Path path) { public boolean isExecutable(Path path) {
UnixPath file = UnixPath.toUnixPath(path); UnixPath file = UnixPath.toUnixPath(path);
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// not cached
sm.checkExec(file.getPathForPermissionCheck());
}
return access(file, X_OK) == 0; return access(file, X_OK) == 0;
} }
@ -374,10 +354,6 @@ public abstract class UnixFileSystemProvider
if (!(obj2 instanceof UnixPath file2)) if (!(obj2 instanceof UnixPath file2))
return false; return false;
// check security manager access to both files
file1.checkRead();
file2.checkRead();
UnixFileAttributes attrs1; UnixFileAttributes attrs1;
UnixFileAttributes attrs2; UnixFileAttributes attrs2;
try { try {
@ -398,7 +374,6 @@ public abstract class UnixFileSystemProvider
@Override @Override
public boolean isHidden(Path obj) { public boolean isHidden(Path obj) {
UnixPath file = UnixPath.toUnixPath(obj); UnixPath file = UnixPath.toUnixPath(obj);
file.checkRead();
UnixPath name = file.getFileName(); UnixPath name = file.getFileName();
if (name == null) if (name == null)
return false; return false;
@ -421,12 +396,6 @@ public abstract class UnixFileSystemProvider
@Override @Override
public FileStore getFileStore(Path obj) throws IOException { public FileStore getFileStore(Path obj) throws IOException {
UnixPath file = UnixPath.toUnixPath(obj); UnixPath file = UnixPath.toUnixPath(obj);
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("getFileStoreAttributes"));
file.checkRead();
}
return getFileStore(file); return getFileStore(file);
} }
@ -435,7 +404,6 @@ public abstract class UnixFileSystemProvider
throws IOException throws IOException
{ {
UnixPath dir = UnixPath.toUnixPath(obj); UnixPath dir = UnixPath.toUnixPath(obj);
dir.checkWrite();
int mode = UnixFileModeAttribute.toUnixMode(UnixFileModeAttribute.ALL_PERMISSIONS, attrs); int mode = UnixFileModeAttribute.toUnixMode(UnixFileModeAttribute.ALL_PERMISSIONS, attrs);
try { try {
@ -453,7 +421,6 @@ public abstract class UnixFileSystemProvider
throws IOException throws IOException
{ {
UnixPath dir = UnixPath.toUnixPath(obj); UnixPath dir = UnixPath.toUnixPath(obj);
dir.checkRead();
if (filter == null) if (filter == null)
throw new NullPointerException(); throw new NullPointerException();
@ -506,14 +473,6 @@ public abstract class UnixFileSystemProvider
" not supported when creating symbolic link"); " not supported when creating symbolic link");
} }
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new LinkPermission("symbolic"));
link.checkWrite();
}
// create link // create link
try { try {
symlink(target.asByteArray(), link); symlink(target.asByteArray(), link);
@ -527,14 +486,6 @@ public abstract class UnixFileSystemProvider
UnixPath link = UnixPath.toUnixPath(obj1); UnixPath link = UnixPath.toUnixPath(obj1);
UnixPath existing = UnixPath.toUnixPath(obj2); UnixPath existing = UnixPath.toUnixPath(obj2);
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new LinkPermission("hard"));
link.checkWrite();
existing.checkWrite();
}
try { try {
link(existing, link); link(existing, link);
} catch (UnixException x) { } catch (UnixException x) {
@ -545,14 +496,6 @@ public abstract class UnixFileSystemProvider
@Override @Override
public Path readSymbolicLink(Path obj1) throws IOException { public Path readSymbolicLink(Path obj1) throws IOException {
UnixPath link = UnixPath.toUnixPath(obj1); UnixPath link = UnixPath.toUnixPath(obj1);
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
FilePermission perm = new FilePermission(link.getPathForPermissionCheck(),
SecurityConstants.FILE_READLINK_ACTION);
sm.checkPermission(perm);
}
try { try {
byte[] target = readlink(link); byte[] target = readlink(link);
return new UnixPath(link.getFileSystem(), target); return new UnixPath(link.getFileSystem(), target);
@ -568,7 +511,6 @@ public abstract class UnixFileSystemProvider
public boolean exists(Path path, LinkOption... options) { public boolean exists(Path path, LinkOption... options) {
if (Util.followLinks(options)) { if (Util.followLinks(options)) {
UnixPath file = UnixPath.toUnixPath(path); UnixPath file = UnixPath.toUnixPath(path);
file.checkRead();
return access(file, F_OK) == 0; return access(file, F_OK) == 0;
} else { } else {
return super.exists(path, options); return super.exists(path, options);

View file

@ -833,47 +833,18 @@ class UnixPath implements Path {
return open(this, flags, 0); return open(this, flags, 0);
} }
void checkRead() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkRead(getPathForPermissionCheck());
}
void checkWrite() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkWrite(getPathForPermissionCheck());
}
void checkDelete() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkDelete(getPathForPermissionCheck());
}
@Override @Override
public UnixPath toAbsolutePath() { public UnixPath toAbsolutePath() {
if (isAbsolute()) { if (isAbsolute()) {
return this; return this;
} }
// The path is relative so need to resolve against default directory, // The path is relative so need to resolve against default directory
// taking care not to reveal the user.dir
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPropertyAccess("user.dir");
}
return new UnixPath(getFileSystem(), return new UnixPath(getFileSystem(),
resolve(getFileSystem().defaultDirectory(), path)); resolve(getFileSystem().defaultDirectory(), path));
} }
@Override @Override
public Path toRealPath(LinkOption... options) throws IOException { public Path toRealPath(LinkOption... options) throws IOException {
checkRead();
UnixPath absolute = toAbsolutePath(); UnixPath absolute = toAbsolutePath();
// if resolving links then use realpath // if resolving links then use realpath
@ -1022,7 +993,6 @@ class UnixPath implements Path {
throw new NullPointerException(); throw new NullPointerException();
if (!(watcher instanceof AbstractWatchService)) if (!(watcher instanceof AbstractWatchService))
throw new ProviderMismatchException(); throw new ProviderMismatchException();
checkRead();
return ((AbstractWatchService)watcher).register(this, events, modifiers); return ((AbstractWatchService)watcher).register(this, events, modifiers);
} }
} }

View file

@ -25,12 +25,12 @@
package sun.nio.fs; package sun.nio.fs;
import java.io.IOException;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.*; import java.nio.file.*;
import java.nio.file.attribute.*; import java.nio.file.attribute.*;
import java.nio.channels.SeekableByteChannel;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.io.IOException;
import static sun.nio.fs.UnixNativeDispatcher.*; import static sun.nio.fs.UnixNativeDispatcher.*;
import static sun.nio.fs.UnixConstants.*; import static sun.nio.fs.UnixConstants.*;
@ -93,13 +93,6 @@ class UnixSecureDirectoryStream
UnixPath child = ds.directory().resolve(file); UnixPath child = ds.directory().resolve(file);
boolean followLinks = Util.followLinks(options); boolean followLinks = Util.followLinks(options);
// permission check using name resolved against original path of directory
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
child.checkRead();
}
ds.readLock().lock(); ds.readLock().lock();
try { try {
if (!ds.isOpen()) if (!ds.isOpen())
@ -146,15 +139,12 @@ class UnixSecureDirectoryStream
int mode = UnixFileModeAttribute int mode = UnixFileModeAttribute
.toUnixMode(UnixFileModeAttribute.ALL_READWRITE, attrs); .toUnixMode(UnixFileModeAttribute.ALL_READWRITE, attrs);
// path for permission check
String pathToCheck = ds.directory().resolve(file).getPathForPermissionCheck();
ds.readLock().lock(); ds.readLock().lock();
try { try {
if (!ds.isOpen()) if (!ds.isOpen())
throw new ClosedDirectoryStreamException(); throw new ClosedDirectoryStreamException();
try { try {
return UnixChannelFactory.newFileChannel(dfd, file, pathToCheck, options, mode); return UnixChannelFactory.newFileChannel(dfd, file, options, mode);
} catch (UnixException x) { } catch (UnixException x) {
x.rethrowAsIOException(file); x.rethrowAsIOException(file);
return null; // keep compiler happy return null; // keep compiler happy
@ -173,13 +163,6 @@ class UnixSecureDirectoryStream
{ {
UnixPath file = getName(obj); UnixPath file = getName(obj);
// permission check using name resolved against original path of directory
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ds.directory().resolve(file).checkDelete();
}
ds.readLock().lock(); ds.readLock().lock();
try { try {
if (!ds.isOpen()) if (!ds.isOpen())
@ -239,14 +222,6 @@ class UnixSecureDirectoryStream
throw new ProviderMismatchException(); throw new ProviderMismatchException();
UnixSecureDirectoryStream that = (UnixSecureDirectoryStream)dir; UnixSecureDirectoryStream that = (UnixSecureDirectoryStream)dir;
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
this.ds.directory().resolve(from).checkWrite();
that.ds.directory().resolve(to).checkWrite();
}
// lock ordering doesn't matter // lock ordering doesn't matter
this.ds.readLock().lock(); this.ds.readLock().lock();
try { try {
@ -337,18 +312,6 @@ class UnixSecureDirectoryStream
} }
} }
private void checkWriteAccess() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (file == null) {
ds.directory().checkWrite();
} else {
ds.directory().resolve(file).checkWrite();
}
}
}
@Override @Override
public String name() { public String name() {
return "basic"; return "basic";
@ -361,15 +324,6 @@ class UnixSecureDirectoryStream
if (!ds.isOpen()) if (!ds.isOpen())
throw new ClosedDirectoryStreamException(); throw new ClosedDirectoryStreamException();
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (file == null) {
ds.directory().checkRead();
} else {
ds.directory().resolve(file).checkRead();
}
}
try { try {
UnixFileAttributes attrs = (file == null) ? UnixFileAttributes attrs = (file == null) ?
UnixFileAttributes.get(dfd) : UnixFileAttributes.get(dfd) :
@ -392,8 +346,6 @@ class UnixSecureDirectoryStream
FileTime createTime) // ignore FileTime createTime) // ignore
throws IOException throws IOException
{ {
checkWriteAccess();
ds.readLock().lock(); ds.readLock().lock();
try { try {
if (!ds.isOpen()) if (!ds.isOpen())
@ -441,15 +393,6 @@ class UnixSecureDirectoryStream
super(file, followLinks); super(file, followLinks);
} }
private void checkWriteAndUserAccess() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
super.checkWriteAccess();
sm.checkPermission(new RuntimePermission("accessUserInformation"));
}
}
@Override @Override
public String name() { public String name() {
return "posix"; return "posix";
@ -457,16 +400,6 @@ class UnixSecureDirectoryStream
@Override @Override
public PosixFileAttributes readAttributes() throws IOException { public PosixFileAttributes readAttributes() throws IOException {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (file == null)
ds.directory().checkRead();
else
ds.directory().resolve(file).checkRead();
sm.checkPermission(new RuntimePermission("accessUserInformation"));
}
ds.readLock().lock(); ds.readLock().lock();
try { try {
if (!ds.isOpen()) if (!ds.isOpen())
@ -490,9 +423,6 @@ class UnixSecureDirectoryStream
public void setPermissions(Set<PosixFilePermission> perms) public void setPermissions(Set<PosixFilePermission> perms)
throws IOException throws IOException
{ {
// permission check
checkWriteAndUserAccess();
ds.readLock().lock(); ds.readLock().lock();
try { try {
if (!ds.isOpen()) if (!ds.isOpen())
@ -513,9 +443,6 @@ class UnixSecureDirectoryStream
} }
private void setOwners(int uid, int gid) throws IOException { private void setOwners(int uid, int gid) throws IOException {
// permission check
checkWriteAndUserAccess();
ds.readLock().lock(); ds.readLock().lock();
try { try {
if (!ds.isOpen()) if (!ds.isOpen())

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -121,12 +121,11 @@ class UnixUriUtils {
// trailing slash if directory // trailing slash if directory
if (sb.charAt(sb.length()-1) != '/') { if (sb.charAt(sb.length()-1) != '/') {
try { try {
up.checkRead();
UnixFileAttributes attrs = UnixFileAttributes.getIfExists(up); UnixFileAttributes attrs = UnixFileAttributes.getIfExists(up);
if (attrs != null if (attrs != null
&& ((attrs.mode() & UnixConstants.S_IFMT) == UnixConstants.S_IFDIR)) && ((attrs.mode() & UnixConstants.S_IFMT) == UnixConstants.S_IFDIR))
sb.append('/'); sb.append('/');
} catch (UnixException | SecurityException ignore) { } } catch (UnixException ignore) { }
} }
try { try {

View file

@ -25,9 +25,9 @@
package sun.nio.fs; package sun.nio.fs;
import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.io.IOException;
import java.util.*; import java.util.*;
import jdk.internal.access.JavaNioAccess; import jdk.internal.access.JavaNioAccess;
@ -114,12 +114,8 @@ abstract class UnixUserDefinedFileAttributeView
} }
} }
@SuppressWarnings("removal")
@Override @Override
public List<String> list() throws IOException { public List<String> list() throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), true, false);
int fd = -1; int fd = -1;
try { try {
fd = file.openForAttributeAccess(followLinks); fd = file.openForAttributeAccess(followLinks);
@ -141,12 +137,8 @@ abstract class UnixUserDefinedFileAttributeView
} }
} }
@SuppressWarnings("removal")
@Override @Override
public int size(String name) throws IOException { public int size(String name) throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), true, false);
int fd = -1; int fd = -1;
try { try {
fd = file.openForAttributeAccess(followLinks); fd = file.openForAttributeAccess(followLinks);
@ -165,12 +157,8 @@ abstract class UnixUserDefinedFileAttributeView
} }
} }
@SuppressWarnings("removal")
@Override @Override
public int read(String name, ByteBuffer dst) throws IOException { public int read(String name, ByteBuffer dst) throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), true, false);
if (dst.isReadOnly()) if (dst.isReadOnly())
throw new IllegalArgumentException("Read-only buffer"); throw new IllegalArgumentException("Read-only buffer");
int pos = dst.position(); int pos = dst.position();
@ -230,12 +218,8 @@ abstract class UnixUserDefinedFileAttributeView
} }
} }
@SuppressWarnings("removal")
@Override @Override
public int write(String name, ByteBuffer src) throws IOException { public int write(String name, ByteBuffer src) throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), false, true);
int pos = src.position(); int pos = src.position();
int lim = src.limit(); int lim = src.limit();
assert (pos <= lim); assert (pos <= lim);
@ -293,12 +277,8 @@ abstract class UnixUserDefinedFileAttributeView
} }
} }
@SuppressWarnings("removal")
@Override @Override
public void delete(String name) throws IOException { public void delete(String name) throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), false, true);
int fd = -1; int fd = -1;
try { try {
fd = file.openForAttributeAccess(followLinks); fd = file.openForAttributeAccess(followLinks);

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -132,11 +132,6 @@ public class UnixUserPrincipals {
private static int lookupName(String name, boolean isGroup) private static int lookupName(String name, boolean isGroup)
throws IOException throws IOException
{ {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("lookupUserInformation"));
}
int id; int id;
try { try {
id = (isGroup) ? getgrnam(name) : getpwnam(name); id = (isGroup) ? getgrnam(name) : getpwnam(name);

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -25,20 +25,12 @@
package sun.nio.ch; package sun.nio.ch;
import java.security.AccessController;
import java.security.PrivilegedAction;
/** /**
* Creates this platform's default SelectorProvider * Creates this platform's default SelectorProvider
*/ */
@SuppressWarnings("removal")
public class DefaultSelectorProvider { public class DefaultSelectorProvider {
private static final SelectorProviderImpl INSTANCE; private static final SelectorProviderImpl INSTANCE = new WEPollSelectorProvider();
static {
PrivilegedAction<SelectorProviderImpl> pa = WEPollSelectorProvider::new;
INSTANCE = AccessController.doPrivileged(pa);
}
/** /**
* Prevent instantiation. * Prevent instantiation.

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -39,9 +39,6 @@ import java.nio.channels.*;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.channels.spi.*; import java.nio.channels.spi.*;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.Random; import java.util.Random;
@ -64,10 +61,7 @@ class PipeImpl
private final SourceChannelImpl source; private final SourceChannelImpl source;
private final SinkChannelImpl sink; private final SinkChannelImpl sink;
private static class Initializer private static class Initializer {
implements PrivilegedExceptionAction<Void>
{
private final SelectorProvider sp; private final SelectorProvider sp;
private final boolean preferUnixDomain; private final boolean preferUnixDomain;
private IOException ioe; private IOException ioe;
@ -79,8 +73,7 @@ class PipeImpl
this.preferUnixDomain = preferUnixDomain; this.preferUnixDomain = preferUnixDomain;
} }
@Override public void init() throws IOException {
public Void run() throws IOException {
LoopbackConnector connector = new LoopbackConnector(); LoopbackConnector connector = new LoopbackConnector();
connector.run(); connector.run();
if (ioe instanceof ClosedByInterruptException) { if (ioe instanceof ClosedByInterruptException) {
@ -101,8 +94,6 @@ class PipeImpl
if (ioe != null) if (ioe != null)
throw new IOException("Unable to establish loopback connection", ioe); throw new IOException("Unable to establish loopback connection", ioe);
return null;
} }
private class LoopbackConnector implements Runnable { private class LoopbackConnector implements Runnable {
@ -190,17 +181,12 @@ class PipeImpl
* *
* @param buffering if false set TCP_NODELAY on TCP sockets * @param buffering if false set TCP_NODELAY on TCP sockets
*/ */
@SuppressWarnings("removal")
PipeImpl(SelectorProvider sp, boolean preferAfUnix, boolean buffering) throws IOException { PipeImpl(SelectorProvider sp, boolean preferAfUnix, boolean buffering) throws IOException {
Initializer initializer = new Initializer(sp, preferAfUnix); Initializer initializer = new Initializer(sp, preferAfUnix);
try { initializer.init();
AccessController.doPrivileged(initializer); SinkChannelImpl sink = initializer.sink;
SinkChannelImpl sink = initializer.sink; if (sink.isNetSocket() && !buffering) {
if (sink.isNetSocket() && !buffering) { sink.setOption(StandardSocketOptions.TCP_NODELAY, true);
sink.setOption(StandardSocketOptions.TCP_NODELAY, true);
}
} catch (PrivilegedActionException pae) {
throw (IOException) pae.getCause();
} }
this.source = initializer.source; this.source = initializer.source;
this.sink = initializer.sink; this.sink = initializer.sink;

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2002, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -27,8 +27,6 @@ package sun.nio.ch;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.net.NetProperties; import sun.net.NetProperties;
import jdk.internal.util.StaticProperty; import jdk.internal.util.StaticProperty;
@ -50,20 +48,16 @@ class UnixDomainSocketsUtil {
* 3. %TEMP% * 3. %TEMP%
* 4. ${java.io.tmpdir} * 4. ${java.io.tmpdir}
*/ */
@SuppressWarnings("removal")
static String getTempDir() { static String getTempDir() {
PrivilegedAction<String> action = () -> { String s = NetProperties.get("jdk.net.unixdomain.tmpdir");
String s = NetProperties.get("jdk.net.unixdomain.tmpdir"); if (s != null) {
if (s != null) { return s;
return s; }
} String temp = System.getenv("TEMP");
String temp = System.getenv("TEMP"); if (temp != null) {
if (temp != null) { return temp;
return temp; }
} return StaticProperty.javaIoTmpDir();
return StaticProperty.javaIoTmpDir();
};
return AccessController.doPrivileged(action);
} }
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -30,9 +30,6 @@ import java.net.InetSocketAddress;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.io.IOException; import java.io.IOException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import jdk.internal.misc.Unsafe; import jdk.internal.misc.Unsafe;
/** /**
@ -115,16 +112,12 @@ class WindowsAsynchronousServerSocketChannelImpl
*/ */
private class AcceptTask implements Runnable, Iocp.ResultHandler { private class AcceptTask implements Runnable, Iocp.ResultHandler {
private final WindowsAsynchronousSocketChannelImpl channel; private final WindowsAsynchronousSocketChannelImpl channel;
@SuppressWarnings("removal")
private final AccessControlContext acc;
private final PendingFuture<AsynchronousSocketChannel,Object> result; private final PendingFuture<AsynchronousSocketChannel,Object> result;
AcceptTask(WindowsAsynchronousSocketChannelImpl channel, AcceptTask(WindowsAsynchronousSocketChannelImpl channel,
@SuppressWarnings("removal") AccessControlContext acc,
PendingFuture<AsynchronousSocketChannel,Object> result) PendingFuture<AsynchronousSocketChannel,Object> result)
{ {
this.channel = channel; this.channel = channel;
this.acc = acc;
this.result = result; this.result = result;
} }
@ -139,7 +132,6 @@ class WindowsAsynchronousServerSocketChannelImpl
} }
// caller must have acquired read lock for the listener and child channel. // caller must have acquired read lock for the listener and child channel.
@SuppressWarnings("removal")
void finishAccept() throws IOException { void finishAccept() throws IOException {
/** /**
* Set local/remote addresses. This is currently very inefficient * Set local/remote addresses. This is currently very inefficient
@ -151,18 +143,6 @@ class WindowsAsynchronousServerSocketChannelImpl
InetSocketAddress local = Net.localAddress(channel.fd); InetSocketAddress local = Net.localAddress(channel.fd);
final InetSocketAddress remote = Net.remoteAddress(channel.fd); final InetSocketAddress remote = Net.remoteAddress(channel.fd);
channel.setConnected(local, remote); channel.setConnected(local, remote);
// permission check (in context of initiating thread)
if (acc != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
SecurityManager sm = System.getSecurityManager();
sm.checkAccept(remote.getAddress().getHostAddress(),
remote.getPort());
return null;
}
}, acc);
}
} }
/** /**
@ -207,7 +187,7 @@ class WindowsAsynchronousServerSocketChannelImpl
closeChildChannel(); closeChildChannel();
if (x instanceof ClosedChannelException) if (x instanceof ClosedChannelException)
x = new AsynchronousCloseException(); x = new AsynchronousCloseException();
if (!(x instanceof IOException) && !(x instanceof SecurityException)) if (!(x instanceof IOException))
x = new IOException(x); x = new IOException(x);
enableAccept(); enableAccept();
result.setFailure(x); result.setFailure(x);
@ -259,7 +239,7 @@ class WindowsAsynchronousServerSocketChannelImpl
closeChildChannel(); closeChildChannel();
if (x instanceof ClosedChannelException) if (x instanceof ClosedChannelException)
x = new AsynchronousCloseException(); x = new AsynchronousCloseException();
if (!(x instanceof IOException) && !(x instanceof SecurityException)) if (!(x instanceof IOException))
x = new IOException(x); x = new IOException(x);
result.setFailure(x); result.setFailure(x);
} }
@ -328,16 +308,9 @@ class WindowsAsynchronousServerSocketChannelImpl
return null; return null;
} }
// need calling context when there is security manager as
// permission check may be done in a different thread without
// any application call frames on the stack
@SuppressWarnings("removal")
AccessControlContext acc = (System.getSecurityManager() == null) ?
null : AccessController.getContext();
PendingFuture<AsynchronousSocketChannel,Object> result = PendingFuture<AsynchronousSocketChannel,Object> result =
new PendingFuture<AsynchronousSocketChannel,Object>(this, handler, attachment); new PendingFuture<AsynchronousSocketChannel,Object>(this, handler, attachment);
AcceptTask task = new AcceptTask(ch, acc, result); AcceptTask task = new AcceptTask(ch, result);
result.setContext(task); result.setContext(task);
// check and set flag to prevent concurrent accepting // check and set flag to prevent concurrent accepting

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -31,9 +31,6 @@ import java.nio.BufferOverflowException;
import java.net.*; import java.net.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.io.IOException; import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import jdk.internal.misc.Unsafe; import jdk.internal.misc.Unsafe;
import sun.net.util.SocketExceptions; import sun.net.util.SocketExceptions;
@ -308,20 +305,6 @@ class WindowsAsynchronousSocketChannelImpl
} }
} }
@SuppressWarnings("removal")
private void doPrivilegedBind(final SocketAddress sa) throws IOException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
public Void run() throws IOException {
bind(sa);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (IOException) e.getException();
}
}
@Override @Override
<A> Future<Void> implConnect(SocketAddress remote, <A> Future<Void> implConnect(SocketAddress remote,
A attachment, A attachment,
@ -337,12 +320,6 @@ class WindowsAsynchronousSocketChannelImpl
InetSocketAddress isa = Net.checkAddress(remote); InetSocketAddress isa = Net.checkAddress(remote);
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkConnect(isa.getAddress().getHostAddress(), isa.getPort());
// check and update state // check and update state
// ConnectEx requires the socket to be bound to a local address // ConnectEx requires the socket to be bound to a local address
IOException bindException = null; IOException bindException = null;
@ -354,11 +331,7 @@ class WindowsAsynchronousSocketChannelImpl
if (localAddress == null) { if (localAddress == null) {
try { try {
SocketAddress any = new InetSocketAddress(0); SocketAddress any = new InetSocketAddress(0);
if (sm == null) { bind(any);
bind(any);
} else {
doPrivilegedBind(any);
}
} catch (IOException x) { } catch (IOException x) {
bindException = x; bindException = x;
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -61,22 +61,6 @@ class WindowsAclFileAttributeView
this.followLinks = followLinks; this.followLinks = followLinks;
} }
// permission check
private void checkAccess(WindowsPath file,
boolean checkRead,
boolean checkWrite)
{
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (checkRead)
sm.checkRead(file.getPathForPermissionCheck());
if (checkWrite)
sm.checkWrite(file.getPathForPermissionCheck());
sm.checkPermission(new RuntimePermission("accessUserInformation"));
}
}
// invokes GetFileSecurity to get requested security information // invokes GetFileSecurity to get requested security information
static NativeBuffer getFileSecurity(String path, int request) static NativeBuffer getFileSecurity(String path, int request)
throws IOException throws IOException
@ -114,8 +98,6 @@ class WindowsAclFileAttributeView
public UserPrincipal getOwner() public UserPrincipal getOwner()
throws IOException throws IOException
{ {
checkAccess(file, true, false);
// GetFileSecurity does not follow links so when following links we // GetFileSecurity does not follow links so when following links we
// need the final target // need the final target
String path = WindowsLinkSupport.getFinalPath(file, followLinks); String path = WindowsLinkSupport.getFinalPath(file, followLinks);
@ -135,8 +117,6 @@ class WindowsAclFileAttributeView
public List<AclEntry> getAcl() public List<AclEntry> getAcl()
throws IOException throws IOException
{ {
checkAccess(file, true, false);
// GetFileSecurity does not follow links so when following links we // GetFileSecurity does not follow links so when following links we
// need the final target // need the final target
String path = WindowsLinkSupport.getFinalPath(file, followLinks); String path = WindowsLinkSupport.getFinalPath(file, followLinks);
@ -158,9 +138,6 @@ class WindowsAclFileAttributeView
throw new ProviderMismatchException(); throw new ProviderMismatchException();
WindowsUserPrincipals.User owner = (WindowsUserPrincipals.User)obj; WindowsUserPrincipals.User owner = (WindowsUserPrincipals.User)obj;
// permission check
checkAccess(file, false, true);
// SetFileSecurity does not follow links so when following links we // SetFileSecurity does not follow links so when following links we
// need the final target // need the final target
String path = WindowsLinkSupport.getFinalPath(file, followLinks); String path = WindowsLinkSupport.getFinalPath(file, followLinks);
@ -199,8 +176,6 @@ class WindowsAclFileAttributeView
@Override @Override
public void setAcl(List<AclEntry> acl) throws IOException { public void setAcl(List<AclEntry> acl) throws IOException {
checkAccess(file, false, true);
// SetFileSecurity does not follow links so when following links we // SetFileSecurity does not follow links so when following links we
// need the final target // need the final target
String path = WindowsLinkSupport.getFinalPath(file, followLinks); String path = WindowsLinkSupport.getFinalPath(file, followLinks);

View file

@ -139,11 +139,8 @@ class WindowsChannelFactory {
* *
* @param pathForWindows * @param pathForWindows
* The path of the file to open/create * The path of the file to open/create
* @param pathToCheck
* The path used for permission checks (if security manager)
*/ */
static FileChannel newFileChannel(String pathForWindows, static FileChannel newFileChannel(String pathForWindows,
String pathToCheck,
Set<? extends OpenOption> options, Set<? extends OpenOption> options,
long pSecurityDescriptor) long pSecurityDescriptor)
throws WindowsException throws WindowsException
@ -165,7 +162,7 @@ class WindowsChannelFactory {
if (flags.append && flags.truncateExisting) if (flags.append && flags.truncateExisting)
throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed"); throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed");
FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor); FileDescriptor fdObj = open(pathForWindows, flags, pSecurityDescriptor);
return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write,
(flags.sync || flags.dsync), flags.direct, null); (flags.sync || flags.dsync), flags.direct, null);
} }
@ -175,13 +172,10 @@ class WindowsChannelFactory {
* *
* @param pathForWindows * @param pathForWindows
* The path of the file to open/create * The path of the file to open/create
* @param pathToCheck
* The path used for permission checks (if security manager)
* @param pool * @param pool
* The thread pool that the channel is associated with * The thread pool that the channel is associated with
*/ */
static AsynchronousFileChannel newAsynchronousFileChannel(String pathForWindows, static AsynchronousFileChannel newAsynchronousFileChannel(String pathForWindows,
String pathToCheck,
Set<? extends OpenOption> options, Set<? extends OpenOption> options,
long pSecurityDescriptor, long pSecurityDescriptor,
ThreadPool pool) ThreadPool pool)
@ -204,7 +198,7 @@ class WindowsChannelFactory {
// open file for overlapped I/O // open file for overlapped I/O
FileDescriptor fdObj; FileDescriptor fdObj;
try { try {
fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor); fdObj = open(pathForWindows, flags, pSecurityDescriptor);
} catch (WindowsException x) { } catch (WindowsException x) {
x.rethrowAsIOException(pathForWindows); x.rethrowAsIOException(pathForWindows);
return null; return null;
@ -226,7 +220,6 @@ class WindowsChannelFactory {
* encapsulating the handle to the open file. * encapsulating the handle to the open file.
*/ */
private static FileDescriptor open(String pathForWindows, private static FileDescriptor open(String pathForWindows,
String pathToCheck,
Flags flags, Flags flags,
long pSecurityDescriptor) long pSecurityDescriptor)
throws WindowsException throws WindowsException
@ -291,20 +284,6 @@ class WindowsChannelFactory {
dwFlagsAndAttributes |= FILE_FLAG_OPEN_REPARSE_POINT; dwFlagsAndAttributes |= FILE_FLAG_OPEN_REPARSE_POINT;
} }
// permission check
if (pathToCheck != null) {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (flags.read)
sm.checkRead(pathToCheck);
if (flags.write)
sm.checkWrite(pathToCheck);
if (flags.deleteOnClose)
sm.checkDelete(pathToCheck);
}
}
// open file // open file
long handle = CreateFile(pathForWindows, long handle = CreateFile(pathForWindows,
dwDesiredAccess, dwDesiredAccess,

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2022, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -46,7 +46,6 @@ class WindowsFileAttributeViews {
@Override @Override
public WindowsFileAttributes readAttributes() throws IOException { public WindowsFileAttributes readAttributes() throws IOException {
file.checkRead();
try { try {
return WindowsFileAttributes.get(file, followLinks); return WindowsFileAttributes.get(file, followLinks);
} catch (WindowsException x) { } catch (WindowsException x) {
@ -110,7 +109,7 @@ class WindowsFileAttributeViews {
// retry succeeded // retry succeeded
x = null; x = null;
} }
} catch (SecurityException | WindowsException | IOException ignore) { } catch (WindowsException | IOException ignore) {
// ignore exceptions to let original exception be thrown // ignore exceptions to let original exception be thrown
} }
} }
@ -134,9 +133,6 @@ class WindowsFileAttributeViews {
return; return;
} }
// permission check
file.checkWrite();
// update times // update times
long t1 = (createTime == null) ? -1L : long t1 = (createTime == null) ? -1L :
WindowsFileAttributes.toWindowsTime(createTime); WindowsFileAttributes.toWindowsTime(createTime);
@ -219,8 +215,6 @@ class WindowsFileAttributeViews {
private void updateAttributes(int flag, boolean enable) private void updateAttributes(int flag, boolean enable)
throws IOException throws IOException
{ {
file.checkWrite();
// GetFileAttributes & SetFileAttributes do not follow links so when // GetFileAttributes & SetFileAttributes do not follow links so when
// following links we need the final target // following links we need the final target
String path = WindowsLinkSupport.getFinalPath(file, followLinks); String path = WindowsLinkSupport.getFinalPath(file, followLinks);

View file

@ -84,15 +84,6 @@ class WindowsFileCopy {
throw new UnsupportedOperationException("Unsupported copy option: " + option); throw new UnsupportedOperationException("Unsupported copy option: " + option);
} }
// check permissions. If the source file is a symbolic link then
// later we must also check LinkPermission
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
source.checkRead();
target.checkWrite();
}
// get attributes of source file // get attributes of source file
// attempt to get attributes of target file // attempt to get attributes of target file
// if both files are the same there is nothing to do // if both files are the same there is nothing to do
@ -144,11 +135,6 @@ class WindowsFileCopy {
CloseHandle(sourceHandle); CloseHandle(sourceHandle);
} }
// if source file is a symbolic link then we must check for LinkPermission
if (sm != null && sourceAttrs.isSymbolicLink()) {
sm.checkPermission(new LinkPermission("symbolic"));
}
// if source is a Unix domain socket, we don't want to copy it for various // if source is a Unix domain socket, we don't want to copy it for various
// reasons including consistency with Unix // reasons including consistency with Unix
if (sourceAttrs.isUnixDomainSocket()) { if (sourceAttrs.isUnixDomainSocket()) {
@ -308,13 +294,6 @@ class WindowsFileCopy {
throw new UnsupportedOperationException("Unsupported option: " + option); throw new UnsupportedOperationException("Unsupported option: " + option);
} }
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
source.checkWrite();
target.checkWrite();
}
final String sourcePath = asWin32Path(source); final String sourcePath = asWin32Path(source);
final String targetPath = asWin32Path(target); final String targetPath = asWin32Path(target);

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -101,23 +101,14 @@ class WindowsFileSystem
throw new AssertionError(x.getMessage()); throw new AssertionError(x.getMessage());
} }
// iterate over roots, ignoring those that the security manager denies // iterate over roots
ArrayList<Path> result = new ArrayList<>(); ArrayList<Path> result = new ArrayList<>();
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
for (int i = 0; i <= 25; i++) { // 0->A, 1->B, 2->C... for (int i = 0; i <= 25; i++) { // 0->A, 1->B, 2->C...
if ((drives & (1 << i)) != 0) { if ((drives & (1 << i)) != 0) {
StringBuilder sb = new StringBuilder(3); StringBuilder sb = new StringBuilder(3);
sb.append((char)('A' + i)); sb.append((char)('A' + i));
sb.append(":\\"); sb.append(":\\");
String root = sb.toString(); String root = sb.toString();
if (sm != null) {
try {
sm.checkRead(root);
} catch (SecurityException x) {
continue;
}
}
result.add(WindowsPath.createFromNormalizedPath(this, root)); result.add(WindowsPath.createFromNormalizedPath(this, root));
} }
} }
@ -141,12 +132,6 @@ class WindowsFileSystem
if (!roots.hasNext()) if (!roots.hasNext())
return null; return null;
WindowsPath root = (WindowsPath)roots.next(); WindowsPath root = (WindowsPath)roots.next();
// ignore if security manager denies access
try {
root.checkRead();
} catch (SecurityException x) {
continue;
}
try { try {
FileStore fs = WindowsFileStore.create(root.toString(), true); FileStore fs = WindowsFileStore.create(root.toString(), true);
if (fs != null) if (fs != null)
@ -186,20 +171,7 @@ class WindowsFileSystem
@Override @Override
public Iterable<FileStore> getFileStores() { public Iterable<FileStore> getFileStores() {
@SuppressWarnings("removal") return FileStoreIterator::new;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkPermission(new RuntimePermission("getFileStoreAttributes"));
} catch (SecurityException se) {
return Collections.emptyList();
}
}
return new Iterable<FileStore>() {
public Iterator<FileStore> iterator() {
return new FileStoreIterator();
}
};
} }
// supported views // supported views

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -112,7 +112,6 @@ class WindowsFileSystemProvider
try { try {
return WindowsChannelFactory return WindowsChannelFactory
.newFileChannel(file.getPathForWin32Calls(), .newFileChannel(file.getPathForWin32Calls(),
file.getPathForPermissionCheck(),
options, options,
sd.address()); sd.address());
} catch (WindowsException x) { } catch (WindowsException x) {
@ -142,7 +141,6 @@ class WindowsFileSystemProvider
try { try {
return WindowsChannelFactory return WindowsChannelFactory
.newAsynchronousFileChannel(file.getPathForWin32Calls(), .newAsynchronousFileChannel(file.getPathForWin32Calls(),
file.getPathForPermissionCheck(),
options, options,
sd.address(), sd.address(),
pool); pool);
@ -227,7 +225,6 @@ class WindowsFileSystemProvider
try { try {
return WindowsChannelFactory return WindowsChannelFactory
.newFileChannel(file.getPathForWin32Calls(), .newFileChannel(file.getPathForWin32Calls(),
file.getPathForPermissionCheck(),
options, options,
sd.address()); sd.address());
} catch (WindowsException x) { } catch (WindowsException x) {
@ -241,7 +238,6 @@ class WindowsFileSystemProvider
@Override @Override
boolean implDelete(Path obj, boolean failIfNotExists) throws IOException { boolean implDelete(Path obj, boolean failIfNotExists) throws IOException {
WindowsPath file = WindowsPath.toWindowsPath(obj); WindowsPath file = WindowsPath.toWindowsPath(obj);
file.checkDelete();
WindowsFileAttributes attrs = null; WindowsFileAttributes attrs = null;
try { try {
@ -324,7 +320,6 @@ class WindowsFileSystemProvider
Set<OpenOption> opts = Collections.emptySet(); Set<OpenOption> opts = Collections.emptySet();
FileChannel fc = WindowsChannelFactory FileChannel fc = WindowsChannelFactory
.newFileChannel(file.getPathForWin32Calls(), .newFileChannel(file.getPathForWin32Calls(),
file.getPathForPermissionCheck(),
opts, opts,
0L); 0L);
fc.close(); fc.close();
@ -371,7 +366,6 @@ class WindowsFileSystemProvider
// check file exists only // check file exists only
if (!(r || w || x)) { if (!(r || w || x)) {
file.checkRead();
try { try {
WindowsFileAttributes.get(file, true); WindowsFileAttributes.get(file, true);
return; return;
@ -389,18 +383,12 @@ class WindowsFileSystemProvider
int mask = 0; int mask = 0;
if (r) { if (r) {
file.checkRead();
mask |= FILE_READ_DATA; mask |= FILE_READ_DATA;
} }
if (w) { if (w) {
file.checkWrite();
mask |= FILE_WRITE_DATA; mask |= FILE_WRITE_DATA;
} }
if (x) { if (x) {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkExec(file.getPathForPermissionCheck());
mask |= FILE_EXECUTE; mask |= FILE_EXECUTE;
} }
@ -440,10 +428,6 @@ class WindowsFileSystemProvider
return false; return false;
WindowsPath file2 = (WindowsPath)obj2; WindowsPath file2 = (WindowsPath)obj2;
// check security manager access to both files
file1.checkRead();
file2.checkRead();
// open both files and see if they are the same // open both files and see if they are the same
long h1 = 0L; long h1 = 0L;
try { try {
@ -483,7 +467,6 @@ class WindowsFileSystemProvider
@Override @Override
public boolean isHidden(Path obj) throws IOException { public boolean isHidden(Path obj) throws IOException {
WindowsPath file = WindowsPath.toWindowsPath(obj); WindowsPath file = WindowsPath.toWindowsPath(obj);
file.checkRead();
WindowsFileAttributes attrs = null; WindowsFileAttributes attrs = null;
try { try {
attrs = WindowsFileAttributes.get(file, true); attrs = WindowsFileAttributes.get(file, true);
@ -496,12 +479,6 @@ class WindowsFileSystemProvider
@Override @Override
public FileStore getFileStore(Path obj) throws IOException { public FileStore getFileStore(Path obj) throws IOException {
WindowsPath file = WindowsPath.toWindowsPath(obj); WindowsPath file = WindowsPath.toWindowsPath(obj);
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("getFileStoreAttributes"));
file.checkRead();
}
return WindowsFileStore.create(file); return WindowsFileStore.create(file);
} }
@ -511,7 +488,6 @@ class WindowsFileSystemProvider
throws IOException throws IOException
{ {
WindowsPath dir = WindowsPath.toWindowsPath(obj); WindowsPath dir = WindowsPath.toWindowsPath(obj);
dir.checkWrite();
WindowsSecurityDescriptor sd = WindowsSecurityDescriptor.fromAttribute(attrs); WindowsSecurityDescriptor sd = WindowsSecurityDescriptor.fromAttribute(attrs);
try { try {
CreateDirectory(dir.getPathForWin32Calls(), sd.address()); CreateDirectory(dir.getPathForWin32Calls(), sd.address());
@ -535,7 +511,6 @@ class WindowsFileSystemProvider
throws IOException throws IOException
{ {
WindowsPath dir = WindowsPath.toWindowsPath(obj); WindowsPath dir = WindowsPath.toWindowsPath(obj);
dir.checkRead();
if (filter == null) if (filter == null)
throw new NullPointerException(); throw new NullPointerException();
return new WindowsDirectoryStream(dir, filter); return new WindowsDirectoryStream(dir, filter);
@ -555,14 +530,6 @@ class WindowsFileSystemProvider
"not supported when creating symbolic link"); "not supported when creating symbolic link");
} }
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new LinkPermission("symbolic"));
link.checkWrite();
}
/** /**
* Throw I/O exception for the drive-relative case because Windows * Throw I/O exception for the drive-relative case because Windows
* creates a link with the resolved target for this case. * creates a link with the resolved target for this case.
@ -611,15 +578,6 @@ class WindowsFileSystemProvider
WindowsPath link = WindowsPath.toWindowsPath(obj1); WindowsPath link = WindowsPath.toWindowsPath(obj1);
WindowsPath existing = WindowsPath.toWindowsPath(obj2); WindowsPath existing = WindowsPath.toWindowsPath(obj2);
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new LinkPermission("hard"));
link.checkWrite();
existing.checkWrite();
}
// create hard link // create hard link
try { try {
CreateHardLink(link.getPathForWin32Calls(), CreateHardLink(link.getPathForWin32Calls(),
@ -634,15 +592,6 @@ class WindowsFileSystemProvider
WindowsPath link = WindowsPath.toWindowsPath(obj1); WindowsPath link = WindowsPath.toWindowsPath(obj1);
WindowsFileSystem fs = link.getFileSystem(); WindowsFileSystem fs = link.getFileSystem();
// permission check
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
FilePermission perm = new FilePermission(link.getPathForPermissionCheck(),
SecurityConstants.FILE_READLINK_ACTION);
sm.checkPermission(perm);
}
String target = WindowsLinkSupport.readLink(link); String target = WindowsLinkSupport.readLink(link);
return WindowsPath.createFromNormalizedPath(fs, target); return WindowsPath.createFromNormalizedPath(fs, target);
} }

View file

@ -28,8 +28,6 @@ package sun.nio.fs;
import java.nio.file.*; import java.nio.file.*;
import java.io.IOException; import java.io.IOException;
import java.io.IOError; import java.io.IOError;
import java.security.AccessController;
import java.security.PrivilegedAction;
import jdk.internal.misc.Unsafe; import jdk.internal.misc.Unsafe;
import static sun.nio.fs.WindowsNativeDispatcher.*; import static sun.nio.fs.WindowsNativeDispatcher.*;
@ -120,7 +118,6 @@ class WindowsLinkSupport {
* Returns the final path of a given path as a String. This should be used * Returns the final path of a given path as a String. This should be used
* prior to calling Win32 system calls that do not follow links. * prior to calling Win32 system calls that do not follow links.
*/ */
@SuppressWarnings("removal")
static String getFinalPath(WindowsPath input, boolean followLinks) static String getFinalPath(WindowsPath input, boolean followLinks)
throws IOException throws IOException
{ {
@ -164,12 +161,7 @@ class WindowsLinkSupport {
if (parent == null) { if (parent == null) {
// no parent so use parent of absolute path // no parent so use parent of absolute path
final WindowsPath t = target; final WindowsPath t = target;
target = AccessController target = t.toAbsolutePath();
.doPrivileged(new PrivilegedAction<WindowsPath>() {
@Override
public WindowsPath run() {
return t.toAbsolutePath();
}});
parent = target.getParent(); parent = target.getParent();
} }
target = parent.resolve(link); target = parent.resolve(link);

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -166,11 +166,6 @@ class WindowsPath implements Path {
return path; return path;
} }
// use this path for permission checks
String getPathForPermissionCheck() {
return path;
}
// use this path for Win32 calls // use this path for Win32 calls
// This method will prefix long paths with \\?\ or \\?\UNC as required. // This method will prefix long paths with \\?\ or \\?\UNC as required.
String getPathForWin32Calls() throws WindowsException { String getPathForWin32Calls() throws WindowsException {
@ -890,30 +885,6 @@ class WindowsPath implements Path {
} }
} }
void checkRead() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkRead(getPathForPermissionCheck());
}
}
void checkWrite() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkWrite(getPathForPermissionCheck());
}
}
void checkDelete() {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkDelete(getPathForPermissionCheck());
}
}
@Override @Override
public URI toUri() { public URI toUri() {
return WindowsUriSupport.toUri(this); return WindowsUriSupport.toUri(this);
@ -924,13 +895,6 @@ class WindowsPath implements Path {
if (isAbsolute()) if (isAbsolute())
return this; return this;
// permission check as per spec
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPropertyAccess("user.dir");
}
try { try {
return createFromNormalizedPath(getFileSystem(), getAbsolutePath()); return createFromNormalizedPath(getFileSystem(), getAbsolutePath());
} catch (WindowsException x) { } catch (WindowsException x) {
@ -940,7 +904,6 @@ class WindowsPath implements Path {
@Override @Override
public WindowsPath toRealPath(LinkOption... options) throws IOException { public WindowsPath toRealPath(LinkOption... options) throws IOException {
checkRead();
String rp = WindowsLinkSupport.getRealPath(this, Util.followLinks(options)); String rp = WindowsLinkSupport.getRealPath(this, Util.followLinks(options));
return createFromNormalizedPath(getFileSystem(), rp); return createFromNormalizedPath(getFileSystem(), rp);
} }
@ -956,31 +919,6 @@ class WindowsPath implements Path {
if (!(watcher instanceof WindowsWatchService)) if (!(watcher instanceof WindowsWatchService))
throw new ProviderMismatchException(); throw new ProviderMismatchException();
// When a security manager is set then we need to make a defensive
// copy of the modifiers and check for the Windows specific FILE_TREE
// modifier. When the modifier is present then check that permission
// has been granted recursively.
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
boolean watchSubtree = false;
final int ml = modifiers.length;
if (ml > 0) {
modifiers = Arrays.copyOf(modifiers, ml);
int i=0;
while (i < ml) {
if (ExtendedOptions.FILE_TREE.matches(modifiers[i++])) {
watchSubtree = true;
break;
}
}
}
String s = getPathForPermissionCheck();
sm.checkRead(s);
if (watchSubtree)
sm.checkRead(s + "\\-");
}
return ((WindowsWatchService)watcher).register(this, events, modifiers); return ((WindowsWatchService)watcher).register(this, events, modifiers);
} }
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -104,9 +104,8 @@ class WindowsUriSupport {
boolean addSlash = false; boolean addSlash = false;
if (!s.endsWith("\\")) { if (!s.endsWith("\\")) {
try { try {
path.checkRead();
addSlash = WindowsFileAttributes.get(path, true).isDirectory(); addSlash = WindowsFileAttributes.get(path, true).isDirectory();
} catch (SecurityException | WindowsException x) { } catch (WindowsException x) {
} }
} }

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -100,19 +100,13 @@ class WindowsUserDefinedFileAttributeView
return Collections.unmodifiableList(list); return Collections.unmodifiableList(list);
} }
@SuppressWarnings("removal")
@Override @Override
public List<String> list() throws IOException { public List<String> list() throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), true, false);
return listUsingStreamEnumeration(); return listUsingStreamEnumeration();
} }
@SuppressWarnings("removal")
@Override @Override
public int size(String name) throws IOException { public int size(String name) throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), true, false);
// wrap with channel // wrap with channel
FileChannel fc = null; FileChannel fc = null;
@ -122,9 +116,9 @@ class WindowsUserDefinedFileAttributeView
if (!followLinks) if (!followLinks)
opts.add(WindowsChannelFactory.OPEN_REPARSE_POINT); opts.add(WindowsChannelFactory.OPEN_REPARSE_POINT);
fc = WindowsChannelFactory fc = WindowsChannelFactory
.newFileChannel(join(file, name), null, opts, 0L); .newFileChannel(join(file, name), opts, 0L);
} catch (WindowsException x) { } catch (WindowsException x) {
x.rethrowAsIOException(join(file.getPathForPermissionCheck(), name)); x.rethrowAsIOException(join(file.getPathForExceptionMessage(), name));
} }
try { try {
long size = fc.size(); long size = fc.size();
@ -136,12 +130,8 @@ class WindowsUserDefinedFileAttributeView
} }
} }
@SuppressWarnings("removal")
@Override @Override
public int read(String name, ByteBuffer dst) throws IOException { public int read(String name, ByteBuffer dst) throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), true, false);
// wrap with channel // wrap with channel
FileChannel fc = null; FileChannel fc = null;
try { try {
@ -150,9 +140,9 @@ class WindowsUserDefinedFileAttributeView
if (!followLinks) if (!followLinks)
opts.add(WindowsChannelFactory.OPEN_REPARSE_POINT); opts.add(WindowsChannelFactory.OPEN_REPARSE_POINT);
fc = WindowsChannelFactory fc = WindowsChannelFactory
.newFileChannel(join(file, name), null, opts, 0L); .newFileChannel(join(file, name), opts, 0L);
} catch (WindowsException x) { } catch (WindowsException x) {
x.rethrowAsIOException(join(file.getPathForPermissionCheck(), name)); x.rethrowAsIOException(join(file.getPathForExceptionMessage(), name));
} }
// read to EOF (nothing we can do if I/O error occurs) // read to EOF (nothing we can do if I/O error occurs)
@ -172,12 +162,8 @@ class WindowsUserDefinedFileAttributeView
} }
} }
@SuppressWarnings("removal")
@Override @Override
public int write(String name, ByteBuffer src) throws IOException { public int write(String name, ByteBuffer src) throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), false, true);
/** /**
* Creating a named stream will cause the unnamed stream to be created * Creating a named stream will cause the unnamed stream to be created
* if it doesn't already exist. To avoid this we open the unnamed stream * if it doesn't already exist. To avoid this we open the unnamed stream
@ -210,9 +196,9 @@ class WindowsUserDefinedFileAttributeView
FileChannel named = null; FileChannel named = null;
try { try {
named = WindowsChannelFactory named = WindowsChannelFactory
.newFileChannel(join(file, name), null, opts, 0L); .newFileChannel(join(file, name), opts, 0L);
} catch (WindowsException x) { } catch (WindowsException x) {
x.rethrowAsIOException(join(file.getPathForPermissionCheck(), name)); x.rethrowAsIOException(join(file.getPathForExceptionMessage(), name));
} }
// write value (nothing we can do if I/O error occurs) // write value (nothing we can do if I/O error occurs)
try { try {
@ -229,12 +215,8 @@ class WindowsUserDefinedFileAttributeView
} }
} }
@SuppressWarnings("removal")
@Override @Override
public void delete(String name) throws IOException { public void delete(String name) throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), false, true);
String path = WindowsLinkSupport.getFinalPath(file, followLinks); String path = WindowsLinkSupport.getFinalPath(file, followLinks);
String toDelete = join(path, name); String toDelete = join(path, name);
try { try {

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -131,12 +131,6 @@ class WindowsUserPrincipals {
} }
static UserPrincipal lookup(String name) throws IOException { static UserPrincipal lookup(String name) throws IOException {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("lookupUserInformation"));
}
// invoke LookupAccountName to get buffer size needed for SID // invoke LookupAccountName to get buffer size needed for SID
int size; int size;
try { try {