View Javadoc
1   /**
2    * This file Copyright (c) 2003-2017 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.context.MgnlContext;
39  
40  import java.io.IOException;
41  import java.nio.file.Files;
42  import java.nio.file.Path;
43  import java.util.Enumeration;
44  import java.util.Iterator;
45  
46  import javax.servlet.FilterChain;
47  import javax.servlet.ServletException;
48  import javax.servlet.http.HttpServletRequest;
49  import javax.servlet.http.HttpServletResponse;
50  
51  import org.apache.commons.io.FileUtils;
52  import org.apache.commons.lang3.StringUtils;
53  
54  import com.oreilly.servlet.MultipartRequest;
55  
56  /**
57   * Processes multipart post requests (fileuploads). Files can be accessed with {@link MultipartForm#getDocument(String)}.
58   */
59  public class CosMultipartRequestFilter extends OncePerRequestAbstractMgnlFilter {
60  
61      /**
62       * Max file upload size.
63       */
64      private static final int MAX_FILE_SIZE = 2000000000; // 2GB
65      private static final String TEMP_SUBDIR_PREFIX = "multipart";
66  
67      @Override
68      public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
69              throws IOException, ServletException {
70  
71          String type = null;
72          String type1 = request.getHeader("Content-Type");
73          String type2 = request.getContentType();
74          if (type1 == null && type2 != null) {
75              type = type2;
76          } else if (type2 == null && type1 != null) {
77              type = type1;
78          } else if (type1 != null) {
79              type = (type1.length() > type2.length() ? type1 : type2);
80          }
81          boolean isMultipart = (type != null) && type.toLowerCase().startsWith("multipart/form-data");
82          MultipartForm mpf = null;
83          Path tempDirPath = null;
84          try {
85              if (isMultipart) {
86                  tempDirPath = Files.createTempDirectory(info.magnolia.cms.core.Path.getTempDirectory().toPath(), TEMP_SUBDIR_PREFIX).toAbsolutePath();
87                  mpf = parseParameters(request, tempDirPath.toString());
88                  request = new MultipartRequestWrapper(request, mpf);
89                  MgnlContext.push(request, response);
90              }
91              try {
92                  chain.doFilter(request, response);
93              } finally {
94                  if (isMultipart) {
95                      MgnlContext.pop();
96                  }
97              }
98          } finally {
99              if (mpf != null) {
100                 Iterator<Document> keys = mpf.getDocuments().values().iterator();
101                 while (keys.hasNext()) {
102                     Document doc = keys.next();
103                     if (doc != null && doc.getFile() != null && doc.getFile().exists()) {
104                         doc.delete();
105                     }
106                 }
107             }
108             if (tempDirPath != null) {
109                 FileUtils.deleteQuietly(tempDirPath.toFile());
110             }
111         }
112     }
113 
114     /**
115      * Adds all request paramaters as request attributes.
116      *
117      * @param request HttpServletRequest
118      */
119     private MultipartForm parseParameters(HttpServletRequest request, String tempDirPath) throws IOException {
120         MultipartForm form = new MultipartForm();
121         String encoding = StringUtils.defaultString(request.getCharacterEncoding(), "UTF-8");
122         MultipartRequest multi = new MultipartRequest(
123                 request,
124                 tempDirPath,
125                 MAX_FILE_SIZE,
126                 encoding,
127                 null);
128         Enumeration params = multi.getParameterNames();
129         while (params.hasMoreElements()) {
130             String name = (String) params.nextElement();
131             String value = multi.getParameter(name);
132             form.addParameter(name, value);
133             String[] s = multi.getParameterValues(name);
134             if (s != null) {
135                 form.addparameterValues(name, s);
136             }
137         }
138         Enumeration files = multi.getFileNames();
139         while (files.hasMoreElements()) {
140             String name = (String) files.nextElement();
141             form.addDocument(name, multi.getFilesystemName(name), multi.getContentType(name), multi.getFile(name));
142         }
143         request.setAttribute(MultipartForm.REQUEST_ATTRIBUTE_NAME, form);
144         return form;
145     }
146 }