Search in sources :

Example 61 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class FunDoctype method eval.

/* (non-Javadoc)
	 * @see org.exist.xquery.Expression#eval(org.exist.dom.persistent.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
	 */
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().start(this);
        context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
        if (contextSequence != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
        }
        if (contextItem != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
        }
    }
    final MutableDocumentSet docs = new DefaultDocumentSet();
    for (int i = 0; i < getArgumentCount(); i++) {
        final Sequence seq = getArgument(i).eval(contextSequence, contextItem);
        for (final SequenceIterator j = seq.iterate(); j.hasNext(); ) {
            final String next = j.nextItem().getStringValue();
            try {
                context.getBroker().getXMLResourcesByDoctype(next, docs);
            } catch (final PermissionDeniedException | LockException e) {
                LOG.error(e.getMessage(), e);
                throw new XPathException(this, e);
            }
        }
    }
    final NodeSet result = new ExtArrayNodeSet(1);
    for (final Iterator<DocumentImpl> i = docs.getDocumentIterator(); i.hasNext(); ) {
        result.add(new NodeProxy(i.next(), NodeId.DOCUMENT_NODE));
    }
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", result);
    }
    return result;
}
Also used : ExtArrayNodeSet(org.exist.dom.persistent.ExtArrayNodeSet) NodeSet(org.exist.dom.persistent.NodeSet) MutableDocumentSet(org.exist.dom.persistent.MutableDocumentSet) DefaultDocumentSet(org.exist.dom.persistent.DefaultDocumentSet) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy) ExtArrayNodeSet(org.exist.dom.persistent.ExtArrayNodeSet) LockException(org.exist.util.LockException) PermissionDeniedException(org.exist.security.PermissionDeniedException)

Example 62 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class DocUtils method getDocumentByPathFromDB.

private static Sequence getDocumentByPathFromDB(final XQueryContext context, final String path) throws XPathException, PermissionDeniedException {
    // check if the loaded documents should remain locked
    final LockMode lockType = context.lockDocumentsOnLoad() ? LockMode.WRITE_LOCK : LockMode.READ_LOCK;
    try {
        final XmldbURI baseURI = context.getBaseURI().toXmldbURI();
        final XmldbURI pathUri;
        if (baseURI != null && !(baseURI.equals("") || baseURI.equals("/db"))) {
            // relative collection Path: add the current base URI
            pathUri = baseURI.resolveCollectionPath(XmldbURI.xmldbUriFor(path, false));
        } else {
            pathUri = XmldbURI.xmldbUriFor(path, false);
        }
        // relative collection Path: add the current module call URI if applicable
        final XmldbURI resourceUri = Optional.ofNullable(context.getModuleLoadPath()).filter(moduleLoadPath -> !moduleLoadPath.isEmpty()).flatMap(moduleLoadPath -> Try(() -> XmldbURI.xmldbUriFor(moduleLoadPath)).toOption()).map(moduleLoadPath -> moduleLoadPath.resolveCollectionPath(pathUri)).orElse(pathUri);
        // try to open the document and acquire a lock
        try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(resourceUri, lockType)) {
            if (lockedDoc == null) {
                return Sequence.EMPTY_SEQUENCE;
            } else {
                final DocumentImpl doc = lockedDoc.getDocument();
                if (!doc.getPermissions().validate(context.getSubject(), Permission.READ)) {
                    throw new PermissionDeniedException("Insufficient privileges to read resource " + path);
                }
                if (doc.getResourceType() == DocumentImpl.BINARY_FILE) {
                    throw new XPathException("Document " + path + " is a binary resource, not an XML document. Please consider using the function util:binary-doc() to retrieve a reference to it.");
                }
                return new NodeProxy(doc);
            }
        }
    } catch (final URISyntaxException e) {
        throw new XPathException(e);
    }
}
Also used : LockMode(org.exist.storage.lock.Lock.LockMode) SAXNotSupportedException(org.xml.sax.SAXNotSupportedException) BrokerPool(org.exist.storage.BrokerPool) XMLReaderPool(org.exist.util.XMLReaderPool) ErrorCodes(org.exist.xquery.ErrorCodes) NodeProxy(org.exist.dom.persistent.NodeProxy) PermissionDeniedException(org.exist.security.PermissionDeniedException) SAXNotRecognizedException(org.xml.sax.SAXNotRecognizedException) XMLReader(org.xml.sax.XMLReader) Source(org.exist.source.Source) java.net(java.net) Namespaces(org.exist.Namespaces) Document(org.w3c.dom.Document) XmldbURI(org.exist.xmldb.XmldbURI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) Permission(org.exist.security.Permission) XQueryContext(org.exist.xquery.XQueryContext) Nullable(javax.annotation.Nullable) InputSource(org.xml.sax.InputSource) LockedDocument(org.exist.dom.persistent.LockedDocument) AnyURIValue(org.exist.xquery.value.AnyURIValue) IOException(java.io.IOException) Try(com.evolvedbinary.j8fu.Try.Try) URLSource(org.exist.source.URLSource) SAXException(org.xml.sax.SAXException) SourceFactory(org.exist.source.SourceFactory) Optional(java.util.Optional) Sequence(org.exist.xquery.value.Sequence) Pattern(java.util.regex.Pattern) SAXAdapter(org.exist.dom.memtree.SAXAdapter) XPathException(org.exist.xquery.XPathException) InputStream(java.io.InputStream) XPathException(org.exist.xquery.XPathException) LockedDocument(org.exist.dom.persistent.LockedDocument) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockMode(org.exist.storage.lock.Lock.LockMode) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy) XmldbURI(org.exist.xmldb.XmldbURI)

