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.io.ByteArrayInputStream;
020import java.io.IOException;
021import java.io.InputStream;
022import java.io.OutputStream;
023import java.io.UncheckedIOException;
024import java.nio.charset.Charset;
025import java.nio.charset.StandardCharsets;
026import java.nio.file.CopyOption;
027import java.nio.file.Files;
028import java.nio.file.InvalidPathException;
029import java.nio.file.Path;
030import java.nio.file.Paths;
031import java.nio.file.StandardCopyOption;
032import java.util.UUID;
033import java.util.concurrent.atomic.AtomicInteger;
034
035import org.apache.commons.fileupload2.core.FileItemFactory.AbstractFileItemBuilder;
036import org.apache.commons.io.Charsets;
037import org.apache.commons.io.build.AbstractOrigin;
038import org.apache.commons.io.file.PathUtils;
039import org.apache.commons.io.function.Uncheck;
040import org.apache.commons.io.output.DeferredFileOutputStream;
041
042/**
043 * The default implementation of the {@link FileItem FileItem} interface.
044 * <p>
045 * After retrieving an instance of this class from a {@link DiskFileItemFactory} instance (see
046 * {@code org.apache.commons.fileupload2.core.servlet.ServletFileUpload
047 * #parseRequest(javax.servlet.http.HttpServletRequest)}), you may either request all contents of file at once using {@link #get()} or request an
048 * {@link java.io.InputStream InputStream} with {@link #getInputStream()} and process the file without attempting to load it into memory, which may come handy
049 * with large files.
050 * </p>
051 * <p>
052 * Temporary files, which are created for file items, should be deleted later on. The best way to do this is using a
053 * {@link org.apache.commons.io.FileCleaningTracker}, which you can set on the {@link DiskFileItemFactory}. However, if you do use such a tracker, then you must
054 * consider the following: Temporary files are automatically deleted as soon as they are no longer needed. (More precisely, when the corresponding instance of
055 * {@link java.io.File} is garbage collected.) This is done by the so-called reaper thread, which is started and stopped automatically by the
056 * {@link org.apache.commons.io.FileCleaningTracker} when there are files to be tracked. It might make sense to terminate that thread, for example, if your web
057 * application ends. See the section on "Resource cleanup" in the users guide of Commons FileUpload.
058 * </p>
059 */
060public final class DiskFileItem implements FileItem<DiskFileItem> {
061
062    /**
063     * Builds a new {@link DiskFileItem} instance.
064     * <p>
065     * For example:
066     * </p>
067     *
068     * <pre>{@code
069     * final FileItem fileItem = fileItemFactory.fileItemBuilder()
070     *   .setFieldName("FieldName")
071     *   .setContentType("ContentType")
072     *   .setFormField(true)
073     *   .setFileName("FileName")
074     *   .setFileItemHeaders(...)
075     *   .get();
076     * }
077     * </pre>
078     */
079    public static class Builder extends AbstractFileItemBuilder<DiskFileItem, Builder> {
080
081        /**
082         * Constructs a new instance.
083         */
084        public Builder() {
085            setBufferSize(DiskFileItemFactory.DEFAULT_THRESHOLD);
086            setPath(PathUtils.getTempDirectory());
087            setCharset(DEFAULT_CHARSET);
088            setCharsetDefault(DEFAULT_CHARSET);
089        }
090
091        /**
092         * Constructs a new instance.
093         * <p>
094         * You must provide an origin that can be converted to a Reader by this builder, otherwise, this call will throw an
095         * {@link UnsupportedOperationException}.
096         * </p>
097         *
098         * @return a new instance.
099         * @throws UnsupportedOperationException if the origin cannot provide a Path.
100         * @see AbstractOrigin#getReader(Charset)
101         */
102        @Override
103        public DiskFileItem get() {
104            final var diskFileItem = new DiskFileItem(getFieldName(), getContentType(), isFormField(), getFileName(), getBufferSize(), getPath(),
105                    getFileItemHeaders(), getCharset());
106            final var tracker = getFileCleaningTracker();
107            if (tracker != null) {
108                tracker.track(diskFileItem.getTempFile().toFile(), diskFileItem);
109            }
110            return diskFileItem;
111        }
112
113    }
114
115    /**
116     * Default content charset to be used when no explicit charset parameter is provided by the sender. Media subtypes of the "text" type are defined to have a
117     * default charset value of "ISO-8859-1" when received via HTTP.
118     */
119    public static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1;
120
121    /**
122     * UID used in unique file name generation.
123     */
124    private static final String UID = UUID.randomUUID().toString().replace('-', '_');
125
126    /**
127     * Counter used in unique identifier generation.
128     */
129    private static final AtomicInteger COUNTER = new AtomicInteger();
130
131    /**
132     * Constructs a new {@link Builder}.
133     *
134     * @return a new {@link Builder}.
135     */
136    public static Builder builder() {
137        return new Builder();
138    }
139
140    /**
141     * Tests if the file name is valid. For example, if it contains a NUL characters, it's invalid. If the file name is valid, it will be returned without any
142     * modifications. Otherwise, throw an {@link InvalidPathException}.
143     *
144     * @param fileName The file name to check
145     * @return Unmodified file name, if valid.
146     * @throws InvalidPathException The file name is invalid.
147     */
148    public static String checkFileName(final String fileName) {
149        if (fileName != null) {
150            // Specific NUL check to build a better exception message.
151            final var indexOf0 = fileName.indexOf(0);
152            if (indexOf0 != -1) {
153                final var sb = new StringBuilder();
154                for (var i = 0; i < fileName.length(); i++) {
155                    final var c = fileName.charAt(i);
156                    switch (c) {
157                    case 0:
158                        sb.append("\\0");
159                        break;
160                    default:
161                        sb.append(c);
162                        break;
163                    }
164                }
165                throw new InvalidPathException(fileName, sb.toString(), indexOf0);
166            }
167            // Throws InvalidPathException on invalid file names
168            Paths.get(fileName);
169        }
170        return fileName;
171    }
172
173    /**
174     * Gets an identifier that is unique within the class loader used to load this class, but does not have random-like appearance.
175     *
176     * @return A String with the non-random looking instance identifier.
177     */
178    private static String getUniqueId() {
179        final var limit = 100_000_000;
180        final var current = COUNTER.getAndIncrement();
181        var id = Integer.toString(current);
182
183        // If you manage to get more than 100 million of ids, you'll
184        // start getting ids longer than 8 characters.
185        if (current < limit) {
186            id = ("00000000" + id).substring(id.length());
187        }
188        return id;
189    }
190
191    /**
192     * The name of the form field as provided by the browser.
193     */
194    private String fieldName;
195
196    /**
197     * The content type passed by the browser, or {@code null} if not defined.
198     */
199    private final String contentType;
200
201    /**
202     * Whether or not this item is a simple form field.
203     */
204    private volatile boolean isFormField;
205
206    /**
207     * The original file name in the user's file system.
208     */
209    private final String fileName;
210
211    /**
212     * The size of the item, in bytes. This is used to cache the size when a file item is moved from its original location.
213     */
214    private volatile long size = -1;
215
216    /**
217     * The threshold above which uploads will be stored on disk.
218     */
219    private final int threshold;
220
221    /**
222     * The directory in which uploaded files will be stored, if stored on disk.
223     */
224    private final Path repository;
225
226    /**
227     * Cached contents of the file.
228     */
229    private byte[] cachedContent;
230
231    /**
232     * Output stream for this item.
233     */
234    private DeferredFileOutputStream dfos;
235
236    /**
237     * The temporary file to use.
238     */
239    private final Path tempFile;
240
241    /**
242     * The file items headers.
243     */
244    private FileItemHeaders fileItemHeaders;
245
246    /**
247     * Default content Charset to be used when no explicit Charset parameter is provided by the sender.
248     */
249    private Charset charsetDefault = DEFAULT_CHARSET;
250
251    /**
252     * Constructs a new {@code DiskFileItem} instance.
253     *
254     * @param fieldName       The name of the form field.
255     * @param contentType     The content type passed by the browser or {@code null} if not specified.
256     * @param isFormField     Whether or not this item is a plain form field, as opposed to a file upload.
257     * @param fileName        The original file name in the user's file system, or {@code null} if not specified.
258     * @param threshold       The threshold, in bytes, below which items will be retained in memory and above which they will be stored as a file.
259     * @param repository      The data repository, which is the directory in which files will be created, should the item size exceed the threshold.
260     * @param fileItemHeaders The file item headers.
261     * @param defaultCharset  The default Charset.
262     */
263    private DiskFileItem(final String fieldName, final String contentType, final boolean isFormField, final String fileName, final int threshold,
264            final Path repository, final FileItemHeaders fileItemHeaders, final Charset defaultCharset) {
265        this.fieldName = fieldName;
266        this.contentType = contentType;
267        this.charsetDefault = defaultCharset;
268        this.isFormField = isFormField;
269        this.fileName = fileName;
270        this.fileItemHeaders = fileItemHeaders;
271        this.threshold = threshold;
272        this.repository = repository != null ? repository : PathUtils.getTempDirectory();
273        this.tempFile = this.repository.resolve(String.format("upload_%s_%s.tmp", UID, getUniqueId()));
274    }
275
276    /**
277     * Deletes the underlying storage for a file item, including deleting any associated temporary disk file. This method can be used to ensure that this is
278     * done at an earlier time, thus preserving system resources.
279     *
280     * @throws IOException if an error occurs.
281     */
282    @Override
283    public DiskFileItem delete() throws IOException {
284        cachedContent = null;
285        final var outputFile = getPath();
286        if (outputFile != null && !isInMemory() && Files.exists(outputFile)) {
287            Files.delete(outputFile);
288        }
289        return this;
290    }
291
292    /**
293     * Gets the contents of the file as an array of bytes. If the contents of the file were not yet cached in memory, they will be loaded from the disk storage
294     * and cached.
295     *
296     * @return The contents of the file as an array of bytes or {@code null} if the data cannot be read.
297     * @throws UncheckedIOException if an I/O error occurs.
298     * @throws OutOfMemoryError     See {@link Files#readAllBytes(Path)}: If an array of the required size cannot be allocated, for example the file is larger
299     *                              that {@code 2GB}
300     */
301    @Override
302    public byte[] get() throws UncheckedIOException {
303        if (isInMemory()) {
304            if (cachedContent == null && dfos != null) {
305                cachedContent = dfos.getData();
306            }
307            return cachedContent != null ? cachedContent.clone() : new byte[0];
308        }
309        return Uncheck.get(() -> Files.readAllBytes(dfos.getFile().toPath()));
310    }
311
312    /**
313     * Gets the content charset passed by the agent or {@code null} if not defined.
314     *
315     * @return The content charset passed by the agent or {@code null} if not defined.
316     */
317    public Charset getCharset() {
318        final var parser = new ParameterParser();
319        parser.setLowerCaseNames(true);
320        // Parameter parser can handle null input
321        final var params = parser.parse(getContentType(), ';');
322        return Charsets.toCharset(params.get("charset"), charsetDefault);
323    }
324
325    /**
326     * Gets the default charset for use when no explicit charset parameter is provided by the sender.
327     *
328     * @return the default charset
329     */
330    public Charset getCharsetDefault() {
331        return charsetDefault;
332    }
333
334    /**
335     * Gets the content type passed by the agent or {@code null} if not defined.
336     *
337     * @return The content type passed by the agent or {@code null} if not defined.
338     */
339    @Override
340    public String getContentType() {
341        return contentType;
342    }
343
344    /**
345     * Gets the name of the field in the multipart form corresponding to this file item.
346     *
347     * @return The name of the form field.
348     * @see #setFieldName(String)
349     */
350    @Override
351    public String getFieldName() {
352        return fieldName;
353    }
354
355    /**
356     * Gets the file item headers.
357     *
358     * @return The file items headers.
359     */
360    @Override
361    public FileItemHeaders getHeaders() {
362        return fileItemHeaders;
363    }
364
365    /**
366     * Gets an {@link java.io.InputStream InputStream} that can be used to retrieve the contents of the file.
367     *
368     * @return An {@link java.io.InputStream InputStream} that can be used to retrieve the contents of the file.
369     * @throws IOException if an error occurs.
370     */
371    @Override
372    public InputStream getInputStream() throws IOException {
373        if (!isInMemory()) {
374            return Files.newInputStream(dfos.getFile().toPath());
375        }
376
377        if (cachedContent == null) {
378            cachedContent = dfos.getData();
379        }
380        return new ByteArrayInputStream(cachedContent);
381    }
382
383    /**
384     * Gets the original file name in the client's file system.
385     *
386     * @return The original file name in the client's file system.
387     * @throws InvalidPathException The file name contains a NUL character, which might be an indicator of a security attack. If you intend to use the file name
388     *                              anyways, catch the exception and use {@link InvalidPathException#getInput()}.
389     */
390    @Override
391    public String getName() {
392        return checkFileName(fileName);
393    }
394
395    /**
396     * Gets an {@link java.io.OutputStream OutputStream} that can be used for storing the contents of the file.
397     *
398     * @return An {@link java.io.OutputStream OutputStream} that can be used for storing the contents of the file.
399     */
400    @Override
401    public OutputStream getOutputStream() {
402        if (dfos == null) {
403            dfos = DeferredFileOutputStream.builder().setThreshold(threshold).setOutputFile(getTempFile().toFile()).get();
404        }
405        return dfos;
406    }
407
408    /**
409     * Gets the {@link Path} for the {@code FileItem}'s data's temporary location on the disk. Note that for {@code FileItem}s that have their data stored in
410     * memory, this method will return {@code null}. When handling large files, you can use {@link Files#move(Path,Path,CopyOption...)} to move the file to new
411     * location without copying the data, if the source and destination locations reside within the same logical volume.
412     *
413     * @return The data file, or {@code null} if the data is stored in memory.
414     */
415    public Path getPath() {
416        if (dfos == null) {
417            return null;
418        }
419        if (isInMemory()) {
420            return null;
421        }
422        return dfos.getFile().toPath();
423    }
424
425    /**
426     * Gets the size of the file.
427     *
428     * @return The size of the file, in bytes.
429     */
430    @Override
431    public long getSize() {
432        if (size >= 0) {
433            return size;
434        }
435        if (cachedContent != null) {
436            return cachedContent.length;
437        }
438        return dfos != null ? dfos.getByteCount() : 0;
439    }
440
441    /**
442     * Gets the contents of the file as a String, using the default character encoding. This method uses {@link #get()} to retrieve the contents of the file.
443     * <p>
444     * <strong>TODO</strong> Consider making this method throw UnsupportedEncodingException.
445     * </p>
446     *
447     * @return The contents of the file, as a string.
448     */
449    @Override
450    public String getString() {
451        return new String(get(), getCharset());
452    }
453
454    /**
455     * Gets the contents of the file as a String, using the specified encoding. This method uses {@link #get()} to retrieve the contents of the file.
456     *
457     * @param charset The charset to use.
458     * @return The contents of the file, as a string.
459     */
460    @Override
461    public String getString(final Charset charset) throws IOException {
462        return new String(get(), Charsets.toCharset(charset, charsetDefault));
463    }
464
465    /**
466     * Creates and returns a {@link java.io.File File} representing a uniquely named temporary file in the configured repository path. The lifetime of the file
467     * is tied to the lifetime of the {@code FileItem} instance; the file will be deleted when the instance is garbage collected.
468     * <p>
469     * <strong>Note: Subclasses that override this method must ensure that they return the same File each time.</strong>
470     * </p>
471     *
472     * @return The {@link java.io.File File} to be used for temporary storage.
473     */
474    protected Path getTempFile() {
475        return tempFile;
476    }
477
478    /**
479     * Tests whether or not a {@code FileItem} instance represents a simple form field.
480     *
481     * @return {@code true} if the instance represents a simple form field; {@code false} if it represents an uploaded file.
482     * @see #setFormField(boolean)
483     */
484    @Override
485    public boolean isFormField() {
486        return isFormField;
487    }
488
489    /**
490     * Provides a hint as to whether or not the file contents will be read from memory.
491     *
492     * @return {@code true} if the file contents will be read from memory; {@code false} otherwise.
493     */
494    @Override
495    public boolean isInMemory() {
496        if (cachedContent != null) {
497            return true;
498        }
499        return dfos.isInMemory();
500    }
501
502    /**
503     * Sets the default charset for use when no explicit charset parameter is provided by the sender.
504     *
505     * @param charset the default charset
506     * @return {@code this} instance.
507     */
508    public DiskFileItem setCharsetDefault(final Charset charset) {
509        charsetDefault = charset;
510        return this;
511    }
512
513    /**
514     * Sets the field name used to reference this file item.
515     *
516     * @param fieldName The name of the form field.
517     * @see #getFieldName()
518     */
519    @Override
520    public DiskFileItem setFieldName(final String fieldName) {
521        this.fieldName = fieldName;
522        return this;
523    }
524
525    /**
526     * Specifies whether or not a {@code FileItem} instance represents a simple form field.
527     *
528     * @param state {@code true} if the instance represents a simple form field; {@code false} if it represents an uploaded file.
529     * @see #isFormField()
530     */
531    @Override
532    public DiskFileItem setFormField(final boolean state) {
533        isFormField = state;
534        return this;
535    }
536
537    /**
538     * Sets the file item headers.
539     *
540     * @param headers The file items headers.
541     */
542    @Override
543    public DiskFileItem setHeaders(final FileItemHeaders headers) {
544        this.fileItemHeaders = headers;
545        return this;
546    }
547
548    /**
549     * Returns a string representation of this object.
550     *
551     * @return a string representation of this object.
552     */
553    @Override
554    public String toString() {
555        return String.format("name=%s, StoreLocation=%s, size=%s bytes, isFormField=%s, FieldName=%s", getName(), getPath(), getSize(), isFormField(),
556                getFieldName());
557    }
558
559    /**
560     * Writes an uploaded item to disk.
561     * <p>
562     * The client code is not concerned with whether or not the item is stored in memory, or on disk in a temporary location. They just want to write the
563     * uploaded item to a file.
564     * </p>
565     * <p>
566     * This implementation first attempts to rename the uploaded item to the specified destination file, if the item was originally written to disk. Otherwise,
567     * the data will be copied to the specified file.
568     * </p>
569     * <p>
570     * This method is only guaranteed to work <em>once</em>, the first time it is invoked for a particular item. This is because, in the event that the method
571     * renames a temporary file, that file will no longer be available to copy or rename again at a later time.
572     * </p>
573     *
574     * @param file The {@code File} into which the uploaded item should be stored.
575     * @throws IOException if an error occurs.
576     */
577    @Override
578    public DiskFileItem write(final Path file) throws IOException {
579        if (isInMemory()) {
580            try (var fout = Files.newOutputStream(file)) {
581                fout.write(get());
582            } catch (final IOException e) {
583                throw new IOException("Unexpected output data", e);
584            }
585        } else {
586            final var outputFile = getPath();
587            if (outputFile == null) {
588                /*
589                 * For whatever reason we cannot write the file to disk.
590                 */
591                throw new FileUploadException("Cannot write uploaded file to disk.");
592            }
593            // Save the length of the file
594            size = Files.size(outputFile);
595            //
596            // The uploaded file is being stored on disk in a temporary location so move it to the desired file.
597            //
598            Files.move(outputFile, file, StandardCopyOption.REPLACE_EXISTING);
599        }
600        return this;
601    }
602}