use of java.nio.file.attribute.AclFileAttributeView in project derby by apache.
the class FileUtil method limitAccessToOwnerViaFileAttributeView.
/**
* Limit access to owner using a
* {@code java.nio.file.attribute.FileAttributeView}.
* Such views are only available on Java 7 and higher, and only on
* file systems that support changing file permissions. Currently,
* this is supported on POSIX file systems and file systems that
* maintain access control lists (ACLs).
*
* @param file the file to limit access to
* @return {@code true} on success, or {@code false} if some of the
* permissions could not be changed
*/
private static boolean limitAccessToOwnerViaFileAttributeView(File file) throws IOException {
Path fileP = file.toPath();
PosixFileAttributeView posixView = Files.getFileAttributeView(fileP, PosixFileAttributeView.class);
if (posixView != null) {
// This is a POSIX file system. Usually,
// FileUtil.limitAccessToOwnerViaFile() will successfully set
// the permissions on such file systems using the java.io.File
// class, so we don't get here. If, however, that approach failed,
// we try again here using a PosixFileAttributeView. That's likely
// to fail too, but at least now we will get an IOException that
// explains why it failed.
EnumSet<PosixFilePermission> perms = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE);
if (file.isDirectory()) {
perms.add(PosixFilePermission.OWNER_EXECUTE);
}
posixView.setPermissions(perms);
return true;
}
AclFileAttributeView aclView = Files.getFileAttributeView(fileP, AclFileAttributeView.class);
if (aclView != null) {
// Since we have an AclFileAttributeView which is not a
// PosixFileAttributeView, we probably have an NTFS file
// system.
// Remove existing ACEs, build a new one which simply
// gives all possible permissions to current owner.
AclEntry ace = AclEntry.newBuilder().setPrincipal(Files.getOwner(fileP)).setType(AclEntryType.ALLOW).setPermissions(EnumSet.allOf(AclEntryPermission.class)).build();
aclView.setAcl(Collections.singletonList(ace));
return true;
}
// We don't know how to set permissions on this file system.
return false;
}
use of java.nio.file.attribute.AclFileAttributeView in project fess-crawler by codelibs.
the class FileSystemClient method getResponseData.
protected ResponseData getResponseData(final String uri, final boolean includeContent) {
final ResponseData responseData = new ResponseData();
try {
responseData.setMethod(Constants.GET_METHOD);
final String filePath = preprocessUri(uri);
responseData.setUrl(filePath);
File file = null;
try {
file = new File(new URI(filePath));
} catch (final URISyntaxException e) {
logger.warn("Could not parse url: " + filePath, e);
}
if (file == null) {
responseData.setHttpStatusCode(Constants.NOT_FOUND_STATUS_CODE);
responseData.setCharSet(charset);
responseData.setContentLength(0);
} else if (file.isFile()) {
// check file size
responseData.setContentLength(file.length());
checkMaxContentLength(responseData);
try {
final FileOwnerAttributeView ownerAttrView = Files.getFileAttributeView(file.toPath(), FileOwnerAttributeView.class);
if (ownerAttrView != null) {
UserPrincipal owner = ownerAttrView.getOwner();
if (owner != null) {
responseData.addMetaData(FS_FILE_USER, owner.getName());
}
}
} catch (Exception e) {
logger.warn("Failed to parse FileOwnerAttributeView.", e);
}
try {
final AclFileAttributeView aclView = Files.getFileAttributeView(file.toPath(), AclFileAttributeView.class);
if (aclView != null) {
responseData.addMetaData(FILE_ATTRIBUTE_VIEW, aclView);
responseData.addMetaData(FS_FILE_GROUPS, aclView.getAcl().stream().map(acl -> acl.principal().getName()).toArray(n -> new String[n]));
}
} catch (Exception e) {
logger.warn("Failed to parse AclFileAttributeView.", e);
}
try {
final PosixFileAttributeView posixView = Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class);
if (posixView != null) {
responseData.addMetaData(FILE_ATTRIBUTE_VIEW, posixView);
responseData.addMetaData(FS_FILE_GROUPS, new String[] { posixView.readAttributes().group().getName() });
}
} catch (Exception e) {
logger.warn("Failed to parse PosixFileAttributeView.", e);
}
responseData.setHttpStatusCode(Constants.OK_STATUS_CODE);
responseData.setCharSet(geCharSet(file));
responseData.setLastModified(new Date(file.lastModified()));
if (file.canRead()) {
final MimeTypeHelper mimeTypeHelper = crawlerContainer.getComponent("mimeTypeHelper");
try (final InputStream is = new BufferedInputStream(new FileInputStream(file))) {
responseData.setMimeType(mimeTypeHelper.getContentType(is, file.getName()));
} catch (final Exception e) {
responseData.setMimeType(mimeTypeHelper.getContentType(null, file.getName()));
}
if (contentLengthHelper != null) {
final long maxLength = contentLengthHelper.getMaxLength(responseData.getMimeType());
if (responseData.getContentLength() > maxLength) {
throw new MaxLengthExceededException("The content length (" + responseData.getContentLength() + " byte) is over " + maxLength + " byte. The url is " + filePath);
}
}
if (includeContent) {
if (file.length() < maxCachedContentSize) {
try (InputStream contentStream = new BufferedInputStream(new FileInputStream(file))) {
responseData.setResponseBody(InputStreamUtil.getBytes(contentStream));
} catch (final Exception e) {
logger.warn("I/O Exception.", e);
responseData.setHttpStatusCode(Constants.SERVER_ERROR_STATUS_CODE);
}
} else {
responseData.setResponseBody(file, false);
}
}
} else {
// Forbidden
responseData.setHttpStatusCode(Constants.FORBIDDEN_STATUS_CODE);
responseData.setMimeType(APPLICATION_OCTET_STREAM);
}
} else if (file.isDirectory()) {
final Set<RequestData> requestDataSet = new HashSet<>();
if (includeContent) {
final File[] files = file.listFiles();
if (files != null) {
for (final File f : files) {
final String chileUri = f.toURI().toASCIIString();
requestDataSet.add(RequestDataBuilder.newRequestData().get().url(chileUri).build());
}
}
}
throw new ChildUrlsException(requestDataSet, this.getClass().getName() + "#getResponseData");
} else {
responseData.setHttpStatusCode(Constants.NOT_FOUND_STATUS_CODE);
responseData.setCharSet(charset);
responseData.setContentLength(0);
}
} catch (final CrawlerSystemException e) {
CloseableUtil.closeQuietly(responseData);
throw e;
} catch (final Exception e) {
CloseableUtil.closeQuietly(responseData);
throw new CrawlingAccessException("Could not access " + uri, e);
}
return responseData;
}
use of java.nio.file.attribute.AclFileAttributeView in project neo4j by neo4j.
the class ConfigTest method shouldNotEvaluateWithIncorrectFilePermission.
@Test
void shouldNotEvaluateWithIncorrectFilePermission() throws IOException {
assumeUnixOrWindows();
Path confFile = testDirectory.file("test.conf");
Files.createFile(confFile);
Files.write(confFile, List.of(TestSettings.intSetting.name() + "=$(foo bar)"));
if (IS_OS_WINDOWS) {
AclFileAttributeView attrs = Files.getFileAttributeView(confFile, AclFileAttributeView.class);
attrs.setAcl(List.of(AclEntry.newBuilder().setType(AclEntryType.ALLOW).setPrincipal(attrs.getOwner()).setPermissions(AclEntryPermission.READ_DATA, AclEntryPermission.WRITE_DATA, AclEntryPermission.READ_ATTRIBUTES, AclEntryPermission.WRITE_ATTRIBUTES, AclEntryPermission.READ_NAMED_ATTRS, AclEntryPermission.WRITE_NAMED_ATTRS, AclEntryPermission.APPEND_DATA, AclEntryPermission.READ_ACL, AclEntryPermission.SYNCHRONIZE, AclEntryPermission.EXECUTE).build()));
} else {
setPosixFilePermissions(confFile, PosixFilePermissions.fromString("rw-----w-"));
}
// Given
Config.Builder builder = Config.newBuilder().allowCommandExpansion().addSettingsClass(TestSettings.class).fromFile(confFile);
// Then
String msg = assertThrows(IllegalArgumentException.class, builder::build).getMessage();
String expectedErrorMessage = IS_OS_WINDOWS ? "does not have the correct ACL for owner" : "does not have the correct file permissions";
assertThat(msg).contains(expectedErrorMessage);
}
use of java.nio.file.attribute.AclFileAttributeView in project che by eclipse.
the class WindowsSshScript method protectPrivateKeyFile.
@Override
protected void protectPrivateKeyFile(File sshKey) throws ServerException {
try {
AclFileAttributeView attributes = Files.getFileAttributeView(sshKey.toPath(), AclFileAttributeView.class);
AclEntry.Builder builder = AclEntry.newBuilder();
builder.setType(ALLOW);
String ownerName = System.getProperty(OWNER_NAME_PROPERTY);
UserPrincipal userPrincipal = FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName(ownerName);
builder.setPrincipal(userPrincipal);
builder.setPermissions(READ_DATA, APPEND_DATA, READ_NAMED_ATTRS, READ_ATTRIBUTES, DELETE, READ_ACL, SYNCHRONIZE);
AclEntry entry = builder.build();
List<AclEntry> aclEntryList = new ArrayList<>();
aclEntryList.add(entry);
attributes.setAcl(aclEntryList);
} catch (IOException e) {
throw new ServerException("Failed to set file permissions");
}
}
use of java.nio.file.attribute.AclFileAttributeView in project qpid-broker-j by apache.
the class AESKeyFileEncrypterFactory method createEmptyKeyFile.
private void createEmptyKeyFile(File file) throws IOException {
final Path parentFilePath = file.getAbsoluteFile().getParentFile().toPath();
if (isPosixFileSystem(file)) {
Set<PosixFilePermission> ownerOnly = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE);
Files.createDirectories(parentFilePath, PosixFilePermissions.asFileAttribute(ownerOnly));
Files.createFile(file.toPath(), PosixFilePermissions.asFileAttribute(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)));
} else if (isAclFileSystem(file)) {
Files.createDirectories(parentFilePath);
final UserPrincipal owner = Files.getOwner(parentFilePath);
AclFileAttributeView attributeView = Files.getFileAttributeView(parentFilePath, AclFileAttributeView.class);
List<AclEntry> acls = new ArrayList<>(attributeView.getAcl());
ListIterator<AclEntry> iter = acls.listIterator();
boolean found = false;
while (iter.hasNext()) {
AclEntry acl = iter.next();
if (!owner.equals(acl.principal())) {
iter.remove();
} else if (acl.type() == AclEntryType.ALLOW) {
found = true;
AclEntry.Builder builder = AclEntry.newBuilder(acl);
Set<AclEntryPermission> permissions = acl.permissions().isEmpty() ? new HashSet<AclEntryPermission>() : EnumSet.copyOf(acl.permissions());
permissions.addAll(Arrays.asList(AclEntryPermission.ADD_FILE, AclEntryPermission.ADD_SUBDIRECTORY, AclEntryPermission.LIST_DIRECTORY));
builder.setPermissions(permissions);
iter.set(builder.build());
}
}
if (!found) {
AclEntry.Builder builder = AclEntry.newBuilder();
builder.setPermissions(AclEntryPermission.ADD_FILE, AclEntryPermission.ADD_SUBDIRECTORY, AclEntryPermission.LIST_DIRECTORY);
builder.setType(AclEntryType.ALLOW);
builder.setPrincipal(owner);
acls.add(builder.build());
}
attributeView.setAcl(acls);
Files.createFile(file.toPath(), new FileAttribute<List<AclEntry>>() {
@Override
public String name() {
return "acl:acl";
}
@Override
public List<AclEntry> value() {
AclEntry.Builder builder = AclEntry.newBuilder();
builder.setType(AclEntryType.ALLOW);
builder.setPermissions(EnumSet.allOf(AclEntryPermission.class));
builder.setPrincipal(owner);
return Collections.singletonList(builder.build());
}
});
} else {
throw new IllegalArgumentException("Unable to determine a mechanism to protect access to the key file on this filesystem");
}
}
Aggregations