Example 63 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class Insert method eval.

/* (non-Javadoc)
     * @see org.exist.xquery.AbstractExpression#eval(org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
     */
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().start(this);
        context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
        if (contextSequence != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
        }
        if (contextItem != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
        }
    }
    if (contextItem != null) {
        contextSequence = contextItem.toSequence();
    }
    Sequence contentSeq = value.eval(contextSequence);
    if (contentSeq.isEmpty()) {
        throw new XPathException(this, Messages.getMessage(Error.UPDATE_EMPTY_CONTENT));
    }
    final Sequence inSeq = select.eval(contextSequence);
    /* If we try and Insert a node at an invalid location,
         * trap the error in a context variable,
         * this is then accessible from xquery via. the context extension module - deliriumsky
         * TODO: This trapping could be expanded further - basically where XPathException is thrown from thiss class
         * TODO: Maybe we could provide more detailed messages in the trap, e.g. couldnt insert node `xyz` into `abc` becuase... this would be nicer for the end user of the xquery application 
         */
    if (!Type.subTypeOf(inSeq.getItemType(), Type.NODE)) {
        // Indicate the failure to perform this update by adding it to the sequence in the context variable XQueryContext.XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR
        ValueSequence prevUpdateErrors = null;
        final XPathException xpe = new XPathException(this, Messages.getMessage(Error.UPDATE_SELECT_TYPE));
        final Object ctxVarObj = context.getAttribute(XQueryContext.XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR);
        if (ctxVarObj == null) {
            prevUpdateErrors = new ValueSequence();
        } else {
            prevUpdateErrors = (ValueSequence) XPathUtil.javaObjectToXPath(ctxVarObj, context);
        }
        prevUpdateErrors.add(new StringValue(xpe.getMessage()));
        context.setAttribute(XQueryContext.XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR, prevUpdateErrors);
        if (!inSeq.isEmpty()) {
            // TODO: should we trap this instead of throwing an exception - deliriumsky?
            throw xpe;
        }
    }
    if (!inSeq.isEmpty()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found: {} nodes", inSeq.getItemCount());
        }
        context.pushInScopeNamespaces();
        contentSeq = deepCopy(contentSeq);
        // start a transaction
        try (final Txn transaction = getTransaction()) {
            final StoredNode[] ql = selectAndLock(transaction, inSeq);
            final NotificationService notifier = context.getBroker().getBrokerPool().getNotificationService();
            final NodeList contentList = seq2nodeList(contentSeq);
            for (final StoredNode node : ql) {
                final DocumentImpl doc = node.getOwnerDocument();
                if (!doc.getPermissions().validate(context.getSubject(), Permission.WRITE)) {
                    throw new PermissionDeniedException("User '" + context.getSubject().getName() + "' does not have permission to write to the document '" + doc.getDocumentURI() + "'!");
                }
                // update the document
                if (mode == INSERT_APPEND) {
                    node.appendChildren(transaction, contentList, -1);
                } else {
                    final NodeImpl parent = (NodeImpl) getParent(node);
                    switch(mode) {
                        case INSERT_BEFORE:
                            parent.insertBefore(transaction, contentList, node);
                            break;
                        case INSERT_AFTER:
                            parent.insertAfter(transaction, contentList, node);
                            break;
                    }
                }
                doc.setLastModified(System.currentTimeMillis());
                modifiedDocuments.add(doc);
                context.getBroker().storeXMLResource(transaction, doc);
                notifier.notifyUpdate(doc, UpdateListener.UPDATE);
            }
            finishTriggers(transaction);
            // commit the transaction
            transaction.commit();
        } catch (final PermissionDeniedException | EXistException | LockException | TriggerException e) {
            throw new XPathException(this, e.getMessage(), e);
        } finally {
            unlockDocuments();
            context.popInScopeNamespaces();
        }
    }
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", Sequence.EMPTY_SEQUENCE);
    }
    return Sequence.EMPTY_SEQUENCE;
}
Also used : NodeImpl(org.exist.dom.persistent.NodeImpl) XPathException(org.exist.xquery.XPathException) NodeList(org.w3c.dom.NodeList) NotificationService(org.exist.storage.NotificationService) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) Txn(org.exist.storage.txn.Txn) EXistException(org.exist.EXistException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) LockException(org.exist.util.LockException) ValueSequence(org.exist.xquery.value.ValueSequence) PermissionDeniedException(org.exist.security.PermissionDeniedException) StringValue(org.exist.xquery.value.StringValue) TriggerException(org.exist.collections.triggers.TriggerException) StoredNode(org.exist.dom.persistent.StoredNode)

