1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.fileupload2.core;
18
19 import java.io.IOException;
20 import java.nio.charset.Charset;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.Map;
27 import java.util.Objects;
28
29 import org.apache.commons.fileupload2.core.FileItemFactory.AbstractFileItemBuilder;
30 import org.apache.commons.io.IOUtils;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 public abstract class AbstractFileUpload<R, I extends FileItem<I>, F extends FileItemFactory<I>> {
48
49
50
51
52 private static final String BOUNDARY_KEY = "boundary";
53
54
55
56
57 private static final String NAME_KEY = "name";
58
59
60
61
62 private static final String FILENAME_KEY = "filename";
63
64
65
66
67 public static final String CONTENT_TYPE = "Content-type";
68
69
70
71
72 public static final String CONTENT_DISPOSITION = "Content-disposition";
73
74
75
76
77 public static final String CONTENT_LENGTH = "Content-length";
78
79
80
81
82 public static final String FORM_DATA = "form-data";
83
84
85
86
87 public static final String ATTACHMENT = "attachment";
88
89
90
91
92 public static final String MULTIPART = "multipart/";
93
94
95
96
97 public static final String MULTIPART_FORM_DATA = "multipart/form-data";
98
99
100
101
102 public static final String MULTIPART_MIXED = "multipart/mixed";
103
104
105
106
107
108
109
110
111
112
113
114 public static final boolean isMultipartContent(final RequestContext ctx) {
115 final var contentType = ctx.getContentType();
116 if (contentType == null) {
117 return false;
118 }
119 return contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART);
120 }
121
122
123
124
125 private long sizeMax = -1;
126
127
128
129
130 private long fileSizeMax = -1;
131
132
133
134
135 private long fileCountMax = -1;
136
137
138
139
140 private Charset headerCharset;
141
142
143
144
145 private ProgressListener progressListener = ProgressListener.NOP;
146
147
148
149
150 private F fileItemFactory;
151
152
153
154
155
156
157
158 public byte[] getBoundary(final String contentType) {
159 final var parser = new ParameterParser();
160 parser.setLowerCaseNames(true);
161
162 final var params = parser.parse(contentType, new char[] { ';', ',' });
163 final var boundaryStr = params.get(BOUNDARY_KEY);
164 return boundaryStr != null ? boundaryStr.getBytes(StandardCharsets.ISO_8859_1) : null;
165 }
166
167
168
169
170
171
172
173 public String getFieldName(final FileItemHeaders headers) {
174 return getFieldName(headers.getHeader(CONTENT_DISPOSITION));
175 }
176
177
178
179
180
181
182
183 private String getFieldName(final String contentDisposition) {
184 String fieldName = null;
185 if (contentDisposition != null && contentDisposition.toLowerCase(Locale.ENGLISH).startsWith(FORM_DATA)) {
186 final var parser = new ParameterParser();
187 parser.setLowerCaseNames(true);
188
189 final var params = parser.parse(contentDisposition, ';');
190 fieldName = params.get(NAME_KEY);
191 if (fieldName != null) {
192 fieldName = fieldName.trim();
193 }
194 }
195 return fieldName;
196 }
197
198
199
200
201
202
203 public long getFileCountMax() {
204 return fileCountMax;
205 }
206
207
208
209
210
211
212 public F getFileItemFactory() {
213 return fileItemFactory;
214 }
215
216
217
218
219
220
221
222
223 public String getFileName(final FileItemHeaders headers) {
224 return getFileName(headers.getHeader(CONTENT_DISPOSITION));
225 }
226
227
228
229
230
231
232
233 private String getFileName(final String contentDisposition) {
234 String fileName = null;
235 if (contentDisposition != null) {
236 final var cdl = contentDisposition.toLowerCase(Locale.ENGLISH);
237 if (cdl.startsWith(FORM_DATA) || cdl.startsWith(ATTACHMENT)) {
238 final var parser = new ParameterParser();
239 parser.setLowerCaseNames(true);
240
241 final var params = parser.parse(contentDisposition, ';');
242 if (params.containsKey(FILENAME_KEY)) {
243 fileName = params.get(FILENAME_KEY);
244 if (fileName != null) {
245 fileName = fileName.trim();
246 } else {
247
248
249
250 fileName = "";
251 }
252 }
253 }
254 }
255 return fileName;
256 }
257
258
259
260
261
262
263
264 public long getFileSizeMax() {
265 return fileSizeMax;
266 }
267
268
269
270
271
272
273
274 public Charset getHeaderCharset() {
275 return headerCharset;
276 }
277
278
279
280
281
282
283
284
285
286
287 public abstract FileItemInputIterator getItemIterator(R request) throws FileUploadException, IOException;
288
289
290
291
292
293
294
295
296
297
298 public FileItemInputIterator getItemIterator(final RequestContext requestContext) throws FileUploadException, IOException {
299 return new FileItemInputIteratorImpl(this, requestContext);
300 }
301
302
303
304
305
306
307
308
309
310
311 public FileItemHeaders getParsedHeaders(final String headerPart) {
312 final var len = headerPart.length();
313 final var headers = newFileItemHeaders();
314 var start = 0;
315 for (;;) {
316 var end = parseEndOfLine(headerPart, start);
317 if (start == end) {
318 break;
319 }
320 final var header = new StringBuilder(headerPart.substring(start, end));
321 start = end + 2;
322 while (start < len) {
323 var nonWs = start;
324 while (nonWs < len) {
325 final var c = headerPart.charAt(nonWs);
326 if (c != ' ' && c != '\t') {
327 break;
328 }
329 ++nonWs;
330 }
331 if (nonWs == start) {
332 break;
333 }
334
335 end = parseEndOfLine(headerPart, nonWs);
336 header.append(' ').append(headerPart, nonWs, end);
337 start = end + 2;
338 }
339 parseHeaderLine(headers, header.toString());
340 }
341 return headers;
342 }
343
344
345
346
347
348
349 public ProgressListener getProgressListener() {
350 return progressListener;
351 }
352
353
354
355
356
357
358
359
360 public long getSizeMax() {
361 return sizeMax;
362 }
363
364
365
366
367
368
369 protected FileItemHeaders newFileItemHeaders() {
370 return AbstractFileItemBuilder.newFileItemHeaders();
371 }
372
373
374
375
376
377
378
379
380 private int parseEndOfLine(final String headerPart, final int end) {
381 var index = end;
382 for (;;) {
383 final var offset = headerPart.indexOf('\r', index);
384 if (offset == -1 || offset + 1 >= headerPart.length()) {
385 throw new IllegalStateException("Expected headers to be terminated by an empty line.");
386 }
387 if (headerPart.charAt(offset + 1) == '\n') {
388 return offset;
389 }
390 index = offset + 1;
391 }
392 }
393
394
395
396
397
398
399
400 private void parseHeaderLine(final FileItemHeaders headers, final String header) {
401 final var colonOffset = header.indexOf(':');
402 if (colonOffset == -1) {
403
404 return;
405 }
406 final var headerName = header.substring(0, colonOffset).trim();
407 final var headerValue = header.substring(colonOffset + 1).trim();
408 headers.addHeader(headerName, headerValue);
409 }
410
411
412
413
414
415
416
417
418 public abstract Map<String, List<I>> parseParameterMap(R request) throws FileUploadException;
419
420
421
422
423
424
425
426
427 public Map<String, List<I>> parseParameterMap(final RequestContext ctx) throws FileUploadException {
428 final var items = parseRequest(ctx);
429 final Map<String, List<I>> itemsMap = new HashMap<>(items.size());
430
431 for (final I fileItem : items) {
432 final var fieldName = fileItem.getFieldName();
433 final var mappedItems = itemsMap.computeIfAbsent(fieldName, k -> new ArrayList<>());
434 mappedItems.add(fileItem);
435 }
436
437 return itemsMap;
438 }
439
440
441
442
443
444
445
446
447 public abstract List<I> parseRequest(R request) throws FileUploadException;
448
449
450
451
452
453
454
455
456 public List<I> parseRequest(final RequestContext requestContext) throws FileUploadException {
457 final List<I> itemList = new ArrayList<>();
458 var successful = false;
459 try {
460 final var fileItemFactory = Objects.requireNonNull(getFileItemFactory(), "No FileItemFactory has been set.");
461 final var buffer = new byte[IOUtils.DEFAULT_BUFFER_SIZE];
462 getItemIterator(requestContext).forEachRemaining(fileItemInput -> {
463 if (itemList.size() == fileCountMax) {
464
465 throw new FileUploadFileCountLimitException(ATTACHMENT, getFileCountMax(), itemList.size());
466 }
467
468
469 final var fileItem = fileItemFactory.fileItemBuilder()
470 .setFieldName(fileItemInput.getFieldName())
471 .setContentType(fileItemInput.getContentType())
472 .setFormField(fileItemInput.isFormField())
473 .setFileName(fileItemInput.getName())
474 .setFileItemHeaders(fileItemInput.getHeaders())
475 .get();
476
477 itemList.add(fileItem);
478 try (var inputStream = fileItemInput.getInputStream();
479 var outputStream = fileItem.getOutputStream()) {
480 IOUtils.copyLarge(inputStream, outputStream, buffer);
481 } catch (final FileUploadException e) {
482 throw e;
483 } catch (final IOException e) {
484 throw new FileUploadException(String.format("Processing of %s request failed. %s", MULTIPART_FORM_DATA, e.getMessage()), e);
485 }
486 });
487 successful = true;
488 return itemList;
489 } catch (final FileUploadException e) {
490 throw e;
491 } catch (final IOException e) {
492 throw new FileUploadException(e.getMessage(), e);
493 } finally {
494 if (!successful) {
495 for (final I fileItem : itemList) {
496 try {
497 fileItem.delete();
498 } catch (final Exception ignored) {
499
500 }
501 }
502 }
503 }
504 }
505
506
507
508
509
510
511 public void setFileCountMax(final long fileCountMax) {
512 this.fileCountMax = fileCountMax;
513 }
514
515
516
517
518
519
520 public void setFileItemFactory(final F factory) {
521 this.fileItemFactory = factory;
522 }
523
524
525
526
527
528
529
530 public void setFileSizeMax(final long fileSizeMax) {
531 this.fileSizeMax = fileSizeMax;
532 }
533
534
535
536
537
538
539
540 public void setHeaderCharset(final Charset headerCharset) {
541 this.headerCharset = headerCharset;
542 }
543
544
545
546
547
548
549 public void setProgressListener(final ProgressListener progressListener) {
550 this.progressListener = progressListener != null ? progressListener : ProgressListener.NOP;
551 }
552
553
554
555
556
557
558
559 public void setSizeMax(final long sizeMax) {
560 this.sizeMax = sizeMax;
561 }
562
563 }