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.fileupload.disk;
018
019import java.io.File;
020
021import org.apache.commons.fileupload.FileItem;
022import org.apache.commons.fileupload.FileItemFactory;
023import org.apache.commons.io.FileCleaningTracker;
024
025/**
026 * <p>The default {@link org.apache.commons.fileupload.FileItemFactory}
027 * implementation. This implementation creates
028 * {@link org.apache.commons.fileupload.FileItem} instances which keep their
029 * content either in memory, for smaller items, or in a temporary file on disk,
030 * for larger items. The size threshold, above which content will be stored on
031 * disk, is configurable, as is the directory in which temporary files will be
032 * created.</p>
033 *
034 * <p>If not otherwise configured, the default configuration values are as
035 * follows:</p>
036 * <ul>
037 *   <li>Size threshold is 10KB.</li>
038 *   <li>Repository is the system default temp directory, as returned by
039 *       <code>System.getProperty("java.io.tmpdir")</code>.</li>
040 * </ul>
041 * <p>
042 * <b>NOTE</b>: Files are created in the system default temp directory with
043 * predictable names. This means that a local attacker with write access to that
044 * directory can perform a TOUTOC attack to replace any uploaded file with a
045 * file of the attackers choice. The implications of this will depend on how the
046 * uploaded file is used but could be significant. When using this
047 * implementation in an environment with local, untrusted users,
048 * {@link #setRepository(File)} MUST be used to configure a repository location
049 * that is not publicly writable. In a Servlet container the location identified
050 * by the ServletContext attribute <code>javax.servlet.context.tempdir</code>
051 * may be used.
052 * </p>
053 *
054 * <p>Temporary files, which are created for file items, should be
055 * deleted later on. The best way to do this is using a
056 * {@link FileCleaningTracker}, which you can set on the
057 * {@link DiskFileItemFactory}. However, if you do use such a tracker,
058 * then you must consider the following: Temporary files are automatically
059 * deleted as soon as they are no longer needed. (More precisely, when the
060 * corresponding instance of {@link java.io.File} is garbage collected.)
061 * This is done by the so-called reaper thread, which is started and stopped
062 * automatically by the {@link FileCleaningTracker} when there are files to be
063 * tracked.
064 * It might make sense to terminate that thread, for example, if
065 * your web application ends. See the section on "Resource cleanup"
066 * in the users guide of commons-fileupload.</p>
067 *
068 * @since FileUpload 1.1
069 *
070 * @version $Id: DiskFileItemFactory.java 1564788 2014-02-05 14:36:41Z markt $
071 */
072public class DiskFileItemFactory implements FileItemFactory {
073
074    // ----------------------------------------------------- Manifest constants
075
076    /**
077     * The default threshold above which uploads will be stored on disk.
078     */
079    public static final int DEFAULT_SIZE_THRESHOLD = 10240;
080
081    // ----------------------------------------------------- Instance Variables
082
083    /**
084     * The directory in which uploaded files will be stored, if stored on disk.
085     */
086    private File repository;
087
088    /**
089     * The threshold above which uploads will be stored on disk.
090     */
091    private int sizeThreshold = DEFAULT_SIZE_THRESHOLD;
092
093    /**
094     * <p>The instance of {@link FileCleaningTracker}, which is responsible
095     * for deleting temporary files.</p>
096     * <p>May be null, if tracking files is not required.</p>
097     */
098    private FileCleaningTracker fileCleaningTracker;
099
100    // ----------------------------------------------------------- Constructors
101
102    /**
103     * Constructs an unconfigured instance of this class. The resulting factory
104     * may be configured by calling the appropriate setter methods.
105     */
106    public DiskFileItemFactory() {
107        this(DEFAULT_SIZE_THRESHOLD, null);
108    }
109
110    /**
111     * Constructs a preconfigured instance of this class.
112     *
113     * @param sizeThreshold The threshold, in bytes, below which items will be
114     *                      retained in memory and above which they will be
115     *                      stored as a file.
116     * @param repository    The data repository, which is the directory in
117     *                      which files will be created, should the item size
118     *                      exceed the threshold.
119     */
120    public DiskFileItemFactory(int sizeThreshold, File repository) {
121        this.sizeThreshold = sizeThreshold;
122        this.repository = repository;
123    }
124
125    // ------------------------------------------------------------- Properties
126
127    /**
128     * Returns the directory used to temporarily store files that are larger
129     * than the configured size threshold.
130     *
131     * @return The directory in which temporary files will be located.
132     *
133     * @see #setRepository(java.io.File)
134     *
135     */
136    public File getRepository() {
137        return repository;
138    }
139
140    /**
141     * Sets the directory used to temporarily store files that are larger
142     * than the configured size threshold.
143     *
144     * @param repository The directory in which temporary files will be located.
145     *
146     * @see #getRepository()
147     *
148     */
149    public void setRepository(File repository) {
150        this.repository = repository;
151    }
152
153    /**
154     * Returns the size threshold beyond which files are written directly to
155     * disk. The default value is 10240 bytes.
156     *
157     * @return The size threshold, in bytes.
158     *
159     * @see #setSizeThreshold(int)
160     */
161    public int getSizeThreshold() {
162        return sizeThreshold;
163    }
164
165    /**
166     * Sets the size threshold beyond which files are written directly to disk.
167     *
168     * @param sizeThreshold The size threshold, in bytes.
169     *
170     * @see #getSizeThreshold()
171     *
172     */
173    public void setSizeThreshold(int sizeThreshold) {
174        this.sizeThreshold = sizeThreshold;
175    }
176
177    // --------------------------------------------------------- Public Methods
178
179    /**
180     * Create a new {@link org.apache.commons.fileupload.disk.DiskFileItem}
181     * instance from the supplied parameters and the local factory
182     * configuration.
183     *
184     * @param fieldName   The name of the form field.
185     * @param contentType The content type of the form field.
186     * @param isFormField <code>true</code> if this is a plain form field;
187     *                    <code>false</code> otherwise.
188     * @param fileName    The name of the uploaded file, if any, as supplied
189     *                    by the browser or other client.
190     *
191     * @return The newly created file item.
192     */
193    public FileItem createItem(String fieldName, String contentType,
194            boolean isFormField, String fileName) {
195        DiskFileItem result = new DiskFileItem(fieldName, contentType,
196                isFormField, fileName, sizeThreshold, repository);
197        FileCleaningTracker tracker = getFileCleaningTracker();
198        if (tracker != null) {
199            tracker.track(result.getTempFile(), result);
200        }
201        return result;
202    }
203
204    /**
205     * Returns the tracker, which is responsible for deleting temporary
206     * files.
207     *
208     * @return An instance of {@link FileCleaningTracker}, or null
209     *   (default), if temporary files aren't tracked.
210     */
211    public FileCleaningTracker getFileCleaningTracker() {
212        return fileCleaningTracker;
213    }
214
215    /**
216     * Sets the tracker, which is responsible for deleting temporary
217     * files.
218     *
219     * @param pTracker An instance of {@link FileCleaningTracker},
220     *   which will from now on track the created files, or null
221     *   (default), to disable tracking.
222     */
223    public void setFileCleaningTracker(FileCleaningTracker pTracker) {
224        fileCleaningTracker = pTracker;
225    }
226
227}