001/*
002 * (C) Copyright 2015-2018 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019package org.nuxeo.ecm.core.blob;
020
021import java.io.FileNotFoundException;
022import java.io.IOException;
023import java.io.InputStream;
024import java.nio.file.Files;
025import java.nio.file.Path;
026import java.nio.file.Paths;
027import java.util.Map;
028
029import org.apache.commons.codec.digest.DigestUtils;
030import org.apache.commons.lang3.StringUtils;
031import org.nuxeo.ecm.core.api.Blob;
032import org.nuxeo.ecm.core.api.NuxeoException;
033
034/**
035 * Blob provider that can reference files on the filesystem.
036 * <p>
037 * This blob provider MUST be configured with a "root" property that specifies the minimum root path for all files:
038 *
039 * <pre>
040 * <code>
041 * &lt;blobprovider name="myfsblobprovider">
042 *   &lt;class>org.nuxeo.ecm.core.blob.FilesystemBlobProvider&lt;/class>
043 *   &lt;property name="root">/base/directory/for/files&lt;/property>
044 * &lt;/blobprovider>
045 * </code>
046 * </pre>
047 * <p>
048 * A root of {@code /} may be used to allow any path.
049 * <p>
050 * Blobs are constructed through {@link FilesystemBlobProvider#createBlob}. The constructed blob's key, which will be
051 * stored in the document database, contains a path relative to the root.
052 *
053 * @since 7.10
054 */
055public class FilesystemBlobProvider extends AbstractBlobProvider {
056
057    public static final String ROOT_PROP = "root";
058
059    /** The root ending with /, or an empty string. */
060    protected String root;
061
062    @Override
063    public void initialize(String blobProviderId, Map<String, String> properties) throws IOException {
064        super.initialize(blobProviderId, properties);
065        root = properties.get(ROOT_PROP);
066        if (StringUtils.isBlank(root)) {
067            throw new NuxeoException(
068                    "Missing property '" + ROOT_PROP + "' for " + getClass().getSimpleName() + ": " + blobProviderId);
069        }
070        if ("/".equals(root)) {
071            root = "";
072        } else if (!root.endsWith("/")) {
073            root = root + "/";
074        }
075    }
076
077    @Override
078    public void close() {
079    }
080
081    @Override
082    public Blob readBlob(BlobInfo blobInfo) throws IOException {
083        return new SimpleManagedBlob(blobInfo);
084    }
085
086    @Override
087    public InputStream getStream(ManagedBlob blob) throws IOException {
088        String key = blob.getKey();
089        // strip prefix
090        int colon = key.indexOf(':');
091        if (colon >= 0 && key.substring(0, colon).equals(blobProviderId)) {
092            key = key.substring(colon + 1);
093        }
094        // final sanity checks
095        if (key.contains("..")) {
096            throw new FileNotFoundException("Illegal path: " + key);
097        }
098        return Files.newInputStream(Paths.get(root + key));
099    }
100
101    @Override
102    public boolean supportsUserUpdate() {
103        return supportsUserUpdateDefaultFalse();
104    }
105
106    @Override
107    public String writeBlob(Blob blob) throws IOException {
108        throw new UnsupportedOperationException("Writing a blob is not supported");
109    }
110
111    /**
112     * Creates a filesystem blob with the given information.
113     * <p>
114     * The passed {@link BlobInfo} contains information about the blob, and the key is a file path.
115     *
116     * @param blobInfo the blob info where the key is a file path
117     * @return the blob
118     */
119    public ManagedBlob createBlob(BlobInfo blobInfo) throws IOException {
120        String filePath = blobInfo.key;
121        if (filePath.contains("..")) {
122            throw new FileNotFoundException("Illegal path: " + filePath);
123        }
124        if (!filePath.startsWith(root)) {
125            throw new FileNotFoundException("Path is not under configured root: " + filePath);
126        }
127        Path path = Paths.get(filePath);
128        if (!Files.exists(path)) {
129            throw new FileNotFoundException(filePath);
130        }
131        // dereference links
132        while (Files.isSymbolicLink(path)) {
133            // dereference if link
134            path = Files.readSymbolicLink(path);
135            if (!Files.exists(path)) {
136                throw new FileNotFoundException(filePath);
137            }
138        }
139        String relativePath = filePath.substring(root.length());
140        long length = Files.size(path);
141        blobInfo = new BlobInfo(blobInfo); // copy
142        blobInfo.key = blobProviderId + ":" + relativePath;
143        blobInfo.length = Long.valueOf(length);
144        if (blobInfo.filename == null) {
145            blobInfo.filename = Paths.get(filePath).getFileName().toString();
146        }
147        if (blobInfo.digest == null) {
148            try (InputStream in = Files.newInputStream(path)) {
149                blobInfo.digest = DigestUtils.md5Hex(in);
150            }
151        }
152        return new SimpleManagedBlob(blobInfo);
153    }
154
155}