DiskFileItem.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.fileupload2.core;

  18. import java.io.ByteArrayInputStream;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.nio.charset.Charset;
  23. import java.nio.charset.StandardCharsets;
  24. import java.nio.file.CopyOption;
  25. import java.nio.file.Files;
  26. import java.nio.file.InvalidPathException;
  27. import java.nio.file.Path;
  28. import java.nio.file.Paths;
  29. import java.nio.file.StandardCopyOption;
  30. import java.util.UUID;
  31. import java.util.concurrent.atomic.AtomicInteger;

  32. import org.apache.commons.fileupload2.core.FileItemFactory.AbstractFileItemBuilder;
  33. import org.apache.commons.io.Charsets;
  34. import org.apache.commons.io.build.AbstractOrigin;
  35. import org.apache.commons.io.file.PathUtils;
  36. import org.apache.commons.io.output.DeferredFileOutputStream;

  37. /**
  38.  * The default implementation of the {@link FileItem FileItem} interface.
  39.  * <p>
  40.  * After retrieving an instance of this class from a {@link DiskFileItemFactory} instance (see
  41.  * {@code org.apache.commons.fileupload2.core.servlet.ServletFileUpload
  42.  * #parseRequest(javax.servlet.http.HttpServletRequest)}), you may either request all contents of file at once using {@link #get()} or request an
  43.  * {@link java.io.InputStream InputStream} with {@link #getInputStream()} and process the file without attempting to load it into memory, which may come handy
  44.  * with large files.
  45.  * </p>
  46.  * <p>
  47.  * Temporary files, which are created for file items, should be deleted later on. The best way to do this is using a
  48.  * {@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
  49.  * consider the following: Temporary files are automatically deleted as soon as they are no longer needed. (More precisely, when the corresponding instance of
  50.  * {@link java.io.File} is garbage collected.) This is done by the so-called reaper thread, which is started and stopped automatically by the
  51.  * {@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
  52.  * application ends. See the section on "Resource cleanup" in the users guide of Commons FileUpload.
  53.  * </p>
  54.  */
  55. public final class DiskFileItem implements FileItem<DiskFileItem> {

  56.     /**
  57.      * Builds a new {@link DiskFileItem} instance.
  58.      * <p>
  59.      * For example:
  60.      * </p>
  61.      *
  62.      * <pre>{@code
  63.      * final FileItem fileItem = fileItemFactory.fileItemBuilder()
  64.      *   .setFieldName("FieldName")
  65.      *   .setContentType("ContentType")
  66.      *   .setFormField(true)
  67.      *   .setFileName("FileName")
  68.      *   .setFileItemHeaders(...)
  69.      *   .get();
  70.      * }
  71.      * </pre>
  72.      */
  73.     public static class Builder extends AbstractFileItemBuilder<DiskFileItem, Builder> {

  74.         /**
  75.          * Constructs a new instance.
  76.          */
  77.         public Builder() {
  78.             setBufferSize(DiskFileItemFactory.DEFAULT_THRESHOLD);
  79.             setPath(PathUtils.getTempDirectory());
  80.             setCharset(DEFAULT_CHARSET);
  81.             setCharsetDefault(DEFAULT_CHARSET);
  82.         }

  83.         /**
  84.          * Constructs a new instance.
  85.          * <p>
  86.          * You must provide an origin that can be converted to a Reader by this builder, otherwise, this call will throw an
  87.          * {@link UnsupportedOperationException}.
  88.          * </p>
  89.          *
  90.          * @return a new instance.
  91.          * @throws UnsupportedOperationException if the origin cannot provide a Path.
  92.          * @see AbstractOrigin#getReader(Charset)
  93.          */
  94.         @Override
  95.         public DiskFileItem get() {
  96.             final var diskFileItem = new DiskFileItem(getFieldName(), getContentType(), isFormField(), getFileName(), getBufferSize(), getPath(),
  97.                     getFileItemHeaders(), getCharset());
  98.             final var tracker = getFileCleaningTracker();
  99.             if (tracker != null) {
  100.                 tracker.track(diskFileItem.getTempFile().toFile(), diskFileItem);
  101.             }
  102.             return diskFileItem;
  103.         }

  104.     }

  105.     /**
  106.      * 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
  107.      * default charset value of "ISO-8859-1" when received via HTTP.
  108.      */
  109.     public static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1;

  110.     /**
  111.      * UID used in unique file name generation.
  112.      */
  113.     private static final String UID = UUID.randomUUID().toString().replace('-', '_');

  114.     /**
  115.      * Counter used in unique identifier generation.
  116.      */
  117.     private static final AtomicInteger COUNTER = new AtomicInteger();

  118.     /**
  119.      * Constructs a new {@link Builder}.
  120.      *
  121.      * @return a new {@link Builder}.
  122.      */
  123.     public static Builder builder() {
  124.         return new Builder();
  125.     }

  126.     /**
  127.      * 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
  128.      * modifications. Otherwise, throw an {@link InvalidPathException}.
  129.      *
  130.      * @param fileName The file name to check
  131.      * @return Unmodified file name, if valid.
  132.      * @throws InvalidPathException The file name is invalid.
  133.      */
  134.     public static String checkFileName(final String fileName) {
  135.         if (fileName != null) {
  136.             // Specific NUL check to build a better exception message.
  137.             final var indexOf0 = fileName.indexOf(0);
  138.             if (indexOf0 != -1) {
  139.                 final var sb = new StringBuilder();
  140.                 for (var i = 0; i < fileName.length(); i++) {
  141.                     final var c = fileName.charAt(i);
  142.                     switch (c) {
  143.                     case 0:
  144.                         sb.append("\\0");
  145.                         break;
  146.                     default:
  147.                         sb.append(c);
  148.                         break;
  149.                     }
  150.                 }
  151.                 throw new InvalidPathException(fileName, sb.toString(), indexOf0);
  152.             }
  153.             // Throws InvalidPathException on invalid file names
  154.             Paths.get(fileName);
  155.         }
  156.         return fileName;
  157.     }

  158.     /**
  159.      * Gets an identifier that is unique within the class loader used to load this class, but does not have random-like appearance.
  160.      *
  161.      * @return A String with the non-random looking instance identifier.
  162.      */
  163.     private static String getUniqueId() {
  164.         final var limit = 100_000_000;
  165.         final var current = COUNTER.getAndIncrement();
  166.         var id = Integer.toString(current);

  167.         // If you manage to get more than 100 million of ids, you'll
  168.         // start getting ids longer than 8 characters.
  169.         if (current < limit) {
  170.             id = ("00000000" + id).substring(id.length());
  171.         }
  172.         return id;
  173.     }

  174.     /**
  175.      * The name of the form field as provided by the browser.
  176.      */
  177.     private String fieldName;

  178.     /**
  179.      * The content type passed by the browser, or {@code null} if not defined.
  180.      */
  181.     private final String contentType;

  182.     /**
  183.      * Whether or not this item is a simple form field.
  184.      */
  185.     private volatile boolean isFormField;

  186.     /**
  187.      * The original file name in the user's file system.
  188.      */
  189.     private final String fileName;

  190.     /**
  191.      * The size of the item, in bytes. This is used to cache the size when a file item is moved from its original location.
  192.      */
  193.     private volatile long size = -1;

  194.     /**
  195.      * The threshold above which uploads will be stored on disk.
  196.      */
  197.     private final int threshold;

  198.     /**
  199.      * The directory in which uploaded files will be stored, if stored on disk.
  200.      */
  201.     private final Path repository;

  202.     /**
  203.      * Cached contents of the file.
  204.      */
  205.     private byte[] cachedContent;

  206.     /**
  207.      * Output stream for this item.
  208.      */
  209.     private DeferredFileOutputStream dfos;

  210.     /**
  211.      * The temporary file to use.
  212.      */
  213.     private final Path tempFile;

  214.     /**
  215.      * The file items headers.
  216.      */
  217.     private FileItemHeaders fileItemHeaders;

  218.     /**
  219.      * Default content Charset to be used when no explicit Charset parameter is provided by the sender.
  220.      */
  221.     private Charset charsetDefault = DEFAULT_CHARSET;

  222.     /**
  223.      * Constructs a new {@code DiskFileItem} instance.
  224.      *
  225.      * @param fieldName       The name of the form field.
  226.      * @param contentType     The content type passed by the browser or {@code null} if not specified.
  227.      * @param isFormField     Whether or not this item is a plain form field, as opposed to a file upload.
  228.      * @param fileName        The original file name in the user's file system, or {@code null} if not specified.
  229.      * @param threshold       The threshold, in bytes, below which items will be retained in memory and above which they will be stored as a file.
  230.      * @param repository      The data repository, which is the directory in which files will be created, should the item size exceed the threshold.
  231.      * @param fileItemHeaders The file item headers.
  232.      * @param defaultCharset  The default Charset.
  233.      */
  234.     private DiskFileItem(final String fieldName, final String contentType, final boolean isFormField, final String fileName, final int threshold,
  235.             final Path repository, final FileItemHeaders fileItemHeaders, final Charset defaultCharset) {
  236.         this.fieldName = fieldName;
  237.         this.contentType = contentType;
  238.         this.charsetDefault = defaultCharset;
  239.         this.isFormField = isFormField;
  240.         this.fileName = fileName;
  241.         this.fileItemHeaders = fileItemHeaders;
  242.         this.threshold = threshold;
  243.         this.repository = repository != null ? repository : PathUtils.getTempDirectory();
  244.         this.tempFile = this.repository.resolve(String.format("upload_%s_%s.tmp", UID, getUniqueId()));
  245.     }

  246.     /**
  247.      * 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
  248.      * done at an earlier time, thus preserving system resources.
  249.      *
  250.      * @throws IOException if an error occurs.
  251.      */
  252.     @Override
  253.     public DiskFileItem delete() throws IOException {
  254.         cachedContent = null;
  255.         final var outputFile = getPath();
  256.         if (outputFile != null && !isInMemory() && Files.exists(outputFile)) {
  257.             Files.delete(outputFile);
  258.         }
  259.         return this;
  260.     }

  261.     /**
  262.      * 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
  263.      * and cached.
  264.      *
  265.      * @return The contents of the file as an array of bytes or {@code null} if the data cannot be read.
  266.      * @throws IOException if an I/O error occurs.
  267.      * @throws OutOfMemoryError     See {@link Files#readAllBytes(Path)}: If an array of the required size cannot be allocated, for example the file is larger
  268.      *                              that {@code 2GB}
  269.      */
  270.     @Override
  271.     public byte[] get() throws IOException {
  272.         if (isInMemory()) {
  273.             if (cachedContent == null && dfos != null) {
  274.                 cachedContent = dfos.getData();
  275.             }
  276.             return cachedContent != null ? cachedContent.clone() : new byte[0];
  277.         }
  278.         return Files.readAllBytes(dfos.getFile().toPath());
  279.     }

  280.     /**
  281.      * Gets the content charset passed by the agent or {@code null} if not defined.
  282.      *
  283.      * @return The content charset passed by the agent or {@code null} if not defined.
  284.      */
  285.     public Charset getCharset() {
  286.         final var parser = new ParameterParser();
  287.         parser.setLowerCaseNames(true);
  288.         // Parameter parser can handle null input
  289.         final var params = parser.parse(getContentType(), ';');
  290.         return Charsets.toCharset(params.get("charset"), charsetDefault);
  291.     }

  292.     /**
  293.      * Gets the default charset for use when no explicit charset parameter is provided by the sender.
  294.      *
  295.      * @return the default charset
  296.      */
  297.     public Charset getCharsetDefault() {
  298.         return charsetDefault;
  299.     }

  300.     /**
  301.      * Gets the content type passed by the agent or {@code null} if not defined.
  302.      *
  303.      * @return The content type passed by the agent or {@code null} if not defined.
  304.      */
  305.     @Override
  306.     public String getContentType() {
  307.         return contentType;
  308.     }

  309.     /**
  310.      * Gets the name of the field in the multipart form corresponding to this file item.
  311.      *
  312.      * @return The name of the form field.
  313.      * @see #setFieldName(String)
  314.      */
  315.     @Override
  316.     public String getFieldName() {
  317.         return fieldName;
  318.     }

  319.     /**
  320.      * Gets the file item headers.
  321.      *
  322.      * @return The file items headers.
  323.      */
  324.     @Override
  325.     public FileItemHeaders getHeaders() {
  326.         return fileItemHeaders;
  327.     }

  328.     /**
  329.      * Gets an {@link java.io.InputStream InputStream} that can be used to retrieve the contents of the file.
  330.      *
  331.      * @return An {@link java.io.InputStream InputStream} that can be used to retrieve the contents of the file.
  332.      * @throws IOException if an error occurs.
  333.      */
  334.     @Override
  335.     public InputStream getInputStream() throws IOException {
  336.         if (!isInMemory()) {
  337.             return Files.newInputStream(dfos.getFile().toPath());
  338.         }

  339.         if (cachedContent == null) {
  340.             cachedContent = dfos.getData();
  341.         }
  342.         return new ByteArrayInputStream(cachedContent);
  343.     }

  344.     /**
  345.      * Gets the original file name in the client's file system.
  346.      *
  347.      * @return The original file name in the client's file system.
  348.      * @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
  349.      *                              anyways, catch the exception and use {@link InvalidPathException#getInput()}.
  350.      */
  351.     @Override
  352.     public String getName() {
  353.         return checkFileName(fileName);
  354.     }

  355.     /**
  356.      * Gets an {@link java.io.OutputStream OutputStream} that can be used for storing the contents of the file.
  357.      *
  358.      * @return An {@link java.io.OutputStream OutputStream} that can be used for storing the contents of the file.
  359.      */
  360.     @Override
  361.     public OutputStream getOutputStream() {
  362.         if (dfos == null) {
  363.             dfos = DeferredFileOutputStream.builder().setThreshold(threshold).setOutputFile(getTempFile().toFile()).get();
  364.         }
  365.         return dfos;
  366.     }

  367.     /**
  368.      * 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
  369.      * 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
  370.      * location without copying the data, if the source and destination locations reside within the same logical volume.
  371.      *
  372.      * @return The data file, or {@code null} if the data is stored in memory.
  373.      */
  374.     public Path getPath() {
  375.         if (dfos == null) {
  376.             return null;
  377.         }
  378.         if (isInMemory()) {
  379.             return null;
  380.         }
  381.         return dfos.getFile().toPath();
  382.     }

  383.     /**
  384.      * Gets the size of the file.
  385.      *
  386.      * @return The size of the file, in bytes.
  387.      */
  388.     @Override
  389.     public long getSize() {
  390.         if (size >= 0) {
  391.             return size;
  392.         }
  393.         if (cachedContent != null) {
  394.             return cachedContent.length;
  395.         }
  396.         return dfos != null ? dfos.getByteCount() : 0;
  397.     }

  398.     /**
  399.      * 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.
  400.      * <p>
  401.      * <strong>TODO</strong> Consider making this method throw UnsupportedEncodingException.
  402.      * </p>
  403.      *
  404.      * @return The contents of the file, as a string.
  405.      * @throws IOException if an I/O error occurs
  406.      */
  407.     @Override
  408.     public String getString() throws IOException {
  409.         return new String(get(), getCharset());
  410.     }

  411.     /**
  412.      * 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.
  413.      *
  414.      * @param charset The charset to use.
  415.      * @return The contents of the file, as a string.
  416.      * @throws IOException if an I/O error occurs
  417.      */
  418.     @Override
  419.     public String getString(final Charset charset) throws IOException {
  420.         return new String(get(), Charsets.toCharset(charset, charsetDefault));
  421.     }

  422.     /**
  423.      * 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
  424.      * is tied to the lifetime of the {@code FileItem} instance; the file will be deleted when the instance is garbage collected.
  425.      * <p>
  426.      * <strong>Note: Subclasses that override this method must ensure that they return the same File each time.</strong>
  427.      * </p>
  428.      *
  429.      * @return The {@link java.io.File File} to be used for temporary storage.
  430.      */
  431.     protected Path getTempFile() {
  432.         return tempFile;
  433.     }

  434.     /**
  435.      * Tests whether or not a {@code FileItem} instance represents a simple form field.
  436.      *
  437.      * @return {@code true} if the instance represents a simple form field; {@code false} if it represents an uploaded file.
  438.      * @see #setFormField(boolean)
  439.      */
  440.     @Override
  441.     public boolean isFormField() {
  442.         return isFormField;
  443.     }

  444.     /**
  445.      * Provides a hint as to whether or not the file contents will be read from memory.
  446.      *
  447.      * @return {@code true} if the file contents will be read from memory; {@code false} otherwise.
  448.      */
  449.     @Override
  450.     public boolean isInMemory() {
  451.         if (cachedContent != null) {
  452.             return true;
  453.         }
  454.         return dfos.isInMemory();
  455.     }

  456.     /**
  457.      * Sets the default charset for use when no explicit charset parameter is provided by the sender.
  458.      *
  459.      * @param charset the default charset
  460.      * @return {@code this} instance.
  461.      */
  462.     public DiskFileItem setCharsetDefault(final Charset charset) {
  463.         charsetDefault = charset;
  464.         return this;
  465.     }

  466.     /**
  467.      * Sets the field name used to reference this file item.
  468.      *
  469.      * @param fieldName The name of the form field.
  470.      * @see #getFieldName()
  471.      */
  472.     @Override
  473.     public DiskFileItem setFieldName(final String fieldName) {
  474.         this.fieldName = fieldName;
  475.         return this;
  476.     }

  477.     /**
  478.      * Specifies whether or not a {@code FileItem} instance represents a simple form field.
  479.      *
  480.      * @param state {@code true} if the instance represents a simple form field; {@code false} if it represents an uploaded file.
  481.      * @see #isFormField()
  482.      */
  483.     @Override
  484.     public DiskFileItem setFormField(final boolean state) {
  485.         isFormField = state;
  486.         return this;
  487.     }

  488.     /**
  489.      * Sets the file item headers.
  490.      *
  491.      * @param headers The file items headers.
  492.      */
  493.     @Override
  494.     public DiskFileItem setHeaders(final FileItemHeaders headers) {
  495.         this.fileItemHeaders = headers;
  496.         return this;
  497.     }

  498.     /**
  499.      * Returns a string representation of this object.
  500.      *
  501.      * @return a string representation of this object.
  502.      */
  503.     @Override
  504.     public String toString() {
  505.         return String.format("name=%s, StoreLocation=%s, size=%s bytes, isFormField=%s, FieldName=%s", getName(), getPath(), getSize(), isFormField(),
  506.                 getFieldName());
  507.     }

  508.     /**
  509.      * Writes an uploaded item to disk.
  510.      * <p>
  511.      * 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
  512.      * uploaded item to a file.
  513.      * </p>
  514.      * <p>
  515.      * This implementation first attempts to rename the uploaded item to the specified destination file, if the item was originally written to disk. Otherwise,
  516.      * the data will be copied to the specified file.
  517.      * </p>
  518.      * <p>
  519.      * 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
  520.      * renames a temporary file, that file will no longer be available to copy or rename again at a later time.
  521.      * </p>
  522.      *
  523.      * @param file The {@code File} into which the uploaded item should be stored.
  524.      * @throws IOException if an error occurs.
  525.      */
  526.     @Override
  527.     public DiskFileItem write(final Path file) throws IOException {
  528.         if (isInMemory()) {
  529.             try (var fout = Files.newOutputStream(file)) {
  530.                 fout.write(get());
  531.             } catch (final IOException e) {
  532.                 throw new IOException("Unexpected output data", e);
  533.             }
  534.         } else {
  535.             final var outputFile = getPath();
  536.             if (outputFile == null) {
  537.                 /*
  538.                  * For whatever reason we cannot write the file to disk.
  539.                  */
  540.                 throw new FileUploadException("Cannot write uploaded file to disk.");
  541.             }
  542.             // Save the length of the file
  543.             size = Files.size(outputFile);
  544.             //
  545.             // The uploaded file is being stored on disk in a temporary location so move it to the desired file.
  546.             //
  547.             Files.move(outputFile, file, StandardCopyOption.REPLACE_EXISTING);
  548.         }
  549.         return this;
  550.     }
  551. }