001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.fileupload2.core;
018
019import java.nio.charset.Charset;
020import java.nio.file.Path;
021
022import org.apache.commons.io.FileCleaningTracker;
023import org.apache.commons.io.build.AbstractOrigin;
024import org.apache.commons.io.build.AbstractStreamBuilder;
025import org.apache.commons.io.file.PathUtils;
026
027/**
028 * The default {@link FileItemFactory} implementation.
029 * <p>
030 * This implementation creates {@link FileItem} instances which keep their content either in memory, for smaller items, or in a temporary file on disk, for
031 * larger items. The size threshold, above which content will be stored on disk, is configurable, as is the directory in which temporary files will be created.
032 * </p>
033 * <p>
034 * If not otherwise configured, the default configuration values are as follows:
035 * </p>
036 * <ul>
037 * <li>Size threshold is 10 KB.</li>
038 * <li>Repository is the system default temporary directory, as returned by {@code System.getProperty("java.io.tmpdir")}.</li>
039 * </ul>
040 * <p>
041 * <b>NOTE</b>: Files are created in the system default temporary directory with predictable names. This means that a local attacker with write access to that
042 * directory can perform a TOUTOC attack to replace any uploaded file with a file of the attackers choice. The implications of this will depend on how the
043 * uploaded file is used but could be significant. When using this implementation in an environment with local, untrusted users, {@link Builder#setPath(Path)}
044 * MUST be used to configure a repository location that is not publicly writable. In a Servlet container the location identified by the ServletContext attribute
045 * {@code javax.servlet.context.tempdir} may be used.
046 * </p>
047 * <p>
048 * Temporary files, which are created for file items, should be deleted later on. The best way to do this is using a {@link FileCleaningTracker}, which you can
049 * set on the {@link DiskFileItemFactory}. However, if you do use such a tracker, then you must consider the following: Temporary files are automatically
050 * deleted as soon as they are no longer needed. (More precisely, when the corresponding instance of {@link java.io.File} is garbage collected.) This is done by
051 * the so-called reaper thread, which is started and stopped automatically by the {@link FileCleaningTracker} when there are files to be tracked. It might make
052 * sense to terminate that thread, for example, if your web application ends. See the section on "Resource cleanup" in the users guide of Commons FileUpload.
053 * </p>
054 *
055 * @see Builder
056 * @see Builder#get()
057 */
058public final class DiskFileItemFactory implements FileItemFactory<DiskFileItem> {
059
060    /**
061     * Builds a new {@link DiskFileItemFactory} instance.
062     * <p>
063     * For example:
064     * </p>
065     * <pre>{@code
066     * DiskFileItemFactory factory = DiskFileItemFactory.builder().setPath(path).setBufferSize(DEFAULT_THRESHOLD).get();
067     * }
068     * </pre>
069     */
070    public static class Builder extends AbstractStreamBuilder<DiskFileItemFactory, Builder> {
071
072        /**
073         * The instance of {@link FileCleaningTracker}, which is responsible for deleting temporary files.
074         * <p>
075         * May be null, if tracking files is not required.
076         * </p>
077         */
078        private FileCleaningTracker fileCleaningTracker;
079
080        public Builder() {
081            setBufferSize(DEFAULT_THRESHOLD);
082            setPath(PathUtils.getTempDirectory());
083            setCharset(DiskFileItem.DEFAULT_CHARSET);
084            setCharsetDefault(DiskFileItem.DEFAULT_CHARSET);
085        }
086
087        /**
088         * Constructs a new instance.
089         * <p>
090         * This builder use the aspects Path and buffer size.
091         * </p>
092         * <p>
093         * You must provide an origin that can be converted to a Reader by this builder, otherwise, this call will throw an
094         * {@link UnsupportedOperationException}.
095         * </p>
096         *
097         * @return a new instance.
098         * @throws UnsupportedOperationException if the origin cannot provide a Path.
099         * @see AbstractOrigin#getReader(Charset)
100         */
101        @Override
102        public DiskFileItemFactory get() {
103            return new DiskFileItemFactory(getPath(), getBufferSize(), getCharset(), fileCleaningTracker);
104        }
105
106        /**
107         * Sets the tracker, which is responsible for deleting temporary files.
108         *
109         * @param fileCleaningTracker Callback to track files created, or null (default) to disable tracking.
110         * @return this
111         */
112        public Builder setFileCleaningTracker(final FileCleaningTracker fileCleaningTracker) {
113            this.fileCleaningTracker = fileCleaningTracker;
114            return this;
115        }
116
117    }
118
119    /**
120     * The default threshold in bytes above which uploads will be stored on disk.
121     */
122    public static final int DEFAULT_THRESHOLD = 10_240;
123
124    /**
125     * Constructs a new {@link Builder}.
126     *
127     * @return a new {@link Builder}.
128     */
129    public static Builder builder() {
130        return new Builder();
131    }
132
133    /**
134     * The directory in which uploaded files will be stored, if stored on disk.
135     */
136    private final Path repository;
137
138    /**
139     * The threshold above which uploads will be stored on disk.
140     */
141    private final int threshold;
142
143    /**
144     * The instance of {@link FileCleaningTracker}, which is responsible for deleting temporary files.
145     * <p>
146     * May be null, if tracking files is not required.
147     * </p>
148     */
149    private final FileCleaningTracker fileCleaningTracker;
150
151    /**
152     * Default content Charset to be used when no explicit Charset parameter is provided by the sender.
153     */
154    private final Charset charsetDefault;
155
156    /**
157     * Constructs a preconfigured instance of this class.
158     *
159     * @param repository          The data repository, which is the directory in which files will be created, should the item size exceed the threshold.
160     * @param threshold           The threshold, in bytes, below which items will be retained in memory and above which they will be stored as a file.
161     * @param charsetDefault      Sets the default charset for use when no explicit charset parameter is provided by the sender.
162     * @param fileCleaningTracker Callback to track files created, or null (default) to disable tracking.
163     */
164    private DiskFileItemFactory(final Path repository, final int threshold, final Charset charsetDefault, final FileCleaningTracker fileCleaningTracker) {
165        this.threshold = threshold;
166        this.repository = repository;
167        this.charsetDefault = charsetDefault;
168        this.fileCleaningTracker = fileCleaningTracker;
169    }
170
171    @SuppressWarnings("unchecked")
172    @Override
173    public DiskFileItem.Builder fileItemBuilder() {
174        // @formatter:off
175        return DiskFileItem.builder()
176                .setBufferSize(threshold)
177                .setCharset(charsetDefault)
178                .setFileCleaningTracker(fileCleaningTracker)
179                .setPath(repository);
180        // @formatter:on
181    }
182
183    /**
184     * Gets the default charset for use when no explicit charset parameter is provided by the sender.
185     *
186     * @return the default charset
187     */
188    public Charset getCharsetDefault() {
189        return charsetDefault;
190    }
191
192    /**
193     * Gets the tracker, which is responsible for deleting temporary files.
194     *
195     * @return An instance of {@link FileCleaningTracker}, or null (default), if temporary files aren't tracked.
196     */
197    public FileCleaningTracker getFileCleaningTracker() {
198        return fileCleaningTracker;
199    }
200
201    /**
202     * Gets the directory used to temporarily store files that are larger than the configured size threshold.
203     *
204     * @return The directory in which temporary files will be located.
205     */
206    public Path getRepository() {
207        return repository;
208    }
209
210    /**
211     * Gets the size threshold beyond which files are written directly to disk. The default value is {@value #DEFAULT_THRESHOLD} bytes.
212     *
213     * @return The size threshold in bytes.
214     */
215    public int getThreshold() {
216        return threshold;
217    }
218}