Search in sources :

Example 6 with Permission

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

the class SystemExport method export.

/**
 * Export a collection. Write out the collection metadata and save the resources stored in the collection.
 *
 * @param current    the collection
 * @param output     the output writer
 * @param date
 * @param prevBackup DOCUMENT ME!
 * @param errorList  a list of {@link org.exist.backup.ErrorReport} objects as returned by methods in {@link org.exist.backup.ConsistencyCheck}
 * @param docs       a document set to keep track of all written documents.
 * @throws IOException
 * @throws SAXException
 * @throws TerminatedException DOCUMENT ME!
 */
private void export(final BackupHandler bh, final Collection current, final BackupWriter output, final Date date, final BackupDescriptor prevBackup, final List<ErrorReport> errorList, final MutableDocumentSet docs) throws IOException, SAXException, TerminatedException, PermissionDeniedException {
    if ((monitor != null) && !monitor.proceed()) {
        throw (new TerminatedException("system export terminated by db"));
    }
    // if( !current.getURI().equalsInternal( XmldbURI.ROOT_COLLECTION_URI ) ) {
    output.newCollection(Backup.encode(URIUtils.urlDecodeUtf8(current.getURI())));
    // }
    final SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
    try {
        final Writer contents = output.newContents();
        // serializer writes to __contents__.xml
        serializer.setOutput(contents, contentsOutputProps);
        final Permission perm = current.getPermissionsNoLock();
        serializer.startDocument();
        serializer.startPrefixMapping("", Namespaces.EXIST_NS);
        final XmldbURI uri = current.getURI();
        final AttributesImpl attr = new AttributesImpl();
        attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", uri.toString());
        attr.addAttribute(Namespaces.EXIST_NS, "version", "version", "CDATA", String.valueOf(currVersion));
        Backup.writeUnixStylePermissionAttributes(attr, perm);
        try {
            attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", new DateTimeValue(new Date(current.getCreated())).getStringValue());
        } catch (final XPathException e) {
            e.printStackTrace();
        }
        bh.backup(current, attr);
        serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr);
        if (perm instanceof ACLPermission) {
            Backup.writeACLPermission(serializer, (ACLPermission) perm);
        }
        bh.backup(current, serializer);
        final int docsCount = current.getDocumentCountNoLock(broker);
        int count = 0;
        for (final Iterator<DocumentImpl> i = current.iteratorNoLock(broker); i.hasNext(); count++) {
            final DocumentImpl doc = i.next();
            if (isDamaged(doc, errorList)) {
                reportError("Skipping damaged document " + doc.getFileURI(), null);
                continue;
            }
            if (doc.getFileURI().equalsInternal(CONTENTS_URI) || doc.getFileURI().equalsInternal(LOST_URI)) {
                // skip __contents__.xml documents
                continue;
            }
            exportDocument(bh, output, date, prevBackup, serializer, docsCount, count, doc);
            docs.add(doc, false);
        }
        for (final Iterator<XmldbURI> i = current.collectionIteratorNoLock(broker); i.hasNext(); ) {
            final XmldbURI childUri = i.next();
            if (childUri.equalsInternal(TEMP_COLLECTION)) {
                continue;
            }
            if (isDamagedChild(childUri, errorList)) {
                reportError("Skipping damaged child collection " + childUri, null);
                continue;
            }
            attr.clear();
            attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", childUri.toString());
            attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", Backup.encode(URIUtils.urlDecodeUtf8(childUri.toString())));
            serializer.startElement(Namespaces.EXIST_NS, "subcollection", "subcollection", attr);
            serializer.endElement(Namespaces.EXIST_NS, "subcollection", "subcollection");
        }
        if (prevBackup != null) {
            // Check which collections and resources have been deleted since
            // the
            // last backup
            final CheckDeletedHandler check = new CheckDeletedHandler(current, serializer);
            try {
                prevBackup.parse(broker.getBrokerPool().getParserPool(), check);
            } catch (final Exception e) {
                LOG.error("Caught exception while trying to parse previous backup descriptor: {}", prevBackup.getSymbolicPath(), e);
            }
        }
        // close <collection>
        serializer.endElement(Namespaces.EXIST_NS, "collection", "collection");
        serializer.endPrefixMapping("");
        serializer.endDocument();
        output.closeContents();
    } finally {
        SerializerPool.getInstance().returnObject(serializer);
        // if( !current.getURI().equalsInternal( XmldbURI.ROOT_COLLECTION_URI ) ) {
        output.closeCollection();
    // }
    }
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) ACLPermission(org.exist.security.ACLPermission) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) TerminatedException(org.exist.xquery.TerminatedException) XMLStreamException(javax.xml.stream.XMLStreamException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) SAXSerializer(org.exist.util.serializer.SAXSerializer) TerminatedException(org.exist.xquery.TerminatedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 7 with Permission

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

the class SystemImportHandler method mkcol.

private Collection mkcol(final XmldbURI collPath, final Date created) throws SAXException {
    try (final Txn transaction = beginTransaction()) {
        final Tuple2<Permission, Long> creationAttributes = Tuple(null, created.getTime());
        final Collection col = broker.getOrCreateCollection(transaction, collPath, Optional.of(creationAttributes));
        transaction.commit();
        return col;
    } catch (final Exception e) {
        throw new SAXException(e);
    }
}
Also used : Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) Txn(org.exist.storage.txn.Txn) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) TransactionException(org.exist.storage.txn.TransactionException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) XPathException(org.exist.xquery.XPathException) SAXException(org.xml.sax.SAXException)

