View Javadoc
1   /**
2    * This file Copyright (c) 2003-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.filters;
35  
36  import info.magnolia.cms.beans.runtime.Document;
37  import info.magnolia.cms.beans.runtime.MultipartForm;
38  import info.magnolia.cms.core.FileSystemHelper;
39  import info.magnolia.context.MgnlContext;
40  import info.magnolia.objectfactory.Components;
41  
42  import java.io.IOException;
43  import java.nio.file.Files;
44  import java.nio.file.Path;
45  import java.util.Enumeration;
46  import java.util.Iterator;
47  import java.util.Locale;
48  
49  import javax.inject.Inject;
50  import javax.servlet.FilterChain;
51  import javax.servlet.ServletException;
52  import javax.servlet.http.HttpServletRequest;
53  import javax.servlet.http.HttpServletResponse;
54  
55  import org.apache.commons.io.FileUtils;
56  import org.apache.commons.lang3.StringUtils;
57  
58  import com.oreilly.servlet.MultipartRequest;
59  
60  /**
61   * Processes multipart post requests (fileuploads). Files can be accessed with {@link MultipartForm#getDocument(String)}.
62   */
63  public class CosMultipartRequestFilter extends OncePerRequestAbstractMgnlFilter {
64  
65      /**
66       * Max file upload size.
67       */
68      private static final int MAX_FILE_SIZE = 2000000000; // 2GB
69      private static final String TEMP_SUBDIR_PREFIX = "multipart";
70  
71      private final FileSystemHelper fileSystemHelper;
72  
73      @Inject
74      public CosMultipartRequestFilter(FileSystemHelper fileSystemHelper) {
75          this.fileSystemHelper = fileSystemHelper;
76      }
77  
78      /**
79       * @deprecated since 5.5.3, use {@link #CosMultipartRequestFilter(FileSystemHelper)} instead.
80       */
81      @Deprecated
82      public CosMultipartRequestFilter() {
83          this(Components.getComponent(FileSystemHelper.class));
84      }
85  
86      @Override
87      public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
88              throws IOException, ServletException {
89  
90          String type = null;
91          String type1 = request.getHeader("Content-Type");
92          String type2 = request.getContentType();
93          if (type1 == null && type2 != null) {
94              type = type2;
95          } else if (type2 == null && type1 != null) {
96              type = type1;
97          } else if (type1 != null) {
98              type = (type1.length() > type2.length() ? type1 : type2);
99          }
100         boolean isMultipart = (type != null) && type.toLowerCase(Locale.ROOT).startsWith("multipart/form-data");
101         MultipartForm mpf = null;
102         Path tempDirPath = null;
103         try {
104             if (isMultipart) {
105                 tempDirPath = Files.createTempDirectory(fileSystemHelper.getTempDirectory().toPath(), TEMP_SUBDIR_PREFIX).toAbsolutePath();
106                 mpf = parseParameters(request, tempDirPath.toString());
107                 request = new MultipartRequestWrapper(request, mpf);
108                 MgnlContext.push(request, response);
109             }
110             try {
111                 chain.doFilter(request, response);
112             } finally {
113                 if (isMultipart) {
114                     MgnlContext.pop();
115                 }
116             }
117         } finally {
118             if (mpf != null) {
119                 Iterator<Document> keys = mpf.getDocuments().values().iterator();
120                 while (keys.hasNext()) {
121                     Document doc = keys.next();
122                     if (doc != null && doc.getFile() != null && doc.getFile().exists()) {
123                         doc.delete();
124                     }
125                 }
126             }
127             if (tempDirPath != null) {
128                 FileUtils.deleteQuietly(tempDirPath.toFile());
129             }
130         }
131     }
132 
133     /**
134      * Adds all request paramaters as request attributes.
135      *
136      * @param request HttpServletRequest
137      */
138     private MultipartForm parseParameters(HttpServletRequest request, String tempDirPath) throws IOException {
139         MultipartForm form = new MultipartForm();
140         String encoding = StringUtils.defaultString(request.getCharacterEncoding(), "UTF-8");
141         MultipartRequest multi = new MultipartRequest(
142                 request,
143                 tempDirPath,
144                 MAX_FILE_SIZE,
145                 encoding,
146                 null);
147         Enumeration params = multi.getParameterNames();
148         while (params.hasMoreElements()) {
149             String name = (String) params.nextElement();
150             String value = multi.getParameter(name);
151             form.addParameter(name, value);
152             String[] s = multi.getParameterValues(name);
153             if (s != null) {
154                 form.addparameterValues(name, s);
155             }
156         }
157         Enumeration files = multi.getFileNames();
158         while (files.hasMoreElements()) {
159             String name = (String) files.nextElement();
160             form.addDocument(name, multi.getFilesystemName(name), multi.getContentType(name), multi.getFile(name));
161         }
162         request.setAttribute(MultipartForm.REQUEST_ATTRIBUTE_NAME, form);
163         return form;
164     }
165 }