|
| 1 | +/* |
| 2 | + * Copyright (C) 2009-2017 Slava Semushin <[email protected]> |
| 3 | + * |
| 4 | + * This program is free software; you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU General Public License as published by |
| 6 | + * the Free Software Foundation; either version 2 of the License, or |
| 7 | + * (at your option) any later version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU General Public License |
| 15 | + * along with this program; if not, write to the Free Software |
| 16 | + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 17 | + */ |
| 18 | +package ru.mystamps.web.controller.interceptor; |
| 19 | + |
| 20 | +import java.io.BufferedInputStream; |
| 21 | +import java.io.ByteArrayInputStream; |
| 22 | +import java.io.File; |
| 23 | +import java.io.FileNotFoundException; |
| 24 | +import java.io.IOException; |
| 25 | +import java.io.InputStream; |
| 26 | +import java.net.HttpURLConnection; |
| 27 | +import java.net.MalformedURLException; |
| 28 | +import java.net.URL; |
| 29 | +import java.net.URLConnection; |
| 30 | +import java.util.concurrent.TimeUnit; |
| 31 | + |
| 32 | +import javax.servlet.http.HttpServletRequest; |
| 33 | +import javax.servlet.http.HttpServletResponse; |
| 34 | + |
| 35 | +import org.apache.commons.lang3.StringUtils; |
| 36 | + |
| 37 | +import org.slf4j.Logger; |
| 38 | +import org.slf4j.LoggerFactory; |
| 39 | + |
| 40 | +import org.springframework.util.StreamUtils; |
| 41 | +import org.springframework.web.multipart.MultipartFile; |
| 42 | +import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; |
| 43 | +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; |
| 44 | + |
| 45 | +import lombok.RequiredArgsConstructor; |
| 46 | + |
| 47 | +// TODO: javadoc |
| 48 | +public class DownloadImageInterceptor extends HandlerInterceptorAdapter { |
| 49 | + private static final Logger LOG = LoggerFactory.getLogger(DownloadImageInterceptor.class); |
| 50 | + |
| 51 | + @Override |
| 52 | + @SuppressWarnings("PMD.SignatureDeclareThrowsException") |
| 53 | + public boolean preHandle( |
| 54 | + HttpServletRequest request, |
| 55 | + HttpServletResponse response, |
| 56 | + Object handler) throws Exception { |
| 57 | + |
| 58 | + if (!"POST".equals(request.getMethod())) { |
| 59 | + return true; |
| 60 | + } |
| 61 | + |
| 62 | + // Inspecting AddSeriesForm.imageUrl field. |
| 63 | + // If it doesn't have a value, then nothing to do here. |
| 64 | + String imageUrl = request.getParameter("imageUrl"); |
| 65 | + if (StringUtils.isEmpty(imageUrl)) { |
| 66 | + return true; |
| 67 | + } |
| 68 | + |
| 69 | + if (!(request instanceof StandardMultipartHttpServletRequest)) { |
| 70 | + LOG.warn( |
| 71 | + "Unknown type of request ({}). " |
| 72 | + + "Downloading images from external servers won't work!", |
| 73 | + request |
| 74 | + ); |
| 75 | + return true; |
| 76 | + } |
| 77 | + |
| 78 | + LOG.debug("preHandle imageUrl = {}", imageUrl); |
| 79 | + |
| 80 | + StandardMultipartHttpServletRequest multipartRequest = |
| 81 | + (StandardMultipartHttpServletRequest)request; |
| 82 | + MultipartFile image = multipartRequest.getFile("image"); |
| 83 | + if (image != null && StringUtils.isNotEmpty(image.getOriginalFilename())) { |
| 84 | + LOG.debug("User provided image, exited"); |
| 85 | + // user specified both image and image URL, we'll handle it later, during validation |
| 86 | + return true; |
| 87 | + } |
| 88 | + |
| 89 | + // user specified image URL: we should download file and represent it as "downloadedImage" field. |
| 90 | + // Doing this our validation will be able to check downloaded file later. |
| 91 | + |
| 92 | + byte[] data; |
| 93 | + try { |
| 94 | + URL url = new URL(imageUrl); |
| 95 | + LOG.debug("URL.getPath(): {} / URL.getFile(): {}", url.getPath(), url.getFile()); |
| 96 | + |
| 97 | + if (!"http".equals(url.getProtocol())) { |
| 98 | + // TODO(security): fix possible log injection |
| 99 | + LOG.info("Invalid link '{}': only HTTP protocol is supported", imageUrl); |
| 100 | + return true; |
| 101 | + } |
| 102 | + |
| 103 | + try { |
| 104 | + URLConnection connection = url.openConnection(); |
| 105 | + if (!(connection instanceof HttpURLConnection)) { |
| 106 | + LOG.warn( |
| 107 | + "Unknown type of connection class ({}). " |
| 108 | + + "Downloading images from external servers won't work!", |
| 109 | + connection |
| 110 | + ); |
| 111 | + return true; |
| 112 | + } |
| 113 | + HttpURLConnection conn = (HttpURLConnection)connection; |
| 114 | + |
| 115 | + conn.setRequestProperty( |
| 116 | + "User-Agent", |
| 117 | + "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0" |
| 118 | + ); |
| 119 | + |
| 120 | + long timeout = TimeUnit.SECONDS.toMillis(1); |
| 121 | + conn.setReadTimeout(Math.toIntExact(timeout)); |
| 122 | + LOG.debug("getReadTimeout(): {}", conn.getReadTimeout()); |
| 123 | + |
| 124 | + // TODO: how bad is it? |
| 125 | + conn.setInstanceFollowRedirects(false); |
| 126 | + |
| 127 | + try { |
| 128 | + conn.connect(); |
| 129 | + } catch (IOException ex) { |
| 130 | + // TODO(security): fix possible log injection |
| 131 | + LOG.error("Couldn't connect to '{}': {}", imageUrl, ex.getMessage()); |
| 132 | + return true; |
| 133 | + } |
| 134 | + |
| 135 | + try (InputStream stream = new BufferedInputStream(conn.getInputStream())) { |
| 136 | + int status = conn.getResponseCode(); |
| 137 | + if (status != HttpURLConnection.HTTP_OK) { |
| 138 | + // TODO(security): fix possible log injection |
| 139 | + LOG.error( |
| 140 | + "Couldn't download file '{}': bad response status {}", |
| 141 | + imageUrl, |
| 142 | + status |
| 143 | + ); |
| 144 | + return true; |
| 145 | + } |
| 146 | + |
| 147 | + // TODO: add protection against huge files |
| 148 | + int contentLength = conn.getContentLength(); |
| 149 | + LOG.debug("Content-Length: {}", contentLength); |
| 150 | + if (contentLength <= 0) { |
| 151 | + // TODO(security): fix possible log injection |
| 152 | + LOG.error( |
| 153 | + "Couldn't download file '{}': it has {} bytes length", |
| 154 | + imageUrl, |
| 155 | + contentLength |
| 156 | + ); |
| 157 | + return true; |
| 158 | + } |
| 159 | + |
| 160 | + String contentType = conn.getContentType(); |
| 161 | + LOG.debug("Content-Type: {}", contentType); |
| 162 | + if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) { |
| 163 | + // TODO(security): fix possible log injection |
| 164 | + LOG.error( |
| 165 | + "Couldn't download file '{}': unsupported image type '{}'", |
| 166 | + imageUrl, |
| 167 | + contentType |
| 168 | + ); |
| 169 | + return true; |
| 170 | + } |
| 171 | + |
| 172 | + data = StreamUtils.copyToByteArray(stream); |
| 173 | + |
| 174 | + } catch (FileNotFoundException ignored) { |
| 175 | + // TODO: show error to user |
| 176 | + // TODO(security): fix possible log injection |
| 177 | + LOG.error("Couldn't download file '{}': not found", imageUrl); |
| 178 | + return true; |
| 179 | + |
| 180 | + } catch (IOException ex) { |
| 181 | + // TODO(security): fix possible log injection |
| 182 | + LOG.error( |
| 183 | + "Couldn't download file from URL '{}': {}", |
| 184 | + imageUrl, |
| 185 | + ex.getMessage() |
| 186 | + ); |
| 187 | + return true; |
| 188 | + } |
| 189 | + |
| 190 | + } catch (IOException ex) { |
| 191 | + LOG.error("Couldn't open connection: {}", ex.getMessage()); |
| 192 | + return true; |
| 193 | + } |
| 194 | + |
| 195 | + } catch (MalformedURLException ex) { |
| 196 | + // TODO(security): fix possible log injection |
| 197 | + // TODO: show error to user |
| 198 | + LOG.error("Invalid image URL '{}': {}", imageUrl, ex.getMessage()); |
| 199 | + return true; |
| 200 | + } |
| 201 | + |
| 202 | + // TODO: use URL.getFile() instead of full link? |
| 203 | + multipartRequest.getMultiFileMap().set("downloadedImage", new MyMultipartFile(data, imageUrl)); |
| 204 | + |
| 205 | + // TODO: how we can validate url? |
| 206 | + |
| 207 | + return true; |
| 208 | + } |
| 209 | + |
| 210 | + @RequiredArgsConstructor |
| 211 | + private static class MyMultipartFile implements MultipartFile { |
| 212 | + private final byte[] content; |
| 213 | + private final String link; |
| 214 | + |
| 215 | + @Override |
| 216 | + public String getName() { |
| 217 | + throw new IllegalStateException("Not implemented"); |
| 218 | + } |
| 219 | + |
| 220 | + @Override |
| 221 | + public String getOriginalFilename() { |
| 222 | + return link; |
| 223 | + } |
| 224 | + |
| 225 | + @Override |
| 226 | + public String getContentType() { |
| 227 | + return "image/jpeg"; |
| 228 | + } |
| 229 | + |
| 230 | + @Override |
| 231 | + public boolean isEmpty() { |
| 232 | + return getSize() == 0; |
| 233 | + } |
| 234 | + |
| 235 | + @Override |
| 236 | + public long getSize() { |
| 237 | + return content.length; |
| 238 | + } |
| 239 | + |
| 240 | + @Override |
| 241 | + public byte[] getBytes() throws IOException { |
| 242 | + return content; |
| 243 | + } |
| 244 | + |
| 245 | + @Override |
| 246 | + public InputStream getInputStream() throws IOException { |
| 247 | + return new ByteArrayInputStream(content); |
| 248 | + } |
| 249 | + |
| 250 | + @Override |
| 251 | + public void transferTo(File dest) throws IOException, IllegalStateException { |
| 252 | + throw new IllegalStateException("Not implemented"); |
| 253 | + } |
| 254 | + } |
| 255 | + |
| 256 | +} |
0 commit comments