1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.fileupload;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.UnsupportedEncodingException;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.NoSuchElementException;
28
29 import javax.servlet.http.HttpServletRequest;
30
31 import org.apache.commons.fileupload.MultipartStream.ItemInputStream;
32 import org.apache.commons.fileupload.servlet.ServletFileUpload;
33 import org.apache.commons.fileupload.servlet.ServletRequestContext;
34 import org.apache.commons.fileupload.util.Closeable;
35 import org.apache.commons.fileupload.util.FileItemHeadersImpl;
36 import org.apache.commons.fileupload.util.LimitedInputStream;
37 import org.apache.commons.fileupload.util.Streams;
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 public abstract class FileUploadBase {
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82 public static final boolean isMultipartContent(RequestContext ctx) {
83 String contentType = ctx.getContentType();
84 if (contentType == null) {
85 return false;
86 }
87 if (contentType.toLowerCase().startsWith(MULTIPART)) {
88 return true;
89 }
90 return false;
91 }
92
93
94
95
96
97
98
99
100
101
102
103
104
105 public static boolean isMultipartContent(HttpServletRequest req) {
106 return ServletFileUpload.isMultipartContent(req);
107 }
108
109
110
111
112
113
114
115
116 public static final String CONTENT_TYPE = "Content-type";
117
118
119
120
121
122 public static final String CONTENT_DISPOSITION = "Content-disposition";
123
124
125
126
127 public static final String CONTENT_LENGTH = "Content-length";
128
129
130
131
132
133 public static final String FORM_DATA = "form-data";
134
135
136
137
138
139 public static final String ATTACHMENT = "attachment";
140
141
142
143
144
145 public static final String MULTIPART = "multipart/";
146
147
148
149
150
151 public static final String MULTIPART_FORM_DATA = "multipart/form-data";
152
153
154
155
156
157 public static final String MULTIPART_MIXED = "multipart/mixed";
158
159
160
161
162
163
164
165
166
167 public static final int MAX_HEADER_SIZE = 1024;
168
169
170
171
172
173
174
175
176
177 private long sizeMax = -1;
178
179
180
181
182
183 private long fileSizeMax = -1;
184
185
186
187
188 private String headerEncoding;
189
190
191
192
193 private ProgressListener listener;
194
195
196
197
198
199
200
201
202
203 public abstract FileItemFactory getFileItemFactory();
204
205
206
207
208
209
210
211 public abstract void setFileItemFactory(FileItemFactory factory);
212
213
214
215
216
217
218
219
220
221
222
223
224 public long getSizeMax() {
225 return sizeMax;
226 }
227
228
229
230
231
232
233
234
235
236
237
238
239 public void setSizeMax(long sizeMax) {
240 this.sizeMax = sizeMax;
241 }
242
243
244
245
246
247
248
249
250 public long getFileSizeMax() {
251 return fileSizeMax;
252 }
253
254
255
256
257
258
259
260
261 public void setFileSizeMax(long fileSizeMax) {
262 this.fileSizeMax = fileSizeMax;
263 }
264
265
266
267
268
269
270
271
272
273 public String getHeaderEncoding() {
274 return headerEncoding;
275 }
276
277
278
279
280
281
282
283
284
285
286 public void setHeaderEncoding(String encoding) {
287 headerEncoding = encoding;
288 }
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308 public List
309 throws FileUploadException {
310 return parseRequest(new ServletRequestContext(req));
311 }
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329 public FileItemIterator getItemIterator(RequestContext ctx)
330 throws FileUploadException, IOException {
331 return new FileItemIteratorImpl(ctx);
332 }
333
334
335
336
337
338
339
340
341
342
343
344
345
346 public List
347 throws FileUploadException {
348 List items = new ArrayList();
349 boolean successful = false;
350 try {
351 FileItemIterator iter = getItemIterator(ctx);
352 FileItemFactory fac = getFileItemFactory();
353 if (fac == null) {
354 throw new NullPointerException(
355 "No FileItemFactory has been set.");
356 }
357 while (iter.hasNext()) {
358 final FileItemStream item = iter.next();
359
360 final String fileName = ((org.apache.commons.fileupload.FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl) item).name;
361 FileItem fileItem = fac.createItem(item.getFieldName(),
362 item.getContentType(), item.isFormField(),
363 fileName);
364 items.add(fileItem);
365 try {
366 Streams.copy(item.openStream(), fileItem.getOutputStream(),
367 true);
368 } catch (FileUploadIOException e) {
369 throw (FileUploadException) e.getCause();
370 } catch (IOException e) {
371 throw new IOFileUploadException(
372 "Processing of " + MULTIPART_FORM_DATA
373 + " request failed. " + e.getMessage(), e);
374 }
375 if (fileItem instanceof FileItemHeadersSupport) {
376 final FileItemHeaders fih = item.getHeaders();
377 ((FileItemHeadersSupport) fileItem).setHeaders(fih);
378 }
379 }
380 successful = true;
381 return items;
382 } catch (FileUploadIOException e) {
383 throw (FileUploadException) e.getCause();
384 } catch (IOException e) {
385 throw new FileUploadException(e.getMessage(), e);
386 } finally {
387 if (!successful) {
388 for (Iterator iterator = items.iterator(); iterator.hasNext();) {
389 FileItem fileItem = (FileItem) iterator.next();
390 try {
391 fileItem.delete();
392 } catch (Throwable e) {
393
394 }
395 }
396 }
397 }
398 }
399
400
401
402
403
404
405
406
407
408
409
410
411
412 protected byte[] getBoundary(String contentType) {
413 ParameterParser parser = new ParameterParser();
414 parser.setLowerCaseNames(true);
415
416 Map params = parser.parse(contentType, new char[] {';', ','});
417 String boundaryStr = (String) params.get("boundary");
418
419 if (boundaryStr == null) {
420 return null;
421 }
422 byte[] boundary;
423 try {
424 boundary = boundaryStr.getBytes("ISO-8859-1");
425 } catch (UnsupportedEncodingException e) {
426 boundary = boundaryStr.getBytes();
427 }
428 return boundary;
429 }
430
431
432
433
434
435
436
437
438
439
440
441 protected String getFileName(Map
442 return getFileName(getHeader(headers, CONTENT_DISPOSITION));
443 }
444
445
446
447
448
449
450
451
452
453 protected String getFileName(FileItemHeaders headers) {
454 return getFileName(headers.getHeader(CONTENT_DISPOSITION));
455 }
456
457
458
459
460
461
462 private String getFileName(String pContentDisposition) {
463 String fileName = null;
464 if (pContentDisposition != null) {
465 String cdl = pContentDisposition.toLowerCase();
466 if (cdl.startsWith(FORM_DATA) || cdl.startsWith(ATTACHMENT)) {
467 ParameterParser parser = new ParameterParser();
468 parser.setLowerCaseNames(true);
469
470 Map params = parser.parse(pContentDisposition, ';');
471 if (params.containsKey("filename")) {
472 fileName = (String) params.get("filename");
473 if (fileName != null) {
474 fileName = fileName.trim();
475 } else {
476
477
478
479 fileName = "";
480 }
481 }
482 }
483 }
484 return fileName;
485 }
486
487
488
489
490
491
492
493
494
495
496 protected String getFieldName(FileItemHeaders headers) {
497 return getFieldName(headers.getHeader(CONTENT_DISPOSITION));
498 }
499
500
501
502
503
504
505
506 private String getFieldName(String pContentDisposition) {
507 String fieldName = null;
508 if (pContentDisposition != null
509 && pContentDisposition.toLowerCase().startsWith(FORM_DATA)) {
510 ParameterParser parser = new ParameterParser();
511 parser.setLowerCaseNames(true);
512
513 Map params = parser.parse(pContentDisposition, ';');
514 fieldName = (String) params.get("name");
515 if (fieldName != null) {
516 fieldName = fieldName.trim();
517 }
518 }
519 return fieldName;
520 }
521
522
523
524
525
526
527
528
529
530
531 protected String getFieldName(Map
532 return getFieldName(getHeader(headers, CONTENT_DISPOSITION));
533 }
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550 protected FileItem createItem(Map
551 boolean isFormField)
552 throws FileUploadException {
553 return getFileItemFactory().createItem(getFieldName(headers),
554 getHeader(headers, CONTENT_TYPE),
555 isFormField,
556 getFileName(headers));
557 }
558
559
560
561
562
563
564
565
566
567
568
569
570
571 protected FileItemHeaders getParsedHeaders(String headerPart) {
572 final int len = headerPart.length();
573 FileItemHeadersImpl headers = newFileItemHeaders();
574 int start = 0;
575 for (;;) {
576 int end = parseEndOfLine(headerPart, start);
577 if (start == end) {
578 break;
579 }
580 String header = headerPart.substring(start, end);
581 start = end + 2;
582 while (start < len) {
583 int nonWs = start;
584 while (nonWs < len) {
585 char c = headerPart.charAt(nonWs);
586 if (c != ' ' && c != '\t') {
587 break;
588 }
589 ++nonWs;
590 }
591 if (nonWs == start) {
592 break;
593 }
594
595 end = parseEndOfLine(headerPart, nonWs);
596 header += " " + headerPart.substring(nonWs, end);
597 start = end + 2;
598 }
599 parseHeaderLine(headers, header);
600 }
601 return headers;
602 }
603
604
605
606
607
608 protected FileItemHeadersImpl newFileItemHeaders() {
609 return new FileItemHeadersImpl();
610 }
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625 protected Map
626 FileItemHeaders headers = getParsedHeaders(headerPart);
627 Map result = new HashMap();
628 for (Iterator iter = headers.getHeaderNames(); iter.hasNext();) {
629 String headerName = (String) iter.next();
630 Iterator iter2 = headers.getHeaders(headerName);
631 String headerValue = (String) iter2.next();
632 while (iter2.hasNext()) {
633 headerValue += "," + iter2.next();
634 }
635 result.put(headerName, headerValue);
636 }
637 return result;
638 }
639
640
641
642
643
644
645
646
647
648 private int parseEndOfLine(String headerPart, int end) {
649 int index = end;
650 for (;;) {
651 int offset = headerPart.indexOf('\r', index);
652 if (offset == -1 || offset + 1 >= headerPart.length()) {
653 throw new IllegalStateException(
654 "Expected headers to be terminated by an empty line.");
655 }
656 if (headerPart.charAt(offset + 1) == '\n') {
657 return offset;
658 }
659 index = offset + 1;
660 }
661 }
662
663
664
665
666
667
668 private void parseHeaderLine(FileItemHeadersImpl headers, String header) {
669 final int colonOffset = header.indexOf(':');
670 if (colonOffset == -1) {
671
672 return;
673 }
674 String headerName = header.substring(0, colonOffset).trim();
675 String headerValue =
676 header.substring(header.indexOf(':') + 1).trim();
677 headers.addHeader(headerName, headerValue);
678 }
679
680
681
682
683
684
685
686
687
688
689
690
691 protected final String getHeader(Map
692 String name) {
693 return (String) headers.get(name.toLowerCase());
694 }
695
696
697
698
699
700 private class FileItemIteratorImpl implements FileItemIterator {
701
702
703
704 class FileItemStreamImpl implements FileItemStream {
705
706
707 private final String contentType;
708
709
710 private final String fieldName;
711
712
713 private final String name;
714
715
716 private final boolean formField;
717
718
719 private final InputStream stream;
720
721
722 private boolean opened;
723
724
725 private FileItemHeaders headers;
726
727
728
729
730
731
732
733
734
735
736 FileItemStreamImpl(String pName, String pFieldName,
737 String pContentType, boolean pFormField,
738 long pContentLength) throws IOException {
739 name = pName;
740 fieldName = pFieldName;
741 contentType = pContentType;
742 formField = pFormField;
743 final ItemInputStream itemStream = multi.newInputStream();
744 InputStream istream = itemStream;
745 if (fileSizeMax != -1) {
746 if (pContentLength != -1
747 && pContentLength > fileSizeMax) {
748 FileSizeLimitExceededException e =
749 new FileSizeLimitExceededException(
750 "The field " + fieldName
751 + " exceeds its maximum permitted "
752 + " size of " + fileSizeMax
753 + " bytes.",
754 pContentLength, fileSizeMax);
755 e.setFileName(pName);
756 e.setFieldName(pFieldName);
757 throw new FileUploadIOException(e);
758 }
759 istream = new LimitedInputStream(istream, fileSizeMax) {
760 protected void raiseError(long pSizeMax, long pCount)
761 throws IOException {
762 itemStream.close(true);
763 FileSizeLimitExceededException e =
764 new FileSizeLimitExceededException(
765 "The field " + fieldName
766 + " exceeds its maximum permitted "
767 + " size of " + pSizeMax
768 + " bytes.",
769 pCount, pSizeMax);
770 e.setFieldName(fieldName);
771 e.setFileName(name);
772 throw new FileUploadIOException(e);
773 }
774 };
775 }
776 stream = istream;
777 }
778
779
780
781
782
783 public String getContentType() {
784 return contentType;
785 }
786
787
788
789
790
791 public String getFieldName() {
792 return fieldName;
793 }
794
795
796
797
798
799
800
801
802
803 public String getName() {
804 return Streams.checkFileName(name);
805 }
806
807
808
809
810
811
812 public boolean isFormField() {
813 return formField;
814 }
815
816
817
818
819
820
821
822 public InputStream openStream() throws IOException {
823 if (opened) {
824 throw new IllegalStateException(
825 "The stream was already opened.");
826 }
827 if (((Closeable) stream).isClosed()) {
828 throw new FileItemStream.ItemSkippedException();
829 }
830 return stream;
831 }
832
833
834
835
836
837 void close() throws IOException {
838 stream.close();
839 }
840
841
842
843
844
845 public FileItemHeaders getHeaders() {
846 return headers;
847 }
848
849
850
851
852
853 public void setHeaders(FileItemHeaders pHeaders) {
854 headers = pHeaders;
855 }
856 }
857
858
859
860
861 private final MultipartStream multi;
862
863
864
865
866 private final MultipartStream.ProgressNotifier notifier;
867
868
869
870 private final byte[] boundary;
871
872
873
874 private FileItemStreamImpl currentItem;
875
876
877
878 private String currentFieldName;
879
880
881
882 private boolean skipPreamble;
883
884
885
886 private boolean itemValid;
887
888
889
890 private boolean eof;
891
892
893
894
895
896
897
898
899 FileItemIteratorImpl(RequestContext ctx)
900 throws FileUploadException, IOException {
901 if (ctx == null) {
902 throw new NullPointerException("ctx parameter");
903 }
904
905 String contentType = ctx.getContentType();
906 if ((null == contentType)
907 || (!contentType.toLowerCase().startsWith(MULTIPART))) {
908 throw new InvalidContentTypeException(
909 "the request doesn't contain a "
910 + MULTIPART_FORM_DATA
911 + " or "
912 + MULTIPART_MIXED
913 + " stream, content type header is "
914 + contentType);
915 }
916
917 InputStream input = ctx.getInputStream();
918
919 if (sizeMax >= 0) {
920 int requestSize = ctx.getContentLength();
921 if (requestSize == -1) {
922 input = new LimitedInputStream(input, sizeMax) {
923 protected void raiseError(long pSizeMax, long pCount)
924 throws IOException {
925 FileUploadException ex =
926 new SizeLimitExceededException(
927 "the request was rejected because"
928 + " its size (" + pCount
929 + ") exceeds the configured maximum"
930 + " (" + pSizeMax + ")",
931 pCount, pSizeMax);
932 throw new FileUploadIOException(ex);
933 }
934 };
935 } else {
936 if (sizeMax >= 0 && requestSize > sizeMax) {
937 throw new SizeLimitExceededException(
938 "the request was rejected because its size ("
939 + requestSize
940 + ") exceeds the configured maximum ("
941 + sizeMax + ")",
942 requestSize, sizeMax);
943 }
944 }
945 }
946
947 String charEncoding = headerEncoding;
948 if (charEncoding == null) {
949 charEncoding = ctx.getCharacterEncoding();
950 }
951
952 boundary = getBoundary(contentType);
953 if (boundary == null) {
954 throw new FileUploadException(
955 "the request was rejected because "
956 + "no multipart boundary was found");
957 }
958
959 notifier = new MultipartStream.ProgressNotifier(listener,
960 ctx.getContentLength());
961 multi = new MultipartStream(input, boundary, notifier);
962 multi.setHeaderEncoding(charEncoding);
963
964 skipPreamble = true;
965 findNextItem();
966 }
967
968
969
970
971
972
973 private boolean findNextItem() throws IOException {
974 if (eof) {
975 return false;
976 }
977 if (currentItem != null) {
978 currentItem.close();
979 currentItem = null;
980 }
981 for (;;) {
982 boolean nextPart;
983 if (skipPreamble) {
984 nextPart = multi.skipPreamble();
985 } else {
986 nextPart = multi.readBoundary();
987 }
988 if (!nextPart) {
989 if (currentFieldName == null) {
990
991 eof = true;
992 return false;
993 }
994
995 multi.setBoundary(boundary);
996 currentFieldName = null;
997 continue;
998 }
999 FileItemHeaders headers = getParsedHeaders(multi.readHeaders());
1000 if (currentFieldName == null) {
1001
1002 String fieldName = getFieldName(headers);
1003 if (fieldName != null) {
1004 String subContentType = headers.getHeader(CONTENT_TYPE);
1005 if (subContentType != null
1006 && subContentType.toLowerCase()
1007 .startsWith(MULTIPART_MIXED)) {
1008 currentFieldName = fieldName;
1009
1010 byte[] subBoundary = getBoundary(subContentType);
1011 multi.setBoundary(subBoundary);
1012 skipPreamble = true;
1013 continue;
1014 }
1015 String fileName = getFileName(headers);
1016 currentItem = new FileItemStreamImpl(fileName,
1017 fieldName, headers.getHeader(CONTENT_TYPE),
1018 fileName == null, getContentLength(headers));
1019 notifier.noteItem();
1020 itemValid = true;
1021 return true;
1022 }
1023 } else {
1024 String fileName = getFileName(headers);
1025 if (fileName != null) {
1026 currentItem = new FileItemStreamImpl(fileName,
1027 currentFieldName,
1028 headers.getHeader(CONTENT_TYPE),
1029 false, getContentLength(headers));
1030 notifier.noteItem();
1031 itemValid = true;
1032 return true;
1033 }
1034 }
1035 multi.discardBodyData();
1036 }
1037 }
1038
1039 private long getContentLength(FileItemHeaders pHeaders) {
1040 try {
1041 return Long.parseLong(pHeaders.getHeader(CONTENT_LENGTH));
1042 } catch (Exception e) {
1043 return -1;
1044 }
1045 }
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056 public boolean hasNext() throws FileUploadException, IOException {
1057 if (eof) {
1058 return false;
1059 }
1060 if (itemValid) {
1061 return true;
1062 }
1063 return findNextItem();
1064 }
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076 public FileItemStream next() throws FileUploadException, IOException {
1077 if (eof || (!itemValid && !hasNext())) {
1078 throw new NoSuchElementException();
1079 }
1080 itemValid = false;
1081 return currentItem;
1082 }
1083 }
1084
1085
1086
1087
1088
1089 public static class FileUploadIOException extends IOException {
1090
1091
1092 private static final long serialVersionUID = -7047616958165584154L;
1093
1094
1095
1096
1097 private final FileUploadException cause;
1098
1099
1100
1101
1102
1103
1104 public FileUploadIOException(FileUploadException pCause) {
1105
1106 cause = pCause;
1107 }
1108
1109
1110
1111
1112
1113 public Throwable getCause() {
1114 return cause;
1115 }
1116 }
1117
1118
1119
1120
1121 public static class InvalidContentTypeException
1122 extends FileUploadException {
1123
1124
1125 private static final long serialVersionUID = -9073026332015646668L;
1126
1127
1128
1129
1130
1131 public InvalidContentTypeException() {
1132
1133 }
1134
1135
1136
1137
1138
1139
1140
1141 public InvalidContentTypeException(String message) {
1142 super(message);
1143 }
1144 }
1145
1146
1147
1148
1149 public static class IOFileUploadException extends FileUploadException {
1150
1151
1152 private static final long serialVersionUID = 1749796615868477269L;
1153
1154
1155
1156
1157 private final IOException cause;
1158
1159
1160
1161
1162
1163
1164 public IOFileUploadException(String pMsg, IOException pException) {
1165 super(pMsg);
1166 cause = pException;
1167 }
1168
1169
1170
1171
1172
1173 public Throwable getCause() {
1174 return cause;
1175 }
1176 }
1177
1178
1179
1180
1181 protected abstract static class SizeException extends FileUploadException {
1182 private static final long serialVersionUID = -8776225574705254126L;
1183
1184
1185
1186
1187 private final long actual;
1188
1189
1190
1191
1192 private final long permitted;
1193
1194
1195
1196
1197
1198
1199
1200 protected SizeException(String message, long actual, long permitted) {
1201 super(message);
1202 this.actual = actual;
1203 this.permitted = permitted;
1204 }
1205
1206
1207
1208
1209
1210
1211 public long getActualSize() {
1212 return actual;
1213 }
1214
1215
1216
1217
1218
1219
1220 public long getPermittedSize() {
1221 return permitted;
1222 }
1223 }
1224
1225
1226
1227
1228
1229
1230
1231
1232 public static class UnknownSizeException
1233 extends FileUploadException {
1234
1235
1236 private static final long serialVersionUID = 7062279004812015273L;
1237
1238
1239
1240
1241
1242 public UnknownSizeException() {
1243 super();
1244 }
1245
1246
1247
1248
1249
1250
1251
1252 public UnknownSizeException(String message) {
1253 super(message);
1254 }
1255 }
1256
1257
1258
1259
1260 public static class SizeLimitExceededException
1261 extends SizeException {
1262
1263
1264 private static final long serialVersionUID = -2474893167098052828L;
1265
1266
1267
1268
1269
1270 public SizeLimitExceededException() {
1271 this(null, 0, 0);
1272 }
1273
1274
1275
1276
1277
1278
1279 public SizeLimitExceededException(String message) {
1280 this(message, 0, 0);
1281 }
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291 public SizeLimitExceededException(String message, long actual,
1292 long permitted) {
1293 super(message, actual, permitted);
1294 }
1295 }
1296
1297
1298
1299
1300 public static class FileSizeLimitExceededException
1301 extends SizeException {
1302
1303
1304 private static final long serialVersionUID = 8150776562029630058L;
1305
1306
1307
1308
1309 private String fileName;
1310
1311
1312
1313
1314 private String fieldName;
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324 public FileSizeLimitExceededException(String message, long actual,
1325 long permitted) {
1326 super(message, actual, permitted);
1327 }
1328
1329
1330
1331
1332
1333
1334 public String getFileName() {
1335 return fileName;
1336 }
1337
1338
1339
1340
1341
1342 public void setFileName(String pFileName) {
1343 fileName = pFileName;
1344 }
1345
1346
1347
1348
1349
1350
1351 public String getFieldName() {
1352 return fieldName;
1353 }
1354
1355
1356
1357
1358
1359 public void setFieldName(String pFieldName) {
1360 fieldName = pFieldName;
1361 }
1362 }
1363
1364
1365
1366
1367
1368 public ProgressListener getProgressListener() {
1369 return listener;
1370 }
1371
1372
1373
1374
1375
1376 public void setProgressListener(ProgressListener pListener) {
1377 listener = pListener;
1378 }
1379 }