Search in sources :

Example 1 with ACLPermission

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

the class SystemExport method exportDocument.

private void exportDocument(final BackupHandler bh, final BackupWriter output, final Date date, final BackupDescriptor prevBackup, final SAXSerializer serializer, final int docsCount, final int count, final DocumentImpl doc) throws IOException, SAXException, TerminatedException {
    if (callback != null) {
        callback.startDocument(doc.getFileURI().toString(), count, docsCount);
    }
    if ((monitor != null) && !monitor.proceed()) {
        throw (new TerminatedException("system export terminated by db"));
    }
    final boolean needsBackup = (prevBackup == null) || (date.getTime() < doc.getLastModified());
    if (needsBackup) {
        // Note: do not auto-close the output stream or the zip will be closed!
        try {
            final OutputStream os = output.newEntry(Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
            if (doc.getResourceType() == DocumentImpl.BINARY_FILE) {
                broker.readBinaryResource((BinaryDocument) doc, os);
            } else {
                final SAXSerializer contentSerializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
                final Writer writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
                try {
                    // write resource to contentSerializer
                    contentSerializer.setOutput(writer, defaultOutputProperties);
                    final Receiver receiver;
                    if (chainFactory != null) {
                        chainFactory.getLast().setNextInChain(contentSerializer);
                        receiver = chainFactory.getFirst();
                    } else {
                        receiver = contentSerializer;
                    }
                    writeXML(doc, receiver);
                } finally {
                    SerializerPool.getInstance().returnObject(contentSerializer);
                    writer.flush();
                }
            }
        } catch (final Exception e) {
            reportError("A write error occurred while exporting document: '" + doc.getFileURI() + "'. Continuing with next document.", e);
            return;
        } finally {
            output.closeEntry();
        }
    }
    final Permission perms = doc.getPermissions();
    // store permissions
    final AttributesImpl attr = new AttributesImpl();
    attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", (doc.getResourceType() == DocumentImpl.BINARY_FILE) ? "BinaryResource" : "XMLResource");
    attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", doc.getFileURI().toString());
    attr.addAttribute(Namespaces.EXIST_NS, "skip", "skip", "CDATA", (needsBackup ? "no" : "yes"));
    Backup.writeUnixStylePermissionAttributes(attr, perms);
    try {
        final String created = new DateTimeValue(new Date(doc.getCreated())).getStringValue();
        final String modified = new DateTimeValue(new Date(doc.getLastModified())).getStringValue();
        attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", created);
        attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", modified);
    } catch (final XPathException e) {
        LOG.warn(e.getMessage(), e);
    }
    attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", Backup.encode(URIUtils.urlDecodeUtf8(doc.getFileURI())));
    String mimeType = "application/xml";
    if (doc.getMimeType() != null) {
        mimeType = Backup.encode(doc.getMimeType());
    }
    attr.addAttribute(Namespaces.EXIST_NS, "mimetype", "mimetype", "CDATA", mimeType);
    // output by serializer
    // if( ( doc.getResourceType() == DocumentImpl.XML_FILE ) && ( metadata != null ) && ( doc.getDoctype() != null ) ) {
    // 
    // if( doc.getDoctype().getName() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "namedoctype", "namedoctype", "CDATA", doc.getDoctype().getName() );
    // }
    // 
    // if( doc.getDoctype().getPublicId() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "publicid", "publicid", "CDATA", doc.getDoctype().getPublicId() );
    // }
    // 
    // if( doc.getDoctype().getSystemId() != null ) {
    // attr.addAttribute( Namespaces.EXIST_NS, "systemid", "systemid", "CDATA", doc.getDoctype().getSystemId() );
    // }
    // }
    bh.backup(doc, attr);
    serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr);
    if (perms instanceof ACLPermission) {
        Backup.writeACLPermission(serializer, (ACLPermission) perms);
    }
    bh.backup(doc, serializer);
    serializer.endElement(Namespaces.EXIST_NS, "resource", "resource");
}
Also used : DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) ACLPermission(org.exist.security.ACLPermission) Receiver(org.exist.util.serializer.Receiver) 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)

Example 2 with ACLPermission

use of org.exist.security.ACLPermission 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 3 with ACLPermission

use of org.exist.security.ACLPermission 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 4 with ACLPermission

use of org.exist.security.ACLPermission 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 5 with ACLPermission

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

the class Backup method backup.

