use of diskCacheV111.util.PermissionDeniedCacheException in project dcache by dCache.
the class ChimeraNameSpaceProvider method createUploadPath.
@Override
public FsPath createUploadPath(Subject subject, FsPath path, FsPath rootPath, Long size, AccessLatency al, RetentionPolicy rp, String spaceToken, Set<CreateOption> options) throws CacheException {
checkState(_uploadDirectory != null, "Upload directory is not configured.");
try {
/* Parent directory must exist.
*/
ExtendedInode parentOfPath = options.contains(CreateOption.CREATE_PARENTS) ? installDirectory(subject, path.parent(), INHERIT_MODE) : lookupDirectory(subject, path.parent());
FileAttributes attributesOfParent = !Subjects.isExemptFromNamespaceChecks(subject) ? getFileAttributesForPermissionHandler(parentOfPath) : null;
/* File must not exist unless overwrite is enabled.
*/
try {
ExtendedInode inodeOfPath = parentOfPath.inodeOf(path.name(), STAT);
if (!options.contains(CreateOption.OVERWRITE_EXISTING) || (inodeOfPath.statCache().getMode() & UnixPermission.S_TYPE) != UnixPermission.S_IFREG) {
throw new FileExistsCacheException("File exists: " + path);
}
/* User must be authorized to delete existing file.
*/
if (!Subjects.isExemptFromNamespaceChecks(subject)) {
FileAttributes attributesOfPath = getFileAttributesForPermissionHandler(inodeOfPath);
if (_permissionHandler.canDeleteFile(subject, attributesOfParent, attributesOfPath) != ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException("Access denied: " + path);
}
}
} catch (FileNotFoundChimeraFsException ignored) {
}
/* User must be authorized to create file.
*/
if (!Subjects.isExemptFromNamespaceChecks(subject)) {
if (_permissionHandler.canCreateFile(subject, attributesOfParent) != ACCESS_ALLOWED) {
throw new PermissionDeniedCacheException("Access denied: " + path);
}
}
/* Attributes are inherited from real parent directory.
*/
int mode = parentOfPath.statCache().getMode() & UnixPermission.S_PERMS;
int gid;
if ((mode & UnixPermission.S_ISGID) != 0) {
gid = parentOfPath.statCache().getGid();
} else if (Subjects.isNobody(subject) || _inheritFileOwnership) {
gid = parentOfPath.statCache().getGid();
} else {
gid = Ints.checkedCast(Subjects.getPrimaryGid(subject));
}
int uid;
if (Subjects.isNobody(subject) || _inheritFileOwnership) {
uid = parentOfPath.statCache().getUid();
} else {
uid = Ints.checkedCast(Subjects.getUid(subject));
}
/* ACLs are copied from real parent to the temporary upload directory
* such that the upload is allowed (in case write permissions rely
* on ACLs) and such that the file will inherit the correct ACLs.
*/
List<ACE> acl = _fs.getACL(parentOfPath);
/* The temporary upload directory has the same tags as the real parent,
* except target file specific properties are stored as tags local to
* the upload directory.
*/
Map<String, byte[]> tags = Maps.newHashMap(parentOfPath.getTags());
if (spaceToken != null) {
tags.put(TAG_WRITE_TOKEN, spaceToken.getBytes(UTF_8));
/* If client provides space token to upload to, the access latency and
* retention policy tags of the upload directory must be disregarded.
*/
tags.remove(TAG_ACCESS_LATENCY);
tags.remove(TAG_RETENTION_POLICY);
}
if (al != null) {
tags.put(TAG_ACCESS_LATENCY, al.toString().getBytes(UTF_8));
}
if (rp != null) {
tags.put(TAG_RETENTION_POLICY, rp.toString().getBytes(UTF_8));
}
if (size != null) {
tags.put(TAG_EXPECTED_SIZE, size.toString().getBytes(UTF_8));
}
tags.put(TAG_PATH, path.toString().getBytes(UTF_8));
/* Upload directory may optionally be relative to the user's root path. Whether
* that's the case depends on if the configured upload directory is an absolute
* or relative path.
*/
FsPath uploadDirectory = rootPath.resolve(_uploadDirectory);
if (_uploadSubDirectory != null) {
uploadDirectory = uploadDirectory.chroot(String.format(_uploadSubDirectory, threadId.get()));
}
/* Upload directory must exist and have the right permissions.
*/
ExtendedInode inodeOfUploadDir = installSystemDirectory(uploadDirectory, 0711, Collections.emptyList(), Collections.emptyMap());
if (inodeOfUploadDir.statCache().getUid() != 0) {
LOGGER.error("Owner must be root: {}", uploadDirectory);
throw new CacheException("Owner must be root: " + uploadDirectory);
}
if ((inodeOfUploadDir.statCache().getMode() & UnixPermission.S_PERMS) != 0711) {
LOGGER.error("File mode must be 0711: {}", uploadDirectory);
throw new CacheException("File mode must be 0711: " + uploadDirectory);
}
/* Use cryptographically strong pseudo random UUID to create temporary upload directory.
*/
UUID uuid = UUID.randomUUID();
_fs.mkdir(inodeOfUploadDir, uuid.toString(), uid, gid, mode, acl, tags);
return uploadDirectory.child(uuid.toString()).child(path.name());
} catch (ChimeraFsException e) {
LOGGER.error("Problem with database: {}", e.getMessage());
throw new CacheException(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, e.getMessage());
}
}
use of diskCacheV111.util.PermissionDeniedCacheException in project dcache by dCache.
the class DCacheAwareJdbcFs method rename.
@Override
public boolean rename(FsInode inode, FsInode srcDir, String source, FsInode destDir, String dest) throws ChimeraFsException {
if (!queryPnfsManagerOnRename) {
return super.rename(inode, srcDir, source, destDir, dest);
}
boolean rc = true;
try {
String sourceDirectory = inode2path(srcDir);
File sourcePath = new File(sourceDirectory, source);
String destinationDirectory = inode2path(destDir);
File destinationPath = new File(destinationDirectory, dest);
pnfsHandler.renameEntry(sourcePath.getCanonicalPath(), destinationPath.getCanonicalPath(), true);
} catch (PermissionDeniedCacheException e) {
throw new PermissionDeniedChimeraFsException(e.getMessage());
} catch (CacheException | IOException e) {
Throwables.propagateIfInstanceOf(e, ChimeraFsException.class);
throw new ChimeraFsException(e.getMessage(), e);
}
return rc;
}
use of diskCacheV111.util.PermissionDeniedCacheException in project dcache by dCache.
the class DCacheAwareJdbcFs method unpin.
/**
* This method sends a request to the pin manager to unpin a given file.
*/
@Override
public void unpin(FsInode inode) throws ChimeraFsException {
PinManagerUnpinMessage message = new PinManagerUnpinMessage(new PnfsId(inode.getId()));
Subject subject = getSubjectFromContext();
message.setSubject(subject);
try {
message.setRequestId(getRequestId(subject));
pinManagerStub.sendAndWait(message);
} catch (PermissionDeniedCacheException e) {
/* Trigger returning NFSERR_PERM back to client. The Linux kernel
* should convert this to an EPERM response.
*/
throw new PermissionDeniedChimeraFsException(e.getMessage(), e);
} catch (NoRouteToCellException | InterruptedException | CacheException e) {
/* We "notify" the client that there was a problem unpinning the
* the file by returning NFSERR_INVAL back to the client. The Linux
* kernel should convert this to an EINVAL response.
*/
throw new InvalidArgumentChimeraException(e.getMessage(), e);
}
}
use of diskCacheV111.util.PermissionDeniedCacheException in project dcache by dCache.
the class FileResources method cmrResources.
@POST
@ApiOperation(value = "Modify a file or directory.")
@Path("{path : .*}")
@ApiResponses({ @ApiResponse(code = 400, message = "Transition for directories not supported"), @ApiResponse(code = 400, message = "Unsupported QoS transition"), @ApiResponse(code = 400, message = "Unknown target QoS"), @ApiResponse(code = 400, message = "Unknown action"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 409, message = "Attribute already exists"), @ApiResponse(code = 409, message = "No such attribute"), @ApiResponse(code = 500, message = "Internal Server Error") })
@Consumes({ MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON)
public Response cmrResources(@ApiParam(value = "Path of file or directory to be modified.", required = true) @PathParam("path") String requestPath, @ApiParam(value = "A JSON object that has an 'action' " + "item with a String value.\n" + "\n" + "If the 'action' value is 'mkdir' " + "then a new directory is created " + "with the name taken from the " + "value of the JSON object 'name' " + "item. This directory is created " + "within the supplied path parameter, " + "which must be an existing directory.\n" + "\n" + "If action is 'mv' then the file " + "or directory specified by the path " + "parameter is moved and/or " + "renamed with the value of the JSON " + "object 'destination' item describing " + "the final location. If the " + "'destination' value is a relative " + "path then it is resolved against " + "the path parameter value.\n" + "\n" + "If action is 'qos' then the value " + "of the JSON object 'target' item " + "describes the desired QoS." + "\n" + "If action is 'pin' then the default " + "value of lifetime is 0 and liftime-unit " + "SECONDS." + "\n" + "If action is 'rm-xattr' then " + "extended attributes of a file " + "or directory are removed as " + "given by the 'names' item. The " + "'names' value is either a " + "string or an array of strings." + "\n" + "If action is 'set-xattr' then " + "extended attributes are created " + "or modified. The optional " + "'mode' item controls whether to " + "create a new attribute (CREATE), " + "to modify an existing attribute " + "(MODIFY), or to assign the value " + "by either creating a new " + "attribute or modifying an " + "existing attribute (EITHER). " + "EITHER is the default mode. The " + "'attributes' item value is a JSON " + "Object with the new attributes," + "where the JSON Object's key is " + "the attribute name and the " + "corresponding JSON Object's " + "value is this attribute's value." + "\n" + "If action is 'set-label' then " + "a label is added to the" + "given file object." + "'label' item value is a String." + "\n" + "If action is 'rm-label' then the corresponding" + "label of a file is removed." + "The 'label' value is either a string." + "\n" + "If action is 'chgrp' then the " + "command requests the change of " + "group-owner of the target file " + "or directory. The value of the " + "JSON object 'gid' item is the " + "numerical value of the desired " + "new group-owner." + "\n" + "If action is 'chmod' then the " + "command reqests the change of " + "the target file's or directory's " + "permissions. The value of the " + "JSON object 'mode' item is the " + "numerical value of the desired " + "mode.", required = true, examples = @Example({ @ExampleProperty(mediaType = "MV", value = "{\n" + " \"action\" : \"mv\",\n" + " \"destination\" : \"../foo\"\n" + "}"), @ExampleProperty(mediaType = "MKDIR", value = "{\n" + " \"action\" : \"mkdir\",\n" + " \"name\" : \"new-subdir\"\n" + "}"), @ExampleProperty(mediaType = "QOS", value = "{\n" + " \"action\" : \"qos\",\n" + " \"target\" : \"DISK+TAPE\"\n" + "}"), @ExampleProperty(mediaType = "PIN", value = "{\n" + " \"action\" : \"pin\",\n" + " \"lifetime\" : \"number\"\n" + " \"lifetime-unit\" : \"SECONDS|MINUTES|HOURS|DAYS\"\n" + "}"), @ExampleProperty(mediaType = "UNPIN", value = "{\n" + " \"action\" : \"unpin\",\n" + "}"), @ExampleProperty(mediaType = "SET-XATTR", value = "{\n" + " \"action\" : \"set-xattr\",\n" + " \"mode\" : \"CREATE\",\n" + " \"attributes\" : {\n" + " \"attr-1\": \"First attribute\",\n" + " \"attr-2\": \"Second attribute\"\n" + " }\n" + "}"), @ExampleProperty(mediaType = "RM-XATTR", value = "{\n" + " \"action\" : \"rm-xattr\",\n" + " \"names\" : [\n" + " \"attr-1\",\n" + " \"attr-2\"\n" + " ]\n" + "}"), @ExampleProperty(mediaType = "SET-LABEL", value = "{\n" + " \"action\" : \"set-label\",\n" + " \"label\" : : \"label\",\n" + "}"), @ExampleProperty(mediaType = "RM-LABEL", value = "{\n" + " \"action\" : \"rm-label\",\n" + " \"label\" : \"label\",\n" + "}"), @ExampleProperty(mediaType = "CHGRP", value = "{\n" + " \"action\" : \"chgrp\",\n" + " \"gid\" : 1000\n" + "}"), @ExampleProperty(mediaType = "CHMOD", value = "{\n" + " \"action\" : \"chmod\",\n" + " \"mode\" : 493\n" + "}") })) String requestPayload) {
try {
JSONObject reqPayload = new JSONObject(requestPayload);
String action = (String) reqPayload.get("action");
PnfsHandler pnfsHandler = HandlerBuilders.roleAwarePnfsHandler(pnfsmanager);
FsPath path = pathMapper.asDcachePath(request, requestPath, ForbiddenException::new);
PnfsId pnfsId;
Long uid;
switch(action) {
case "mkdir":
String name = (String) reqPayload.get("name");
FsPath.checkChildName(name, BadRequestException::new);
pnfsHandler = HandlerBuilders.pnfsHandler(// FIXME: non-role identity to ensure correct ownership
pnfsmanager);
pnfsHandler.createPnfsDirectory(path.child(name).toString());
break;
case "mv":
String dest = (String) reqPayload.get("destination");
FsPath target = pathMapper.resolve(request, path, dest);
pnfsHandler.renameEntry(path.toString(), target.toString(), true);
break;
case "qos":
String targetQos = reqPayload.getString("target");
new QoSTransitionEngine(poolmanager, poolMonitor, pnfsHandler, pinmanager).adjustQoS(path, targetQos, request.getRemoteHost());
break;
case "pin":
Integer lifetime = reqPayload.optInt("lifetime");
if (lifetime == null) {
lifetime = 0;
}
String lifetimeUnitVal = reqPayload.optString("lifetime-unit");
TimeUnit lifetimeUnit = lifetimeUnitVal == null ? TimeUnit.SECONDS : TimeUnit.valueOf(lifetimeUnitVal);
pnfsId = pnfsHandler.getPnfsIdByPath(path.toString());
/*
* Fire-and-forget, as it was in 5.2
*/
pinmanager.notify(new PinManagerPinMessage(FileAttributes.ofPnfsId(pnfsId), getProtocolInfo(), getRequestId(), lifetimeUnit.toMillis(lifetime)));
break;
case "unpin":
pnfsId = pnfsHandler.getPnfsIdByPath(path.toString());
PinManagerUnpinMessage message = new PinManagerUnpinMessage(pnfsId);
message.setRequestId(getRequestId());
pinmanager.notify(message);
break;
case "rm-xattr":
Object namesArgument = reqPayload.get("names");
if (namesArgument instanceof String) {
pnfsHandler.removeExtendedAttribute(path, (String) namesArgument);
} else if (namesArgument instanceof JSONArray) {
JSONArray namesArray = (JSONArray) namesArgument;
List<String> names = new ArrayList<>(namesArray.length());
for (int i = 0; i < namesArray.length(); i++) {
names.add(namesArray.getString(i));
}
pnfsHandler.removeExtendedAttribute(path, names);
} else {
throw new JSONException("\"names\" is not a String or an array");
}
break;
case "set-xattr":
String modeString = reqPayload.optString("mode", "EITHER");
Mode xattrSetMode = modeOf(modeString);
JSONObject attributeOject = reqPayload.getJSONObject("attributes");
Map<String, byte[]> attributes = new HashMap<>(attributeOject.length());
for (String key : attributeOject.keySet()) {
String value = attributeOject.getString(key);
attributes.put(key, value.getBytes(StandardCharsets.UTF_8));
}
pnfsHandler.writeExtendedAttribute(path, attributes, xattrSetMode);
break;
case "set-label":
String label = reqPayload.getString("label");
pnfsHandler.setFileAttributes(path, FileAttributes.ofLabel(label));
break;
case "rm-label":
String labelsArgument = reqPayload.getString("label");
pnfsHandler.removeLabel(path, labelsArgument);
break;
case "chgrp":
int gid = reqPayload.getInt("gid");
pnfsHandler.setFileAttributes(path, FileAttributes.ofGid(gid));
break;
case "chmod":
int mode = reqPayload.getInt("mode");
pnfsHandler.setFileAttributes(path, FileAttributes.ofMode(mode));
break;
default:
throw new UnsupportedOperationException("No such action " + action);
}
} catch (FileNotFoundCacheException e) {
throw new NotFoundException(e);
} catch (PermissionDeniedCacheException e) {
if (RequestUser.isAnonymous()) {
throw new NotAuthorizedException(e);
} else {
throw new ForbiddenException(e);
}
} catch (AttributeExistsCacheException e) {
throw new WebApplicationException(Response.status(409, "Attribute already exist").build());
} catch (NoAttributeCacheException e) {
throw new WebApplicationException(Response.status(409, "No such attribute").build());
} catch (UnsupportedOperationException | URISyntaxException | JSONException | CacheException | InterruptedException | NoRouteToCellException e) {
throw new BadRequestException(e.getMessage(), e);
}
return successfulResponse(Response.Status.CREATED);
}
use of diskCacheV111.util.PermissionDeniedCacheException in project dcache by dCache.
the class FileResources method getFileAttributes.
@GET
@ApiOperation(value = "Find metadata and optionally directory contents.", notes = "The method offers the possibility to list the content of a " + "directory in addition to providing metadata of a " + "specified file or directory.")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal Server Error") })
@Path("{path : .*}")
@Produces(MediaType.APPLICATION_JSON)
public JsonFileAttributes getFileAttributes(@ApiParam("Path of file or directory.") @PathParam("path") String requestPath, @ApiParam("Whether to include directory listing.") @DefaultValue("false") @QueryParam("children") boolean isList, @ApiParam("Whether to include file locality information.") @DefaultValue("false") @QueryParam("locality") boolean isLocality, @ApiParam(value = "Whether to include replica locations.") @QueryParam("locations") boolean isLocations, @ApiParam(value = "Whether to include quality of service.") @DefaultValue("false") @QueryParam("qos") boolean isQos, @ApiParam("Whether to include extended attributes.") @QueryParam("xattr") boolean isXattr, @ApiParam("Whether to include labels.") @QueryParam("labels") boolean isLabels, @ApiParam("Whether or not to list checksum values.") @QueryParam("checksum") boolean isChecksum, @ApiParam("Limit number of replies in directory listing.") @QueryParam("limit") String limit, @ApiParam("Number of entries to skip in directory listing.") @QueryParam("offset") String offset) throws CacheException {
JsonFileAttributes fileAttributes = new JsonFileAttributes();
Set<FileAttribute> attributes = NamespaceUtils.getRequestedAttributes(isLocality, isLocations, isQos, isChecksum, false);
PnfsHandler handler = HandlerBuilders.roleAwarePnfsHandler(pnfsmanager);
FsPath path = pathMapper.asDcachePath(request, requestPath, ForbiddenException::new);
try {
FileAttributes namespaceAttributes = handler.getFileAttributes(path, attributes);
NamespaceUtils.chimeraToJsonAttributes(path.name(), fileAttributes, namespaceAttributes, isLocality, isLocations, isLabels, false, isXattr, isChecksum, request, poolMonitor);
if (isQos) {
NamespaceUtils.addQoSAttributes(fileAttributes, namespaceAttributes, request, poolMonitor, pinmanager);
}
// fill children list id it's a directory and listing is requested
if (namespaceAttributes.getFileType() == FileType.DIR && isList) {
Range<Integer> range;
try {
int lower = (offset == null) ? 0 : Integer.parseInt(offset);
int ceiling = (limit == null) ? Integer.MAX_VALUE : Integer.parseInt(limit);
if (ceiling < 0 || lower < 0) {
throw new BadRequestException("limit and offset can not be less than zero.");
}
range = (Integer.MAX_VALUE - lower < ceiling) ? Range.atLeast(lower) : Range.closedOpen(lower, lower + ceiling);
} catch (NumberFormatException e) {
throw new BadRequestException("limit and offset must be an integer value.");
}
List<JsonFileAttributes> children = new ArrayList<>();
DirectoryStream stream = listDirectoryHandler.list(HttpServletRequests.roleAwareSubject(request), HttpServletRequests.roleAwareRestriction(request), path, null, range, attributes);
for (DirectoryEntry entry : stream) {
String fName = entry.getName();
JsonFileAttributes childrenAttributes = new JsonFileAttributes();
NamespaceUtils.chimeraToJsonAttributes(fName, childrenAttributes, entry.getFileAttributes(), isLocality, isLocations, isLabels, false, isXattr, isChecksum, request, poolMonitor);
childrenAttributes.setFileName(fName);
if (isQos) {
NamespaceUtils.addQoSAttributes(childrenAttributes, entry.getFileAttributes(), request, poolMonitor, pinmanager);
}
children.add(childrenAttributes);
}
fileAttributes.setChildren(children);
}
} catch (FileNotFoundCacheException e) {
throw new NotFoundException(e);
} catch (PermissionDeniedCacheException e) {
if (RequestUser.isAnonymous()) {
throw new NotAuthorizedException(e);
} else {
throw new ForbiddenException(e);
}
} catch (CacheException | InterruptedException | NoRouteToCellException ex) {
LOG.warn(Exceptions.meaningfulMessage(ex));
throw new InternalServerErrorException(ex);
}
return fileAttributes;
}
Aggregations