Example 64 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class MetadataFunctions method extractMetadataFromLocalResource.

private Sequence extractMetadataFromLocalResource(final XmldbURI docUri) throws XPathException {
    try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(docUri, LockMode.READ_LOCK)) {
        if (lockedDoc != null && lockedDoc.getDocument() instanceof BinaryDocument) {
            final BinaryDocument binDoc = (BinaryDocument) lockedDoc.getDocument();
            final BrokerPool pool = context.getBroker().getBrokerPool();
            final BlobStore blobStore = pool.getBlobStore();
            try (final Txn transaction = pool.getTransactionManager().beginTransaction()) {
                final Sequence result = blobStore.with(transaction, binDoc.getBlobId(), blobFile -> TaggedTryUnchecked(XPathException.class, () -> exifToolExtract(blobFile))).get();
                transaction.commit();
                return result;
            }
        } else {
            throw new XPathException(this, "The binary document at " + docUri.toString() + " cannot be found.");
        }
    } catch (PermissionDeniedException | IOException | TransactionException e) {
        throw new XPathException(this, "Could not access binary document: " + e.getMessage(), e);
    }
}
Also used : BinaryDocument(org.exist.dom.persistent.BinaryDocument) LockMode(org.exist.storage.lock.Lock.LockMode) Txn(org.exist.storage.txn.Txn) BrokerPool(org.exist.storage.BrokerPool) SequenceType(org.exist.xquery.value.SequenceType) FunctionParameterSequenceType(org.exist.xquery.value.FunctionParameterSequenceType) QName(org.exist.dom.QName) URISyntaxException(java.net.URISyntaxException) FunctionSignature(org.exist.xquery.FunctionSignature) PermissionDeniedException(org.exist.security.PermissionDeniedException) Cardinality(org.exist.xquery.Cardinality) BlobStore(org.exist.storage.blob.BlobStore) BasicFunction(org.exist.xquery.BasicFunction) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) Source(org.exist.source.Source) FunctionReturnSequenceType(org.exist.xquery.value.FunctionReturnSequenceType) XmldbURI(org.exist.xmldb.XmldbURI) URI(java.net.URI) Path(java.nio.file.Path) XQueryContext(org.exist.xquery.XQueryContext) OutputStream(java.io.OutputStream) InputSource(org.xml.sax.InputSource) LockedDocument(org.exist.dom.persistent.LockedDocument) Type(org.exist.xquery.value.Type) IOException(java.io.IOException) TransactionException(org.exist.storage.txn.TransactionException) Logger(org.apache.logging.log4j.Logger) TaggedTryUnchecked(com.evolvedbinary.j8fu.Try.TaggedTryUnchecked) ModuleUtils(org.exist.xquery.modules.ModuleUtils) SAXException(org.xml.sax.SAXException) SourceFactory(org.exist.source.SourceFactory) Sequence(org.exist.xquery.value.Sequence) LogManager(org.apache.logging.log4j.LogManager) BinaryDocument(org.exist.dom.persistent.BinaryDocument) XPathException(org.exist.xquery.XPathException) InputStream(java.io.InputStream) TransactionException(org.exist.storage.txn.TransactionException) XPathException(org.exist.xquery.XPathException) LockedDocument(org.exist.dom.persistent.LockedDocument) PermissionDeniedException(org.exist.security.PermissionDeniedException) Txn(org.exist.storage.txn.Txn) Sequence(org.exist.xquery.value.Sequence) IOException(java.io.IOException) BrokerPool(org.exist.storage.BrokerPool) BlobStore(org.exist.storage.blob.BlobStore)