private void backup(final Set<String> seenBlobIds, final Collection current, final BackupWriter output, final BackupDialog dialog) throws XMLDBException, IOException, SAXException {
    if (current == null) {
        return;
    }
    current.setProperty(OutputKeys.ENCODING, defaultOutputProperties.getProperty(OutputKeys.ENCODING));
    current.setProperty(OutputKeys.INDENT, defaultOutputProperties.getProperty(OutputKeys.INDENT));
    current.setProperty(EXistOutputKeys.EXPAND_XINCLUDES, defaultOutputProperties.getProperty(EXistOutputKeys.EXPAND_XINCLUDES));
    current.setProperty(EXistOutputKeys.PROCESS_XSL_PI, defaultOutputProperties.getProperty(EXistOutputKeys.PROCESS_XSL_PI));
    // get collections and documents
    final String[] collections = current.listChildCollections();
    final String[] resources = current.listResources();
    // do not sort: order is important because permissions need to be read in the same order below
    // Arrays.sort( resources );
    final UserManagementService mgtService = (UserManagementService) current.getService("UserManagementService", "1.0");
    final Permission[] perms = mgtService.listResourcePermissions();
    final Permission currentPerms = mgtService.getPermissions(current);
    if (dialog != null) {
        dialog.setCollection(current.getName());
        dialog.setResourceCount(resources.length);
    }
    final Writer contents = output.newContents();
    // serializer writes to __contents__.xml
    final SAXSerializer serializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
    try {
        serializer.setOutput(contents, contentsOutputProps);
        serializer.startDocument();
        serializer.startPrefixMapping("", Namespaces.EXIST_NS);
        // write <collection> element
        final EXistCollection cur = (EXistCollection) current;
        final AttributesImpl attr = new AttributesImpl();
        // The name should have come from an XmldbURI.toString() call
        attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", current.getName());
        writeUnixStylePermissionAttributes(attr, currentPerms);
        attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", "" + new DateTimeValue(cur.getCreationTime()));
        attr.addAttribute(Namespaces.EXIST_NS, "deduplicate-blobs", "deduplicate-blobs", "CDATA", Boolean.toString(deduplicateBlobs));
        attr.addAttribute(Namespaces.EXIST_NS, "version", "version", "CDATA", String.valueOf(BACKUP_FORMAT_VERSION));
        serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr);
        if (currentPerms instanceof ACLPermission) {
            writeACLPermission(serializer, (ACLPermission) currentPerms);
        }
        // scan through resources
        for (int i = 0; i < resources.length; i++) {
            try {
                if ("__contents__.xml".equals(resources[i])) {
                    // Skipping resources[i]
                    continue;
                }
                final Resource resource = current.getResource(resources[i]);
                if (dialog != null) {
                    dialog.setResource(resources[i]);
                    dialog.setProgress(i);
                }
                // Avoid NPE
                if (resource == null) {
                    final String msg = "Resource " + resources[i] + " could not be found.";
                    if (dialog != null) {
                        Object[] options = { "Ignore", "Abort" };
                        int n = JOptionPane.showOptionDialog(null, msg, "Backup Error", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
                        if (n == JOptionPane.YES_OPTION) {
                            // ignore one
                            continue;
                        }
                        // Abort
                        dialog.dispose();
                        JOptionPane.showMessageDialog(null, "Backup aborted.", "Abort", JOptionPane.WARNING_MESSAGE);
                    }
                    throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, msg);
                }
                final String name = resources[i];
                String filename = encode(URIUtils.urlDecodeUtf8(resources[i]));
                if (".".equals(name.trim())) {
                    filename = EXIST_GENERATED_FILENAME_DOT_FILENAME + i;
                } else if ("..".equals(name.trim())) {
                    filename = EXIST_GENERATED_FILENAME_DOTDOT_FILENAME + i;
                }
                final OutputStream os;
                if (resource instanceof ExtendedResource) {
                    if (deduplicateBlobs && resource instanceof EXistBinaryResource) {
                        // only add distinct blobs to the Blob Store once!
                        final String blobId = ((EXistBinaryResource) resource).getBlobId().toString();
                        if (!seenBlobIds.contains(blobId)) {
                            os = output.newBlobEntry(blobId);
                            ((ExtendedResource) resource).getContentIntoAStream(os);
                            output.closeEntry();
                            seenBlobIds.add(blobId);
                        }
                    } else {
                        os = output.newEntry(filename);
                        ((ExtendedResource) resource).getContentIntoAStream(os);
                        output.closeEntry();
                    }
                } else {
                    os = output.newEntry(filename);
                    final Writer writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
                    // write resource to contentSerializer
                    final SAXSerializer contentSerializer = (SAXSerializer) SerializerPool.getInstance().borrowObject(SAXSerializer.class);
                    try {
                        contentSerializer.setOutput(writer, defaultOutputProperties);
                        ((EXistResource) resource).setLexicalHandler(contentSerializer);
                        ((XMLResource) resource).getContentAsSAX(contentSerializer);
                    } finally {
                        SerializerPool.getInstance().returnObject(contentSerializer);
                    }
                    writer.flush();
                    output.closeEntry();
                }
                final EXistResource ris = (EXistResource) resource;
                // store permissions
                attr.clear();
                attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", resource.getResourceType());
                attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", name);
                writeUnixStylePermissionAttributes(attr, perms[i]);
                Date date = ris.getCreationTime();
                if (date != null) {
                    attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", "" + new DateTimeValue(date));
                }
                date = ris.getLastModificationTime();
                if (date != null) {
                    attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", "" + new DateTimeValue(date));
                }
                attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", filename);
                attr.addAttribute(Namespaces.EXIST_NS, "mimetype", "mimetype", "CDATA", encode(((EXistResource) resource).getMimeType()));
                if (!"BinaryResource".equals(resource.getResourceType())) {
                    if (ris.getDocType() != null) {
                        if (ris.getDocType().getName() != null) {
                            attr.addAttribute(Namespaces.EXIST_NS, "namedoctype", "namedoctype", "CDATA", ris.getDocType().getName());
                        }
                        if (ris.getDocType().getPublicId() != null) {
                            attr.addAttribute(Namespaces.EXIST_NS, "publicid", "publicid", "CDATA", ris.getDocType().getPublicId());
                        }
                        if (ris.getDocType().getSystemId() != null) {
                            attr.addAttribute(Namespaces.EXIST_NS, "systemid", "systemid", "CDATA", ris.getDocType().getSystemId());
                        }
                    }
                } else {
                    attr.addAttribute(Namespaces.EXIST_NS, "blob-id", "blob-id", "CDATA", ((EXistBinaryResource) ris).getBlobId().toString());
                }
                serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr);
                if (perms[i] instanceof ACLPermission) {
                    writeACLPermission(serializer, (ACLPermission) perms[i]);
                }
                serializer.endElement(Namespaces.EXIST_NS, "resource", "resource");
            } catch (final XMLDBException e) {
                System.err.println("Failed to backup resource " + resources[i] + " from collection " + current.getName());
                throw e;
            }
        }
        // write sub-collections
        for (final String collection : collections) {
            if (current.getName().equals(XmldbURI.SYSTEM_COLLECTION) && "temp".equals(collection)) {
                continue;
            }
            attr.clear();
            attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", collection);
            attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", encode(URIUtils.urlDecodeUtf8(collection)));
            serializer.startElement(Namespaces.EXIST_NS, "subcollection", "subcollection", attr);
            serializer.endElement(Namespaces.EXIST_NS, "subcollection", "subcollection");
        }
        // close <collection>
        serializer.endElement(Namespaces.EXIST_NS, "collection", "collection");
        serializer.endPrefixMapping("");
        serializer.endDocument();
        output.closeContents();
    } finally {
        SerializerPool.getInstance().returnObject(serializer);
    }
    // descend into sub-collections
    for (final String collection : collections) {
        final Collection child = current.getChildCollection(collection);
        if (child.getName().equals(XmldbURI.TEMP_COLLECTION)) {
            continue;
        }
        output.newCollection(encode(URIUtils.urlDecodeUtf8(collection)));
        backup(seenBlobIds, child, output, dialog);
        output.closeCollection();
    }
}
Also used : ACLPermission(org.exist.security.ACLPermission) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ACLPermission(org.exist.security.ACLPermission) Permission(org.exist.security.Permission) SAXSerializer(org.exist.util.serializer.SAXSerializer) DateTimeValue(org.exist.xquery.value.DateTimeValue) XMLResource(org.xmldb.api.modules.XMLResource) XMLResource(org.xmldb.api.modules.XMLResource) Date(java.util.Date)

Aggregations

ACLPermission (org.exist.security.ACLPermission)10 Permission (org.exist.security.Permission)8 PermissionDeniedException (org.exist.security.PermissionDeniedException)5 ACEAider (org.exist.security.internal.aider.ACEAider)3 SAXSerializer (org.exist.util.serializer.SAXSerializer)3 DateTimeValue (org.exist.xquery.value.DateTimeValue)3 AttributesImpl (org.xml.sax.helpers.AttributesImpl)3 XMLStreamException (javax.xml.stream.XMLStreamException)2 LockException (org.exist.util.LockException)2 XmldbURI (org.exist.xmldb.XmldbURI)2 TerminatedException (org.exist.xquery.TerminatedException)2 XPathException (org.exist.xquery.XPathException)2 SAXException (org.xml.sax.SAXException)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1 EXistException (org.exist.EXistException)1 Collection (org.exist.collections.Collection)1 DocumentImpl (org.exist.dom.persistent.DocumentImpl)1 LockedDocument (org.exist.dom.persistent.LockedDocument)1