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 */
070public class DiskFileItemFactory implements FileItemFactory {
071
072    // ----------------------------------------------------- Manifest constants
073
074    /**
075     * The default threshold above which uploads will be stored on disk.
076     */
077    public static final int DEFAULT_SIZE_THRESHOLD = 10240;
078
079    // ----------------------------------------------------- Instance Variables
080
081    /**
082     * The directory in which uploaded files will be stored, if stored on disk.
083     */
084    private File repository;
085
086    /**
087     * The threshold above which uploads will be stored on disk.
088     */
089    private int sizeThreshold = DEFAULT_SIZE_THRESHOLD;
090
091    /**
092     * <p>The instance of {@link FileCleaningTracker}, which is responsible
093     * for deleting temporary files.</p>
094     * <p>May be null, if tracking files is not required.</p>
095     */
096    private FileCleaningTracker fileCleaningTracker;
097
098    /**
099     * Default content charset to be used when no explicit charset
100     * parameter is provided by the sender.
101     */
102    private String defaultCharset = DiskFileItem.DEFAULT_CHARSET;
103
104    // ----------------------------------------------------------- Constructors
105
106    /**
107     * Constructs an unconfigured instance of this class. The resulting factory
108     * may be configured by calling the appropriate setter methods.
109     */
110    public DiskFileItemFactory() {
111        this(DEFAULT_SIZE_THRESHOLD, null);
112    }
113
114    /**
115     * Constructs a preconfigured instance of this class.
116     *
117     * @param sizeThreshold The threshold, in bytes, below which items will be
118     *                      retained in memory and above which they will be
119     *                      stored as a file.
120     * @param repository    The data repository, which is the directory in
121     *                      which files will be created, should the item size
122     *                      exceed the threshold.
123     */
124    public DiskFileItemFactory(int sizeThreshold, File repository) {
125        this.sizeThreshold = sizeThreshold;
126        this.repository = repository;
127    }
128
129    // ------------------------------------------------------------- Properties
130
131    /**
132     * Returns the directory used to temporarily store files that are larger
133     * than the configured size threshold.
134     *
135     * @return The directory in which temporary files will be located.
136     *
137     * @see #setRepository(java.io.File)
138     *
139     */
140    public File getRepository() {
141        return repository;
142    }
143
144    /**
145     * Sets the directory used to temporarily store files that are larger
146     * than the configured size threshold.
147     *
148     * @param repository The directory in which temporary files will be located.
149     *
150     * @see #getRepository()
151     *
152     */
153    public void setRepository(File repository) {
154        this.repository = repository;
155    }
156
157    /**
158     * Returns the size threshold beyond which files are written directly to
159     * disk. The default value is 10240 bytes.
160     *
161     * @return The size threshold, in bytes.
162     *
163     * @see #setSizeThreshold(int)
164     */
165    public int getSizeThreshold() {
166        return sizeThreshold;
167    }
168
169    /**
170     * Sets the size threshold beyond which files are written directly to disk.
171     *
172     * @param sizeThreshold The size threshold, in bytes.
173     *
174     * @see #getSizeThreshold()
175     *
176     */
177    public void setSizeThreshold(int sizeThreshold) {
178        this.sizeThreshold = sizeThreshold;
179    }
180
181    // --------------------------------------------------------- Public Methods
182
183    /**
184     * Create a new {@link org.apache.commons.fileupload.disk.DiskFileItem}
185     * instance from the supplied parameters and the local factory
186     * configuration.
187     *
188     * @param fieldName   The name of the form field.
189     * @param contentType The content type of the form field.
190     * @param isFormField <code>true</code> if this is a plain form field;
191     *                    <code>false</code> otherwise.
192     * @param fileName    The name of the uploaded file, if any, as supplied
193     *                    by the browser or other client.
194     *
195     * @return The newly created file item.
196     */
197    @Override
198    public FileItem createItem(String fieldName, String contentType,
199            boolean isFormField, String fileName) {
200        DiskFileItem result = new DiskFileItem(fieldName, contentType,
201                isFormField, fileName, sizeThreshold, repository);
202        result.setDefaultCharset(defaultCharset);
203        FileCleaningTracker tracker = getFileCleaningTracker();
204        if (tracker != null) {
205            tracker.track(result.getTempFile(), result);
206        }
207        return result;
208    }
209
210    /**
211     * Returns the tracker, which is responsible for deleting temporary
212     * files.
213     *
214     * @return An instance of {@link FileCleaningTracker}, or null
215     *   (default), if temporary files aren't tracked.
216     */
217    public FileCleaningTracker getFileCleaningTracker() {
218        return fileCleaningTracker;
219    }
220
221    /**
222     * Sets the tracker, which is responsible for deleting temporary
223     * files.
224     *
225     * @param pTracker An instance of {@link FileCleaningTracker},
226     *   which will from now on track the created files, or null
227     *   (default), to disable tracking.
228     */
229    public void setFileCleaningTracker(FileCleaningTracker pTracker) {
230        fileCleaningTracker = pTracker;
231    }
232
233    /**
234     * Returns the default charset for use when no explicit charset
235     * parameter is provided by the sender.
236     * @return the default charset
237     */
238    public String getDefaultCharset() {
239        return defaultCharset;
240    }
241
242    /**
243     * Sets the default charset for use when no explicit charset
244     * parameter is provided by the sender.
245     * @param pCharset the default charset
246     */
247    public void setDefaultCharset(String pCharset) {
248        defaultCharset = pCharset;
249    }
250}