Example 8 with Permission

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

the class CollectionDeferredPermission method apply.

@Override
public void apply(final DBBroker broker, final Txn transaction) {
    try (final Collection collection = broker.openCollection(getTarget(), Lock.LockMode.WRITE_LOCK)) {
        final Permission permission = collection.getPermissions();
        PermissionFactory.chown(broker, permission, Optional.ofNullable(getOwner()), Optional.ofNullable(getGroup()));
        PermissionFactory.chmod(broker, permission, Optional.of(getMode()), Optional.ofNullable(permission instanceof ACLPermission ? getAces() : null));
        broker.saveCollection(transaction, collection);
    } catch (final PermissionDeniedException | IOException e) {
        final String msg = "ERROR: Failed to set permissions on Collection '" + getTarget() + "'.";
        LOG.error(msg, e);
        getListener().warn(msg);
    }
}
Also used : ACLPermission(org.exist.security.ACLPermission) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException)

Example 9 with Permission

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

the class ResourceDeferredPermission method apply.

@Override
public void apply(final DBBroker broker, final Txn transaction) {
    try (final LockedDocument lockedDoc = broker.getXMLResource(getTarget(), Lock.LockMode.WRITE_LOCK)) {
        final DocumentImpl doc = lockedDoc.getDocument();
        final Permission permission = doc.getPermissions();
        PermissionFactory.chown(broker, permission, Optional.ofNullable(getOwner()), Optional.ofNullable(getGroup()));
        PermissionFactory.chmod(broker, permission, Optional.of(getMode()), Optional.ofNullable(permission instanceof ACLPermission ? getAces() : null));
        broker.storeXMLResource(transaction, doc);
    } catch (final PermissionDeniedException e) {
        final String msg = "ERROR: Failed to set permissions on Document '" + getTarget() + "'.";
        LOG.error(msg, e);
        getListener().warn(msg);
    }
}
Also used : ACLPermission(org.exist.security.ACLPermission) LockedDocument(org.exist.dom.persistent.LockedDocument) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) PermissionDeniedException(org.exist.security.PermissionDeniedException) DocumentImpl(org.exist.dom.persistent.DocumentImpl)

Example 10 with Permission

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

the class RestoreHandler method restoreCollectionEntry.

