forked from undertow-io/undertow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MultiPartParserDefinition.java
494 lines (434 loc) · 20.4 KB
/
MultiPartParserDefinition.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.server.handlers.form;
import io.undertow.UndertowLogger;
import io.undertow.UndertowMessages;
import io.undertow.UndertowOptions;
import io.undertow.server.ExchangeCompletionListener;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HeaderMap;
import io.undertow.util.Headers;
import io.undertow.util.MalformedMessageException;
import io.undertow.util.MultipartParser;
import io.undertow.util.SameThreadExecutor;
import io.undertow.util.StatusCodes;
import org.xnio.ChannelListener;
import org.xnio.IoUtils;
import io.undertow.connector.PooledByteBuffer;
import org.xnio.channels.StreamSourceChannel;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileAttribute;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executor;
/**
* @author Stuart Douglas
*/
public class MultiPartParserDefinition implements FormParserFactory.ParserDefinition<MultiPartParserDefinition> {
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
private Executor executor;
private Path tempFileLocation;
private String defaultEncoding = StandardCharsets.ISO_8859_1.displayName();
private long maxIndividualFileSize = -1;
private long fileSizeThreshold;
public MultiPartParserDefinition() {
tempFileLocation = Paths.get(System.getProperty("java.io.tmpdir"));
}
public MultiPartParserDefinition(final Path tempDir) {
tempFileLocation = tempDir;
}
@Override
public FormDataParser create(final HttpServerExchange exchange) {
String mimeType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
if (mimeType != null && mimeType.startsWith(MULTIPART_FORM_DATA)) {
String boundary = Headers.extractQuotedValueFromHeader(mimeType, "boundary");
if (boundary == null) {
UndertowLogger.REQUEST_LOGGER.debugf("Could not find boundary in multipart request with ContentType: %s, multipart data will not be available", mimeType);
return null;
}
final MultiPartUploadHandler parser = new MultiPartUploadHandler(exchange, boundary, maxIndividualFileSize, fileSizeThreshold, defaultEncoding);
exchange.addExchangeCompleteListener(new ExchangeCompletionListener() {
@Override
public void exchangeEvent(final HttpServerExchange exchange, final NextListener nextListener) {
IoUtils.safeClose(parser);
nextListener.proceed();
}
});
Long sizeLimit = exchange.getConnection().getUndertowOptions().get(UndertowOptions.MULTIPART_MAX_ENTITY_SIZE);
if(sizeLimit != null) {
exchange.setMaxEntitySize(sizeLimit);
}
UndertowLogger.REQUEST_LOGGER.tracef("Created multipart parser for %s", exchange);
return parser;
}
return null;
}
public Executor getExecutor() {
return executor;
}
public MultiPartParserDefinition setExecutor(final Executor executor) {
this.executor = executor;
return this;
}
public Path getTempFileLocation() {
return tempFileLocation;
}
public MultiPartParserDefinition setTempFileLocation(Path tempFileLocation) {
this.tempFileLocation = tempFileLocation;
return this;
}
public String getDefaultEncoding() {
return defaultEncoding;
}
public MultiPartParserDefinition setDefaultEncoding(final String defaultEncoding) {
this.defaultEncoding = defaultEncoding;
return this;
}
public long getMaxIndividualFileSize() {
return maxIndividualFileSize;
}
public void setMaxIndividualFileSize(final long maxIndividualFileSize) {
this.maxIndividualFileSize = maxIndividualFileSize;
}
public void setFileSizeThreshold(long fileSizeThreshold) {
this.fileSizeThreshold = fileSizeThreshold;
}
private final class MultiPartUploadHandler implements FormDataParser, MultipartParser.PartHandler {
private final HttpServerExchange exchange;
private final FormData data;
private final List<Path> createdFiles = new ArrayList<>();
private final long maxIndividualFileSize;
private final long fileSizeThreshold;
private String defaultEncoding;
private final ByteArrayOutputStream contentBytes = new ByteArrayOutputStream();
private String currentName;
private String fileName;
private Path file;
private FileChannel fileChannel;
private HeaderMap headers;
private HttpHandler handler;
private long currentFileSize;
private final MultipartParser.ParseState parser;
private MultiPartUploadHandler(final HttpServerExchange exchange, final String boundary, final long maxIndividualFileSize, final long fileSizeThreshold, final String defaultEncoding) {
this.exchange = exchange;
this.maxIndividualFileSize = maxIndividualFileSize;
this.defaultEncoding = defaultEncoding;
this.fileSizeThreshold = fileSizeThreshold;
this.data = new FormData(exchange.getConnection().getUndertowOptions().get(UndertowOptions.MAX_PARAMETERS, 1000));
String charset = defaultEncoding;
String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
if (contentType != null) {
String value = Headers.extractQuotedValueFromHeader(contentType, "charset");
if (value != null) {
charset = value;
}
}
this.parser = MultipartParser.beginParse(exchange.getConnection().getByteBufferPool(), this, boundary.getBytes(StandardCharsets.US_ASCII), charset);
}
@Override
public void parse(final HttpHandler handler) throws Exception {
if (exchange.getAttachment(FORM_DATA) != null) {
handler.handleRequest(exchange);
return;
}
this.handler = handler;
//we need to delegate to a thread pool
//as we parse with blocking operations
StreamSourceChannel requestChannel = exchange.getRequestChannel();
if (requestChannel == null) {
throw new IOException(UndertowMessages.MESSAGES.requestChannelAlreadyProvided());
}
if (executor == null) {
exchange.dispatch(new NonBlockingParseTask(exchange.getConnection().getWorker(), requestChannel));
} else {
exchange.dispatch(executor, new NonBlockingParseTask(executor, requestChannel));
}
}
@Override
public FormData parseBlocking() throws IOException {
final FormData existing = exchange.getAttachment(FORM_DATA);
if (existing != null) {
return existing;
}
InputStream inputStream = exchange.getInputStream();
if (inputStream == null) {
throw new IOException(UndertowMessages.MESSAGES.requestChannelAlreadyProvided());
}
try (PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().getArrayBackedPool().allocate()){
ByteBuffer buf = pooled.getBuffer();
while (true) {
buf.clear();
int c = inputStream.read(buf.array(), buf.arrayOffset(), buf.remaining());
if (c == -1) {
if (parser.isComplete()) {
break;
} else {
throw UndertowMessages.MESSAGES.connectionTerminatedReadingMultiPartData();
}
} else if (c != 0) {
buf.limit(c);
parser.parse(buf);
}
}
exchange.putAttachment(FORM_DATA, data);
} catch (MalformedMessageException e) {
throw new IOException(e);
}
return exchange.getAttachment(FORM_DATA);
}
@Override
public void beginPart(final HeaderMap headers) {
this.currentFileSize = 0;
this.headers = headers;
final String disposition = headers.getFirst(Headers.CONTENT_DISPOSITION);
if (disposition != null) {
if (disposition.startsWith("form-data")) {
currentName = Headers.extractQuotedValueFromHeader(disposition, "name");
fileName = Headers.extractQuotedValueFromHeaderWithEncoding(disposition, "filename");
if (fileName != null && fileSizeThreshold == 0) {
try {
if (tempFileLocation != null) {
//Files impl is buggy, hence zero len
final FileAttribute[] emptyFA = new FileAttribute[] {};
final LinkOption[] emptyLO = new LinkOption[] {};
final Path normalized = tempFileLocation.normalize();
if (!Files.exists(normalized)) {
final int pathElementsCount = normalized.getNameCount();
Path tmp = normalized;
LinkedList<Path> dirsToGuard = new LinkedList<>();
for(int i=0;i<pathElementsCount;i++) {
if(Files.exists(tmp, emptyLO)) {
if(!Files.isDirectory(tmp, emptyLO)) {
//First existing element in path is a file,
//this will cause java.nio.file.FileSystemException
throw UndertowMessages.MESSAGES.pathElementIsRegularFile(tmp);
}
break;
} else {
dirsToGuard.addFirst(tmp);
tmp = tmp.getParent();
}
}
try {
Files.createDirectories(normalized, emptyFA);
} finally {
for (Path p : dirsToGuard) {
try {
p.toFile().deleteOnExit();
} catch (Exception e) {
break;
}
}
}
} else if (!Files.isDirectory(normalized, emptyLO)) {
throw new IOException(UndertowMessages.MESSAGES.pathNotADirectory(normalized));
}
file = Files.createTempFile(normalized, "undertow", "upload");
} else {
file = Files.createTempFile("undertow", "upload");
}
createdFiles.add(file);
fileChannel = FileChannel.open(file, StandardOpenOption.READ, StandardOpenOption.WRITE);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
@Override
public void data(final ByteBuffer buffer) throws IOException {
this.currentFileSize += buffer.remaining();
if (this.maxIndividualFileSize > 0 && this.currentFileSize > this.maxIndividualFileSize) {
throw UndertowMessages.MESSAGES.maxFileSizeExceeded(this.maxIndividualFileSize);
}
if (file == null && fileName != null && fileSizeThreshold < this.currentFileSize) {
try {
if (tempFileLocation != null) {
file = Files.createTempFile(tempFileLocation, "undertow", "upload");
} else {
file = Files.createTempFile("undertow", "upload");
}
createdFiles.add(file);
FileOutputStream fileOutputStream = new FileOutputStream(file.toFile());
contentBytes.writeTo(fileOutputStream);
fileChannel = fileOutputStream.getChannel();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (file == null) {
while (buffer.hasRemaining()) {
contentBytes.write(buffer.get());
}
} else {
fileChannel.write(buffer);
}
}
@Override
public void endPart() {
if (file != null) {
data.add(currentName, file, fileName, headers);
file = null;
contentBytes.reset();
try {
fileChannel.close();
fileChannel = null;
} catch (IOException e) {
throw new RuntimeException(e);
}
} else if (fileName != null) {
data.add(currentName, Arrays.copyOf(contentBytes.toByteArray(), contentBytes.size()), fileName, headers);
contentBytes.reset();
} else {
try {
String charset = defaultEncoding;
String contentType = headers.getFirst(Headers.CONTENT_TYPE);
if (contentType != null) {
String cs = Headers.extractQuotedValueFromHeader(contentType, "charset");
if (cs != null) {
charset = cs;
}
}
data.add(currentName, new String(contentBytes.toByteArray(), charset), charset, headers);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
contentBytes.reset();
}
}
public List<Path> getCreatedFiles() {
return createdFiles;
}
@Override
public void close() throws IOException {
IoUtils.safeClose(fileChannel);
//we have to dispatch this, as it may result in file IO
final List<Path> files = new ArrayList<>(getCreatedFiles());
exchange.getConnection().getWorker().execute(new Runnable() {
@Override
public void run() {
for (final Path file : files) {
if (Files.exists(file)) {
try {
Files.delete(file);
} catch (NoSuchFileException e) { // ignore
} catch (IOException e) {
UndertowLogger.REQUEST_LOGGER.cannotRemoveUploadedFile(file);
}
}
}
}
});
}
@Override
public void setCharacterEncoding(final String encoding) {
this.defaultEncoding = encoding;
parser.setCharacterEncoding(encoding);
}
private final class NonBlockingParseTask implements Runnable {
private final Executor executor;
private final StreamSourceChannel requestChannel;
private NonBlockingParseTask(Executor executor, StreamSourceChannel requestChannel) {
this.executor = executor;
this.requestChannel = requestChannel;
}
@Override
public void run() {
try {
final FormData existing = exchange.getAttachment(FORM_DATA);
if (existing != null) {
exchange.dispatch(SameThreadExecutor.INSTANCE, handler);
return;
}
PooledByteBuffer pooled = exchange.getConnection().getByteBufferPool().allocate();
try {
while (true) {
int c = requestChannel.read(pooled.getBuffer());
if(c == 0) {
requestChannel.getReadSetter().set(new ChannelListener<StreamSourceChannel>() {
@Override
public void handleEvent(StreamSourceChannel channel) {
channel.suspendReads();
executor.execute(NonBlockingParseTask.this);
}
});
requestChannel.resumeReads();
return;
} else if (c == -1) {
if (parser.isComplete()) {
exchange.putAttachment(FORM_DATA, data);
exchange.dispatch(SameThreadExecutor.INSTANCE, handler);
} else {
UndertowLogger.REQUEST_IO_LOGGER.ioException(UndertowMessages.MESSAGES.connectionTerminatedReadingMultiPartData());
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
exchange.endExchange();
}
return;
} else {
pooled.getBuffer().flip();
parser.parse(pooled.getBuffer());
pooled.getBuffer().compact();
}
}
} catch (MalformedMessageException e) {
UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
exchange.endExchange();
} finally {
pooled.close();
}
} catch (Throwable e) {
UndertowLogger.REQUEST_IO_LOGGER.debug("Exception parsing data", e);
exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
exchange.endExchange();
}
}
}
}
public static class FileTooLargeException extends IOException {
public FileTooLargeException() {
super();
}
public FileTooLargeException(String message) {
super(message);
}
public FileTooLargeException(String message, Throwable cause) {
super(message, cause);
}
public FileTooLargeException(Throwable cause) {
super(cause);
}
}
}