/
MultipartParser.java
630 lines (524 loc) · 16.9 KB
/
MultipartParser.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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 org.springframework.http.codec.multipart;
import java.nio.charset.Charset;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.util.context.Context;
import org.springframework.core.codec.DecodingException;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferLimitException;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
/**
* Subscribes to a buffer stream and produces a flux of {@link Token} instances.
*
* @author Arjen Poutsma
* @since 5.3
*/
final class MultipartParser extends BaseSubscriber<DataBuffer> {
private static final byte CR = '\r';
private static final byte LF = '\n';
private static final byte[] CR_LF = {CR, LF};
private static final byte HYPHEN = '-';
private static final byte[] TWO_HYPHENS = {HYPHEN, HYPHEN};
private static final String HEADER_ENTRY_SEPARATOR = "\\r\\n";
private static final Log logger = LogFactory.getLog(MultipartParser.class);
private final AtomicReference<State> state;
private final FluxSink<Token> sink;
private final byte[] boundary;
private final int maxHeadersSize;
private final AtomicBoolean requestOutstanding = new AtomicBoolean();
private final Charset headersCharset;
private MultipartParser(FluxSink<Token> sink, byte[] boundary, int maxHeadersSize, Charset headersCharset) {
this.sink = sink;
this.boundary = boundary;
this.maxHeadersSize = maxHeadersSize;
this.headersCharset = headersCharset;
this.state = new AtomicReference<>(new PreambleState());
}
/**
* Parses the given stream of {@link DataBuffer} objects into a stream of {@link Token} objects.
* @param buffers the input buffers
* @param boundary the multipart boundary, as found in the {@code Content-Type} header
* @param maxHeadersSize the maximum buffered header size
* @param headersCharset the charset to use for decoding headers
* @return a stream of parsed tokens
*/
public static Flux<Token> parse(Flux<DataBuffer> buffers, byte[] boundary, int maxHeadersSize,
Charset headersCharset) {
return Flux.create(sink -> {
MultipartParser parser = new MultipartParser(sink, boundary, maxHeadersSize, headersCharset);
sink.onCancel(parser::onSinkCancel);
sink.onRequest(n -> parser.requestBuffer());
buffers.subscribe(parser);
});
}
@Override
public Context currentContext() {
return Context.of(this.sink.contextView());
}
@Override
protected void hookOnSubscribe(Subscription subscription) {
requestBuffer();
}
@Override
protected void hookOnNext(DataBuffer value) {
this.requestOutstanding.set(false);
this.state.get().onNext(value);
}
@Override
protected void hookOnComplete() {
this.state.get().onComplete();
}
@Override
protected void hookOnError(Throwable throwable) {
State oldState = this.state.getAndSet(DisposedState.INSTANCE);
oldState.dispose();
this.sink.error(throwable);
}
private void onSinkCancel() {
State oldState = this.state.getAndSet(DisposedState.INSTANCE);
oldState.dispose();
cancel();
}
boolean changeState(State oldState, State newState, @Nullable DataBuffer remainder) {
if (this.state.compareAndSet(oldState, newState)) {
if (logger.isTraceEnabled()) {
logger.trace("Changed state: " + oldState + " -> " + newState);
}
oldState.dispose();
if (remainder != null) {
if (remainder.readableByteCount() > 0) {
newState.onNext(remainder);
}
else {
DataBufferUtils.release(remainder);
requestBuffer();
}
}
return true;
}
else {
DataBufferUtils.release(remainder);
return false;
}
}
void emitHeaders(HttpHeaders headers) {
if (logger.isTraceEnabled()) {
logger.trace("Emitting headers: " + headers);
}
this.sink.next(new HeadersToken(headers));
}
void emitBody(DataBuffer buffer) {
if (logger.isTraceEnabled()) {
logger.trace("Emitting body: " + buffer);
}
this.sink.next(new BodyToken(buffer));
}
void emitError(Throwable t) {
cancel();
this.sink.error(t);
}
void emitComplete() {
cancel();
this.sink.complete();
}
private void requestBuffer() {
if (upstream() != null &&
!this.sink.isCancelled() &&
this.sink.requestedFromDownstream() > 0 &&
this.requestOutstanding.compareAndSet(false, true)) {
request(1);
}
}
/**
* Represents the output of {@link #parse(Flux, byte[], int, Charset)}.
*/
public abstract static class Token {
public abstract HttpHeaders headers();
public abstract DataBuffer buffer();
}
/**
* Represents a token that contains {@link HttpHeaders}.
*/
public final static class HeadersToken extends Token {
private final HttpHeaders headers;
public HeadersToken(HttpHeaders headers) {
this.headers = headers;
}
@Override
public HttpHeaders headers() {
return this.headers;
}
@Override
public DataBuffer buffer() {
throw new IllegalStateException();
}
}
/**
* Represents a token that contains {@link DataBuffer}.
*/
public final static class BodyToken extends Token {
private final DataBuffer buffer;
public BodyToken(DataBuffer buffer) {
this.buffer = buffer;
}
@Override
public HttpHeaders headers() {
throw new IllegalStateException();
}
@Override
public DataBuffer buffer() {
return this.buffer;
}
}
/**
* Represents the internal state of the {@link MultipartParser}.
* The flow for well-formed multipart messages is shown below:
* <p><pre>
* PREAMBLE
* |
* v
* +-->HEADERS--->DISPOSED
* | |
* | v
* +----BODY
* </pre>
* For malformed messages the flow ends in DISPOSED, and also when the
* sink is {@linkplain #onSinkCancel() cancelled}.
*/
private interface State {
void onNext(DataBuffer buf);
void onComplete();
default void dispose() {
}
}
/**
* The initial state of the parser. Looks for the first boundary of the
* multipart message. Note that the first boundary is not necessarily
* prefixed with {@code CR LF}; only the prefix {@code --} is required.
*/
private final class PreambleState implements State {
private final DataBufferUtils.Matcher firstBoundary;
public PreambleState() {
this.firstBoundary = DataBufferUtils.matcher(
MultipartUtils.concat(TWO_HYPHENS, MultipartParser.this.boundary));
}
/**
* Looks for the first boundary in the given buffer. If found, changes
* state to {@link HeadersState}, and passes on the remainder of the
* buffer.
*/
@Override
public void onNext(DataBuffer buf) {
int endIdx = this.firstBoundary.match(buf);
if (endIdx != -1) {
if (logger.isTraceEnabled()) {
logger.trace("First boundary found @" + endIdx + " in " + buf);
}
DataBuffer headersBuf = MultipartUtils.sliceFrom(buf, endIdx);
DataBufferUtils.release(buf);
changeState(this, new HeadersState(), headersBuf);
}
else {
DataBufferUtils.release(buf);
requestBuffer();
}
}
@Override
public void onComplete() {
if (changeState(this, DisposedState.INSTANCE, null)) {
emitError(new DecodingException("Could not find first boundary"));
}
}
@Override
public String toString() {
return "PREAMBLE";
}
}
/**
* The state of the parser dealing with part headers. Parses header
* buffers into a {@link HttpHeaders} instance, making sure that
* the amount does not exceed {@link #maxHeadersSize}.
*/
private final class HeadersState implements State {
private final DataBufferUtils.Matcher endHeaders = DataBufferUtils.matcher(MultipartUtils.concat(CR_LF, CR_LF));
private final AtomicInteger byteCount = new AtomicInteger();
private final List<DataBuffer> buffers = new ArrayList<>();
/**
* First checks whether the multipart boundary leading to this state
* was the final boundary. Then looks for the header-body boundary
* ({@code CR LF CR LF}) in the given buffer. If found, checks whether
* the size of all header buffers does not exceed {@link #maxHeadersSize},
* converts all buffers collected so far into a {@link HttpHeaders} object
* and changes to {@link BodyState}, passing the remainder of the
* buffer. If the boundary is not found, the buffer is collected if
* its size does not exceed {@link #maxHeadersSize}.
*/
@Override
public void onNext(DataBuffer buf) {
if (isLastBoundary(buf)) {
if (logger.isTraceEnabled()) {
logger.trace("Last boundary found in " + buf);
}
if (changeState(this, DisposedState.INSTANCE, buf)) {
emitComplete();
}
return;
}
int endIdx = this.endHeaders.match(buf);
if (endIdx != -1) {
if (logger.isTraceEnabled()) {
logger.trace("End of headers found @" + endIdx + " in " + buf);
}
long count = this.byteCount.addAndGet(endIdx);
if (belowMaxHeaderSize(count)) {
DataBuffer headerBuf = MultipartUtils.sliceTo(buf, endIdx);
this.buffers.add(headerBuf);
DataBuffer bodyBuf = MultipartUtils.sliceFrom(buf, endIdx);
DataBufferUtils.release(buf);
emitHeaders(parseHeaders());
changeState(this, new BodyState(), bodyBuf);
}
}
else {
long count = this.byteCount.addAndGet(buf.readableByteCount());
if (belowMaxHeaderSize(count)) {
this.buffers.add(buf);
requestBuffer();
}
}
}
/**
* If the given buffer is the first buffer, check whether it starts with {@code --}.
* If it is the second buffer, check whether it makes up {@code --} together with the first buffer.
*/
private boolean isLastBoundary(DataBuffer buf) {
return (this.buffers.isEmpty() &&
buf.readableByteCount() >= 2 &&
buf.getByte(0) == HYPHEN && buf.getByte(1) == HYPHEN)
||
(this.buffers.size() == 1 &&
this.buffers.get(0).readableByteCount() == 1 &&
this.buffers.get(0).getByte(0) == HYPHEN &&
buf.readableByteCount() >= 1 &&
buf.getByte(0) == HYPHEN);
}
/**
* Checks whether the given {@code count} is below or equal to {@link #maxHeadersSize}
* and emits a {@link DataBufferLimitException} if not.
*/
private boolean belowMaxHeaderSize(long count) {
if (count <= MultipartParser.this.maxHeadersSize) {
return true;
}
else {
emitError(new DataBufferLimitException("Part headers exceeded the memory usage limit of " +
MultipartParser.this.maxHeadersSize + " bytes"));
return false;
}
}
/**
* Parses the list of buffers into a {@link HttpHeaders} instance.
* Converts the joined buffers into a string using ISO=8859-1, and parses
* that string into key and values.
*/
private HttpHeaders parseHeaders() {
if (this.buffers.isEmpty()) {
return HttpHeaders.EMPTY;
}
DataBuffer joined = this.buffers.get(0).factory().join(this.buffers);
this.buffers.clear();
String string = joined.toString(MultipartParser.this.headersCharset);
DataBufferUtils.release(joined);
String[] lines = string.split(HEADER_ENTRY_SEPARATOR);
HttpHeaders result = new HttpHeaders();
for (String line : lines) {
int idx = line.indexOf(':');
if (idx != -1) {
String name = line.substring(0, idx);
String value = line.substring(idx + 1);
while (value.startsWith(" ")) {
value = value.substring(1);
}
result.add(name, value);
}
}
return result;
}
@Override
public void onComplete() {
if (changeState(this, DisposedState.INSTANCE, null)) {
emitError(new DecodingException("Could not find end of headers"));
}
}
@Override
public void dispose() {
this.buffers.forEach(DataBufferUtils::release);
}
@Override
public String toString() {
return "HEADERS";
}
}
/**
* The state of the parser dealing with multipart bodies. Relays
* data buffers as {@link BodyToken} until the boundary is found (or
* rather: {@code CR LF - - boundary}.
*/
private final class BodyState implements State {
private final DataBufferUtils.Matcher boundary;
private final int boundaryLength;
private final Deque<DataBuffer> queue = new ConcurrentLinkedDeque<>();
public BodyState() {
byte[] delimiter = MultipartUtils.concat(CR_LF, TWO_HYPHENS, MultipartParser.this.boundary);
this.boundary = DataBufferUtils.matcher(delimiter);
this.boundaryLength = delimiter.length;
}
/**
* Checks whether the (end of the) needle {@code CR LF - - boundary}
* can be found in {@code buffer}. If found, the needle can overflow into the
* previous buffer, so we calculate the length and slice the current
* and previous buffers accordingly. We then change to {@link HeadersState}
* and pass on the remainder of {@code buffer}. If the needle is not found, we
* make {@code buffer} the previous buffer.
*/
@Override
public void onNext(DataBuffer buffer) {
int endIdx = this.boundary.match(buffer);
if (endIdx != -1) {
if (logger.isTraceEnabled()) {
logger.trace("Boundary found @" + endIdx + " in " + buffer);
}
int len = endIdx - buffer.readPosition() - this.boundaryLength + 1;
if (len > 0) {
// whole boundary in buffer.
// slice off the body part, and flush
DataBuffer body = buffer.retainedSlice(buffer.readPosition(), len);
enqueue(body);
flush();
}
else if (len < 0) {
// boundary spans multiple buffers, and we've just found the end
// iterate over buffers in reverse order
DataBuffer prev;
while ((prev = this.queue.pollLast()) != null) {
int prevLen = prev.readableByteCount() + len;
if (prevLen > 0) {
// slice body part of previous buffer, and flush it
DataBuffer body = prev.retainedSlice(prev.readPosition(), prevLen);
DataBufferUtils.release(prev);
enqueue(body);
flush();
break;
}
else {
// previous buffer only contains boundary bytes
DataBufferUtils.release(prev);
len += prev.readableByteCount();
}
}
}
else /* if (len == 0) */ {
// buffer starts with complete delimiter, flush out the previous buffers
flush();
}
DataBuffer remainder = MultipartUtils.sliceFrom(buffer, endIdx);
DataBufferUtils.release(buffer);
changeState(this, new HeadersState(), remainder);
}
else {
enqueue(buffer);
requestBuffer();
}
}
/**
* Store the given buffer. Emit buffers that cannot contain boundary bytes,
* by iterating over the queue in reverse order, and summing buffer sizes.
* The first buffer that passes the boundary length and subsequent buffers
* are emitted (in the correct, non-reverse order).
*/
private void enqueue(DataBuffer buf) {
this.queue.add(buf);
int len = 0;
Deque<DataBuffer> emit = new ArrayDeque<>();
for (Iterator<DataBuffer> iterator = this.queue.descendingIterator(); iterator.hasNext(); ) {
DataBuffer previous = iterator.next();
if (len > this.boundaryLength) {
// addFirst to negate iterating in reverse order
emit.addFirst(previous);
iterator.remove();
}
len += previous.readableByteCount();
}
emit.forEach(MultipartParser.this::emitBody);
}
private void flush() {
this.queue.forEach(MultipartParser.this::emitBody);
this.queue.clear();
}
@Override
public void onComplete() {
if (changeState(this, DisposedState.INSTANCE, null)) {
emitError(new DecodingException("Could not find end of body"));
}
}
@Override
public void dispose() {
this.queue.forEach(DataBufferUtils::release);
this.queue.clear();
}
@Override
public String toString() {
return "BODY";
}
}
/**
* The state of the parser when finished, either due to seeing the final
* boundary or to a malformed message. Releases all incoming buffers.
*/
private static final class DisposedState implements State {
public static final DisposedState INSTANCE = new DisposedState();
private DisposedState() {
}
@Override
public void onNext(DataBuffer buf) {
DataBufferUtils.release(buf);
}
@Override
public void onComplete() {
}
@Override
public String toString() {
return "DISPOSED";
}
}
}