private DeferredPermission restoreCollectionEntry(final Attributes atts) throws SAXException {
    final String name = atts.getValue("name");
    if (name == null) {
        throw new SAXException("Collection requires a name attribute");
    }
    final String owner = getAttr(atts, "owner", SecurityManager.SYSTEM);
    final String group = getAttr(atts, "group", SecurityManager.DBA_GROUP);
    final String mode = getAttr(atts, "mode", "644");
    final String created = atts.getValue("created");
    final String strVersion = atts.getValue("version");
    if (strVersion != null) {
        try {
            this.version = Integer.parseInt(strVersion);
        } catch (final NumberFormatException nfe) {
            final String msg = "Could not parse version number for Collection '" + name + "', defaulting to version 0";
            listener.warn(msg);
            LOG.warn(msg);
            this.version = 0;
        }
    }
    try {
        listener.createdCollection(name);
        final XmldbURI collUri;
        if (version >= STRICT_URI_VERSION) {
            collUri = XmldbURI.create(name);
        } else {
            try {
                collUri = URIUtils.encodeXmldbUriFor(name);
            } catch (final URISyntaxException e) {
                listener.warn("Could not parse document name into a URI: " + e.getMessage());
                return new SkippedEntryDeferredPermission();
            }
        }
        if (version >= BLOB_STORE_VERSION) {
            this.deduplicateBlobs = Boolean.parseBoolean(atts.getValue("deduplicate-blobs"));
        } else {
            this.deduplicateBlobs = false;
        }
        final LockManager lockManager = broker.getBrokerPool().getLockManager();
        try (final Txn transaction = beginTransaction();
            final ManagedCollectionLock colLock = lockManager.acquireCollectionWriteLock(collUri)) {
            Collection collection = broker.getCollection(collUri);
            if (collection == null) {
                final Tuple2<Permission, Long> creationAttributes = Tuple(null, getDateFromXSDateTimeStringForItem(created, name).getTime());
                collection = broker.getOrCreateCollection(transaction, collUri, Optional.of(creationAttributes));
                broker.saveCollection(transaction, collection);
            }
            transaction.commit();
            this.currentCollectionUri = collection.getURI();
        }
        final DeferredPermission deferredPermission;
        if (name.startsWith(XmldbURI.SYSTEM_COLLECTION)) {
            // prevents restore of a backup from changing System collection ownership
            deferredPermission = new CollectionDeferredPermission(listener, currentCollectionUri, SecurityManager.SYSTEM, SecurityManager.DBA_GROUP, Integer.parseInt(mode, 8));
        } else {
            deferredPermission = new CollectionDeferredPermission(listener, currentCollectionUri, owner, group, Integer.parseInt(mode, 8));
        }
        return deferredPermission;
    } catch (final IOException | LockException | TransactionException | PermissionDeniedException e) {
        final String msg = "An unrecoverable error occurred while restoring collection '" + name + "': " + e.getMessage() + ". Aborting restore!";
        LOG.error(msg, e);
        listener.warn(msg);
        throw new SAXException(msg, e);
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) Txn(org.exist.storage.txn.Txn) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) LockManager(org.exist.storage.lock.LockManager) TransactionException(org.exist.storage.txn.TransactionException) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) Collection(org.exist.collections.Collection) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI) ManagedCollectionLock(org.exist.storage.lock.ManagedCollectionLock)

Aggregations

Permission (org.exist.security.Permission)49 XmldbURI (org.exist.xmldb.XmldbURI)23 PermissionDeniedException (org.exist.security.PermissionDeniedException)19 ACLPermission (org.exist.security.ACLPermission)18 Collection (org.exist.collections.Collection)17 Test (org.junit.Test)14 IOException (java.io.IOException)11 Subject (org.exist.security.Subject)11 SAXException (org.xml.sax.SAXException)9 EXistException (org.exist.EXistException)7 DocumentImpl (org.exist.dom.persistent.DocumentImpl)7 ACEAider (org.exist.security.internal.aider.ACEAider)7 Txn (org.exist.storage.txn.Txn)6 XMLDBException (org.xmldb.api.base.XMLDBException)6 URISyntaxException (java.net.URISyntaxException)4 XMLStreamException (javax.xml.stream.XMLStreamException)4 Account (org.exist.security.Account)4 TerminatedException (org.exist.xquery.TerminatedException)4 XPathException (org.exist.xquery.XPathException)4 DateTimeValue (org.exist.xquery.value.DateTimeValue)4