/
PartGenerator.java
819 lines (668 loc) · 21.1 KB
/
PartGenerator.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
/*
* 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.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
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.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
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.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.FastByteArrayOutputStream;
/**
* Subscribes to a token stream (i.e. the result of
* {@link MultipartParser#parse(Flux, byte[], int, Charset)}, and produces a flux of {@link Part} objects.
*
* @author Arjen Poutsma
* @since 5.3
*/
final class PartGenerator extends BaseSubscriber<MultipartParser.Token> {
private static final Log logger = LogFactory.getLog(PartGenerator.class);
private final AtomicReference<State> state = new AtomicReference<>(new InitialState());
private final AtomicInteger partCount = new AtomicInteger();
private final AtomicBoolean requestOutstanding = new AtomicBoolean();
private final FluxSink<Part> sink;
private final int maxParts;
private final boolean streaming;
private final int maxInMemorySize;
private final long maxDiskUsagePerPart;
private final Mono<Path> fileStorageDirectory;
private final Scheduler blockingOperationScheduler;
private PartGenerator(FluxSink<Part> sink, int maxParts, int maxInMemorySize, long maxDiskUsagePerPart,
boolean streaming, Mono<Path> fileStorageDirectory, Scheduler blockingOperationScheduler) {
this.sink = sink;
this.maxParts = maxParts;
this.maxInMemorySize = maxInMemorySize;
this.maxDiskUsagePerPart = maxDiskUsagePerPart;
this.streaming = streaming;
this.fileStorageDirectory = fileStorageDirectory;
this.blockingOperationScheduler = blockingOperationScheduler;
}
/**
* Creates parts from a given stream of tokens.
*/
public static Flux<Part> createParts(Flux<MultipartParser.Token> tokens, int maxParts, int maxInMemorySize,
long maxDiskUsagePerPart, boolean streaming, Mono<Path> fileStorageDirectory,
Scheduler blockingOperationScheduler) {
return Flux.create(sink -> {
PartGenerator generator = new PartGenerator(sink, maxParts, maxInMemorySize, maxDiskUsagePerPart, streaming,
fileStorageDirectory, blockingOperationScheduler);
sink.onCancel(generator::onSinkCancel);
sink.onRequest(l -> generator.requestToken());
tokens.subscribe(generator);
});
}
@Override
public Context currentContext() {
return Context.of(this.sink.contextView());
}
@Override
protected void hookOnSubscribe(Subscription subscription) {
requestToken();
}
@Override
protected void hookOnNext(MultipartParser.Token token) {
this.requestOutstanding.set(false);
State state = this.state.get();
if (token instanceof MultipartParser.HeadersToken) {
// finish previous part
state.partComplete(false);
if (tooManyParts()) {
return;
}
newPart(state, token.headers());
}
else {
state.body(token.buffer());
}
}
private void newPart(State currentState, HttpHeaders headers) {
if (isFormField(headers)) {
changeStateInternal(new FormFieldState(headers));
requestToken();
}
else if (!this.streaming) {
changeStateInternal(new InMemoryState(headers));
requestToken();
}
else {
Flux<DataBuffer> streamingContent = Flux.create(contentSink -> {
State newState = new StreamingState(contentSink);
if (changeState(currentState, newState)) {
contentSink.onRequest(l -> requestToken());
requestToken();
}
});
emitPart(DefaultParts.part(headers, streamingContent));
}
}
@Override
protected void hookOnComplete() {
this.state.get().partComplete(true);
}
@Override
protected void hookOnError(Throwable throwable) {
this.state.get().error(throwable);
changeStateInternal(DisposedState.INSTANCE);
this.sink.error(throwable);
}
private void onSinkCancel() {
changeStateInternal(DisposedState.INSTANCE);
cancel();
}
boolean changeState(State oldState, State newState) {
if (this.state.compareAndSet(oldState, newState)) {
if (logger.isTraceEnabled()) {
logger.trace("Changed state: " + oldState + " -> " + newState);
}
oldState.dispose();
return true;
}
else {
logger.warn("Could not switch from " + oldState +
" to " + newState + "; current state:"
+ this.state.get());
return false;
}
}
private void changeStateInternal(State newState) {
if (this.state.get() == DisposedState.INSTANCE) {
return;
}
State oldState = this.state.getAndSet(newState);
if (logger.isTraceEnabled()) {
logger.trace("Changed state: " + oldState + " -> " + newState);
}
oldState.dispose();
}
void emitPart(Part part) {
if (logger.isTraceEnabled()) {
logger.trace("Emitting: " + part);
}
this.sink.next(part);
}
void emitComplete() {
this.sink.complete();
}
void emitError(Throwable t) {
cancel();
this.sink.error(t);
}
void requestToken() {
if (upstream() != null &&
!this.sink.isCancelled() &&
this.sink.requestedFromDownstream() > 0 &&
this.requestOutstanding.compareAndSet(false, true)) {
request(1);
}
}
private boolean tooManyParts() {
int count = this.partCount.incrementAndGet();
if (this.maxParts > 0 && count > this.maxParts) {
emitError(new DecodingException("Too many parts (" + count + "/" + this.maxParts + " allowed)"));
return true;
}
else {
return false;
}
}
private static boolean isFormField(HttpHeaders headers) {
MediaType contentType = headers.getContentType();
return (contentType == null || MediaType.TEXT_PLAIN.equalsTypeAndSubtype(contentType))
&& headers.getContentDisposition().getFilename() == null;
}
/**
* Represents the internal state of the {@link PartGenerator} for
* creating a single {@link Part}.
* {@link State} instances are stateful, and created when a new
* {@link MultipartParser.HeadersToken} is accepted (see
* {@link #newPart(State, HttpHeaders)}.
* The following rules determine which state the creator will have:
* <ol>
* <li>If the part is a {@linkplain #isFormField(HttpHeaders) form field},
* the creator will be in the {@link FormFieldState}.</li>
* <li>If {@linkplain #streaming} is enabled, the creator will be in the
* {@link StreamingState}.</li>
* <li>Otherwise, the creator will initially be in the
* {@link InMemoryState}, but will switch over to {@link CreateFileState}
* when the part byte count exceeds {@link #maxInMemorySize},
* then to {@link WritingFileState} (to write the memory contents),
* and finally {@link IdleFileState}, which switches back to
* {@link WritingFileState} when more body data comes in.</li>
* </ol>
*/
private interface State {
/**
* Invoked when a {@link MultipartParser.BodyToken} is received.
*/
void body(DataBuffer dataBuffer);
/**
* Invoked when all tokens for the part have been received.
* @param finalPart {@code true} if this was the last part (and
* {@link #emitComplete()} should be called; {@code false} otherwise
*/
void partComplete(boolean finalPart);
/**
* Invoked when an error has been received.
*/
default void error(Throwable throwable) {
}
/**
* Cleans up any state.
*/
default void dispose() {
}
}
/**
* The initial state of the creator. Throws an exception for {@link #body(DataBuffer)}.
*/
private final class InitialState implements State {
private InitialState() {
}
@Override
public void body(DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
emitError(new IllegalStateException("Body token not expected"));
}
@Override
public void partComplete(boolean finalPart) {
if (finalPart) {
emitComplete();
}
}
@Override
public String toString() {
return "INITIAL";
}
}
/**
* The creator state when a {@linkplain #isFormField(HttpHeaders) form field} is received.
* Stores all body buffers in memory (up until {@link #maxInMemorySize}).
*/
private final class FormFieldState implements State {
private final FastByteArrayOutputStream value = new FastByteArrayOutputStream();
private final HttpHeaders headers;
public FormFieldState(HttpHeaders headers) {
this.headers = headers;
}
@Override
public void body(DataBuffer dataBuffer) {
int size = this.value.size() + dataBuffer.readableByteCount();
if (PartGenerator.this.maxInMemorySize == -1 ||
size < PartGenerator.this.maxInMemorySize) {
store(dataBuffer);
requestToken();
}
else {
DataBufferUtils.release(dataBuffer);
emitError(new DataBufferLimitException("Form field value exceeded the memory usage limit of " +
PartGenerator.this.maxInMemorySize + " bytes"));
}
}
private void store(DataBuffer dataBuffer) {
try {
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
this.value.write(bytes);
}
catch (IOException ex) {
emitError(ex);
}
finally {
DataBufferUtils.release(dataBuffer);
}
}
@Override
public void partComplete(boolean finalPart) {
byte[] bytes = this.value.toByteArrayUnsafe();
String value = new String(bytes, MultipartUtils.charset(this.headers));
emitPart(DefaultParts.formFieldPart(this.headers, value));
if (finalPart) {
emitComplete();
}
}
@Override
public String toString() {
return "FORM-FIELD";
}
}
/**
* The creator state when {@link #streaming} is {@code true} (and not
* handling a form field). Relays all received buffers to a sink.
*/
private final class StreamingState implements State {
private final FluxSink<DataBuffer> bodySink;
public StreamingState(FluxSink<DataBuffer> bodySink) {
this.bodySink = bodySink;
}
@Override
public void body(DataBuffer dataBuffer) {
if (!this.bodySink.isCancelled()) {
this.bodySink.next(dataBuffer);
if (this.bodySink.requestedFromDownstream() > 0) {
requestToken();
}
}
else {
DataBufferUtils.release(dataBuffer);
// even though the body sink is canceled, the (outer) part sink
// might not be, so request another token
requestToken();
}
}
@Override
public void partComplete(boolean finalPart) {
if (!this.bodySink.isCancelled()) {
this.bodySink.complete();
}
if (finalPart) {
emitComplete();
}
}
@Override
public void error(Throwable throwable) {
if (!this.bodySink.isCancelled()) {
this.bodySink.error(throwable);
}
}
@Override
public String toString() {
return "STREAMING";
}
}
/**
* The creator state when {@link #streaming} is {@code false} (and not
* handling a form field). Stores all received buffers in a queue.
* If the byte count exceeds {@link #maxInMemorySize}, the creator state
* is changed to {@link CreateFileState}, and eventually to
* {@link CreateFileState}.
*/
private final class InMemoryState implements State {
private final AtomicLong byteCount = new AtomicLong();
private final Queue<DataBuffer> content = new ConcurrentLinkedQueue<>();
private final HttpHeaders headers;
private volatile boolean releaseOnDispose = true;
public InMemoryState(HttpHeaders headers) {
this.headers = headers;
}
@Override
public void body(DataBuffer dataBuffer) {
long prevCount = this.byteCount.get();
long count = this.byteCount.addAndGet(dataBuffer.readableByteCount());
if (PartGenerator.this.maxInMemorySize == -1 ||
count <= PartGenerator.this.maxInMemorySize) {
storeBuffer(dataBuffer);
}
else if (prevCount <= PartGenerator.this.maxInMemorySize) {
switchToFile(dataBuffer, count);
}
else {
DataBufferUtils.release(dataBuffer);
emitError(new IllegalStateException("Body token not expected"));
}
}
private void storeBuffer(DataBuffer dataBuffer) {
this.content.add(dataBuffer);
requestToken();
}
private void switchToFile(DataBuffer current, long byteCount) {
List<DataBuffer> content = new ArrayList<>(this.content);
content.add(current);
this.releaseOnDispose = false;
CreateFileState newState = new CreateFileState(this.headers, content, byteCount);
if (changeState(this, newState)) {
newState.createFile();
}
else {
content.forEach(DataBufferUtils::release);
}
}
@Override
public void partComplete(boolean finalPart) {
emitMemoryPart();
if (finalPart) {
emitComplete();
}
}
private void emitMemoryPart() {
byte[] bytes = new byte[(int) this.byteCount.get()];
int idx = 0;
for (DataBuffer buffer : this.content) {
int len = buffer.readableByteCount();
buffer.read(bytes, idx, len);
idx += len;
DataBufferUtils.release(buffer);
}
this.content.clear();
Flux<DataBuffer> content = Flux.just(DefaultDataBufferFactory.sharedInstance.wrap(bytes));
emitPart(DefaultParts.part(this.headers, content));
}
@Override
public void dispose() {
if (this.releaseOnDispose) {
this.content.forEach(DataBufferUtils::release);
}
}
@Override
public String toString() {
return "IN-MEMORY";
}
}
/**
* The creator state when waiting for a temporary file to be created.
* {@link InMemoryState} initially switches to this state when the byte
* count exceeds {@link #maxInMemorySize}, and then calls
* {@link #createFile()} to switch to {@link WritingFileState}.
*/
private final class CreateFileState implements State {
private final HttpHeaders headers;
private final Collection<DataBuffer> content;
private final long byteCount;
private volatile boolean completed;
private volatile boolean finalPart;
private volatile boolean releaseOnDispose = true;
public CreateFileState(HttpHeaders headers, Collection<DataBuffer> content, long byteCount) {
this.headers = headers;
this.content = content;
this.byteCount = byteCount;
}
@Override
public void body(DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
emitError(new IllegalStateException("Body token not expected"));
}
@Override
public void partComplete(boolean finalPart) {
this.completed = true;
this.finalPart = finalPart;
}
public void createFile() {
PartGenerator.this.fileStorageDirectory
.map(this::createFileState)
.subscribeOn(PartGenerator.this.blockingOperationScheduler)
.subscribe(this::fileCreated, PartGenerator.this::emitError);
}
private WritingFileState createFileState(Path directory) {
try {
Path tempFile = Files.createTempFile(directory, null, ".multipart");
if (logger.isTraceEnabled()) {
logger.trace("Storing multipart data in file " + tempFile);
}
WritableByteChannel channel = Files.newByteChannel(tempFile, StandardOpenOption.WRITE);
return new WritingFileState(this, tempFile, channel);
}
catch (IOException ex) {
throw new UncheckedIOException("Could not create temp file in " + directory, ex);
}
}
private void fileCreated(WritingFileState newState) {
this.releaseOnDispose = false;
if (changeState(this, newState)) {
newState.writeBuffers(this.content);
if (this.completed) {
newState.partComplete(this.finalPart);
}
}
else {
MultipartUtils.closeChannel(newState.channel);
this.content.forEach(DataBufferUtils::release);
}
}
@Override
public void dispose() {
if (this.releaseOnDispose) {
this.content.forEach(DataBufferUtils::release);
}
}
@Override
public String toString() {
return "CREATE-FILE";
}
}
private final class IdleFileState implements State {
private final HttpHeaders headers;
private final Path file;
private final WritableByteChannel channel;
private final AtomicLong byteCount;
private volatile boolean closeOnDispose = true;
public IdleFileState(WritingFileState state) {
this.headers = state.headers;
this.file = state.file;
this.channel = state.channel;
this.byteCount = state.byteCount;
}
@Override
public void body(DataBuffer dataBuffer) {
long count = this.byteCount.addAndGet(dataBuffer.readableByteCount());
if (PartGenerator.this.maxDiskUsagePerPart == -1 || count <= PartGenerator.this.maxDiskUsagePerPart) {
this.closeOnDispose = false;
WritingFileState newState = new WritingFileState(this);
if (changeState(this, newState)) {
newState.writeBuffer(dataBuffer);
}
else {
MultipartUtils.closeChannel(this.channel);
DataBufferUtils.release(dataBuffer);
}
}
else {
DataBufferUtils.release(dataBuffer);
emitError(new DataBufferLimitException(
"Part exceeded the disk usage limit of " + PartGenerator.this.maxDiskUsagePerPart +
" bytes"));
}
}
@Override
public void partComplete(boolean finalPart) {
MultipartUtils.closeChannel(this.channel);
emitPart(DefaultParts.part(this.headers, this.file, PartGenerator.this.blockingOperationScheduler));
if (finalPart) {
emitComplete();
}
}
@Override
public void dispose() {
if (this.closeOnDispose) {
MultipartUtils.closeChannel(this.channel);
}
}
@Override
public String toString() {
return "IDLE-FILE";
}
}
private final class WritingFileState implements State {
private final HttpHeaders headers;
private final Path file;
private final WritableByteChannel channel;
private final AtomicLong byteCount;
private volatile boolean completed;
private volatile boolean finalPart;
public WritingFileState(CreateFileState state, Path file, WritableByteChannel channel) {
this.headers = state.headers;
this.file = file;
this.channel = channel;
this.byteCount = new AtomicLong(state.byteCount);
}
public WritingFileState(IdleFileState state) {
this.headers = state.headers;
this.file = state.file;
this.channel = state.channel;
this.byteCount = state.byteCount;
}
@Override
public void body(DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
emitError(new IllegalStateException("Body token not expected"));
}
@Override
public void partComplete(boolean finalPart) {
this.completed = true;
this.finalPart = finalPart;
}
public void writeBuffer(DataBuffer dataBuffer) {
Mono.just(dataBuffer)
.flatMap(this::writeInternal)
.subscribeOn(PartGenerator.this.blockingOperationScheduler)
.subscribe(null,
PartGenerator.this::emitError,
this::writeComplete);
}
public void writeBuffers(Iterable<DataBuffer> dataBuffers) {
Flux.fromIterable(dataBuffers)
.concatMap(this::writeInternal)
.then()
.subscribeOn(PartGenerator.this.blockingOperationScheduler)
.subscribe(null,
PartGenerator.this::emitError,
this::writeComplete);
}
private void writeComplete() {
IdleFileState newState = new IdleFileState(this);
if (this.completed) {
newState.partComplete(this.finalPart);
}
else if (changeState(this, newState)) {
requestToken();
}
else {
MultipartUtils.closeChannel(this.channel);
}
}
@SuppressWarnings("BlockingMethodInNonBlockingContext")
private Mono<Void> writeInternal(DataBuffer dataBuffer) {
try {
ByteBuffer byteBuffer = dataBuffer.asByteBuffer();
while (byteBuffer.hasRemaining()) {
this.channel.write(byteBuffer);
}
return Mono.empty();
}
catch (IOException ex) {
return Mono.error(ex);
}
finally {
DataBufferUtils.release(dataBuffer);
}
}
@Override
public String toString() {
return "WRITE-FILE";
}
}
private static final class DisposedState implements State {
public static final DisposedState INSTANCE = new DisposedState();
private DisposedState() {
}
@Override
public void body(DataBuffer dataBuffer) {
DataBufferUtils.release(dataBuffer);
}
@Override
public void partComplete(boolean finalPart) {
}
@Override
public String toString() {
return "DISPOSED";
}
}
}