Example 65 with PermissionDeniedException

use of org.exist.security.PermissionDeniedException in project exist by eXist-db.

the class ZipEntryFunctions method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    final XmldbURI uri = ((AnyURIValue) args[0].itemAt(0)).toXmldbURI();
    final String entryName = args[1].itemAt(0).getStringValue();
    final ZipFileSource zipFileSource = new ZipFileFromDb(uri);
    ZipInputStream zis = null;
    boolean mustClose = true;
    Sequence result = Sequence.EMPTY_SEQUENCE;
    try {
        zis = zipFileSource.getStream(context.getBroker());
        ZipEntry zipEntry;
        while ((zipEntry = zis.getNextEntry()) != null) {
            try {
                if (zipEntry.getName().equals(entryName)) {
                    // process
                    if (isCalledAs(BINARY_ENTRY_NAME)) {
                        result = extractBinaryEntry(zis);
                        mustClose = false;
                    } else if (isCalledAs(HTML_ENTRY_NAME)) {
                        result = extractHtmlEntry(zis);
                    } else if (isCalledAs(TEXT_ENTRY_NAME)) {
                        result = extractStringEntry(zis);
                    } else if (isCalledAs(XML_ENTRY_NAME)) {
                        result = extractXmlEntry(zis);
                    }
                    break;
                }
            } finally {
            // DONT need to close as the extract functions
            // close the stream on the zip entry
            /*if(mustClose) {
                        zis.closeEntry();
                    }*/
            }
        }
    } catch (final IOException | PermissionDeniedException ioe) {
        LOG.error(ioe.getMessage(), ioe);
        throw new XPathException(this, ioe.getMessage(), ioe);
    } finally {
        if (zis != null && mustClose) {
            try {
                zis.close();
            } catch (final IOException ioe) {
                LOG.warn(ioe.getMessage(), ioe);
            }
        }
        zipFileSource.close();
    }
    return result;
}
Also used : XPathException(org.exist.xquery.XPathException) AnyURIValue(org.exist.xquery.value.AnyURIValue) ZipEntry(java.util.zip.ZipEntry) Sequence(org.exist.xquery.value.Sequence) IOException(java.io.IOException) ZipInputStream(java.util.zip.ZipInputStream) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Aggregations

PermissionDeniedException (org.exist.security.PermissionDeniedException)182 EXistException (org.exist.EXistException)82 XmldbURI (org.exist.xmldb.XmldbURI)70 IOException (java.io.IOException)58 DocumentImpl (org.exist.dom.persistent.DocumentImpl)48 Collection (org.exist.collections.Collection)44 DBBroker (org.exist.storage.DBBroker)41 Txn (org.exist.storage.txn.Txn)38 LockException (org.exist.util.LockException)35 SAXException (org.xml.sax.SAXException)35 LockedDocument (org.exist.dom.persistent.LockedDocument)31 XPathException (org.exist.xquery.XPathException)31 Permission (org.exist.security.Permission)23 URISyntaxException (java.net.URISyntaxException)22 TriggerException (org.exist.collections.triggers.TriggerException)22 Source (org.exist.source.Source)20 Path (java.nio.file.Path)19 Account (org.exist.security.Account)18 InputSource (org.xml.sax.InputSource)18 Sequence (org.exist.xquery.value.Sequence)17