Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/sun/net/www/http/ChunkedInputStream.java
41161 views
1
/*
2
* Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
package sun.net.www.http;
26
27
import java.io.*;
28
import java.util.concurrent.locks.ReentrantLock;
29
import sun.net.www.*;
30
import sun.nio.cs.US_ASCII;
31
32
/**
33
* A <code>ChunkedInputStream</code> provides a stream for reading a body of
34
* a http message that can be sent as a series of chunks, each with its own
35
* size indicator. Optionally the last chunk can be followed by trailers
36
* containing entity-header fields.
37
* <p>
38
* A <code>ChunkedInputStream</code> is also <code>Hurryable</code> so it
39
* can be hurried to the end of the stream if the bytes are available on
40
* the underlying stream.
41
*/
42
public class ChunkedInputStream extends InputStream implements Hurryable {
43
44
/**
45
* The underlying stream
46
*/
47
private InputStream in;
48
49
/**
50
* The <code>HttpClient</code> that should be notified when the chunked stream has
51
* completed.
52
*/
53
private HttpClient hc;
54
55
/**
56
* The <code>MessageHeader</code> that is populated with any optional trailer
57
* that appear after the last chunk.
58
*/
59
private MessageHeader responses;
60
61
/**
62
* The size, in bytes, of the chunk that is currently being read.
63
* This size is only valid if the current position in the underlying
64
* input stream is inside a chunk (ie: state == STATE_READING_CHUNK).
65
*/
66
private int chunkSize;
67
68
/**
69
* The number of bytes read from the underlying stream for the current
70
* chunk. This value is always in the range <code>0</code> through to
71
* <code>chunkSize</code>
72
*/
73
private int chunkRead;
74
75
/**
76
* The internal buffer array where chunk data is available for the
77
* application to read.
78
*/
79
private byte chunkData[] = new byte[4096];
80
81
/**
82
* The current position in the buffer. It contains the index
83
* of the next byte to read from <code>chunkData</code>
84
*/
85
private int chunkPos;
86
87
/**
88
* The index one greater than the index of the last valid byte in the
89
* buffer. This value is always in the range <code>0</code> through
90
* <code>chunkData.length</code>.
91
*/
92
private int chunkCount;
93
94
/**
95
* The internal buffer where bytes from the underlying stream can be
96
* read. It may contain bytes representing chunk-size, chunk-data, or
97
* trailer fields.
98
*/
99
private byte rawData[] = new byte[32];
100
101
/**
102
* The current position in the buffer. It contains the index
103
* of the next byte to read from <code>rawData</code>
104
*/
105
private int rawPos;
106
107
/**
108
* The index one greater than the index of the last valid byte in the
109
* buffer. This value is always in the range <code>0</code> through
110
* <code>rawData.length</code>.
111
*/
112
private int rawCount;
113
114
/**
115
* Indicates if an error was encountered when processing the chunked
116
* stream.
117
*/
118
private boolean error;
119
120
/**
121
* Indicates if the chunked stream has been closed using the
122
* <code>close</code> method.
123
*/
124
private boolean closed;
125
126
private final ReentrantLock readLock = new ReentrantLock();
127
128
/*
129
* Maximum chunk header size of 2KB + 2 bytes for CRLF
130
*/
131
private static final int MAX_CHUNK_HEADER_SIZE = 2050;
132
133
/**
134
* State to indicate that next field should be :-
135
* chunk-size [ chunk-extension ] CRLF
136
*/
137
static final int STATE_AWAITING_CHUNK_HEADER = 1;
138
139
/**
140
* State to indicate that we are currently reading the chunk-data.
141
*/
142
static final int STATE_READING_CHUNK = 2;
143
144
/**
145
* Indicates that a chunk has been completely read and the next
146
* fields to be examine should be CRLF
147
*/
148
static final int STATE_AWAITING_CHUNK_EOL = 3;
149
150
/**
151
* Indicates that all chunks have been read and the next field
152
* should be optional trailers or an indication that the chunked
153
* stream is complete.
154
*/
155
static final int STATE_AWAITING_TRAILERS = 4;
156
157
/**
158
* State to indicate that the chunked stream is complete and
159
* no further bytes should be read from the underlying stream.
160
*/
161
static final int STATE_DONE = 5;
162
163
/**
164
* Indicates the current state.
165
*/
166
private int state;
167
168
169
/**
170
* Check to make sure that this stream has not been closed.
171
*/
172
private void ensureOpen() throws IOException {
173
if (closed) {
174
throw new IOException("stream is closed");
175
}
176
}
177
178
179
/**
180
* Ensures there is <code>size</code> bytes available in
181
* <code>rawData</code>. This requires that we either
182
* shift the bytes in use to the begining of the buffer
183
* or allocate a large buffer with sufficient space available.
184
*/
185
private void ensureRawAvailable(int size) {
186
if (rawCount + size > rawData.length) {
187
int used = rawCount - rawPos;
188
if (used + size > rawData.length) {
189
byte tmp[] = new byte[used + size];
190
if (used > 0) {
191
System.arraycopy(rawData, rawPos, tmp, 0, used);
192
}
193
rawData = tmp;
194
} else {
195
if (used > 0) {
196
System.arraycopy(rawData, rawPos, rawData, 0, used);
197
}
198
}
199
rawCount = used;
200
rawPos = 0;
201
}
202
}
203
204
205
/**
206
* Close the underlying input stream by either returning it to the
207
* keep alive cache or closing the stream.
208
* <p>
209
* As a chunked stream is inheritly persistent (see HTTP 1.1 RFC) the
210
* underlying stream can be returned to the keep alive cache if the
211
* stream can be completely read without error.
212
*/
213
private void closeUnderlying() throws IOException {
214
if (in == null) {
215
return;
216
}
217
218
if (!error && state == STATE_DONE) {
219
hc.finished();
220
} else {
221
if (!hurry()) {
222
hc.closeServer();
223
}
224
}
225
226
in = null;
227
}
228
229
/**
230
* Attempt to read the remainder of a chunk directly into the
231
* caller's buffer.
232
* <p>
233
* Return the number of bytes read.
234
*/
235
private int fastRead(byte[] b, int off, int len) throws IOException {
236
237
// assert state == STATE_READING_CHUNKS;
238
239
int remaining = chunkSize - chunkRead;
240
int cnt = (remaining < len) ? remaining : len;
241
if (cnt > 0) {
242
int nread;
243
try {
244
nread = in.read(b, off, cnt);
245
} catch (IOException e) {
246
error = true;
247
throw e;
248
}
249
if (nread > 0) {
250
chunkRead += nread;
251
if (chunkRead >= chunkSize) {
252
state = STATE_AWAITING_CHUNK_EOL;
253
}
254
return nread;
255
}
256
error = true;
257
throw new IOException("Premature EOF");
258
} else {
259
return 0;
260
}
261
}
262
263
/**
264
* Process any outstanding bytes that have already been read into
265
* <code>rawData</code>.
266
* <p>
267
* The parsing of the chunked stream is performed as a state machine with
268
* <code>state</code> representing the current state of the processing.
269
* <p>
270
* Returns when either all the outstanding bytes in rawData have been
271
* processed or there is insufficient bytes available to continue
272
* processing. When the latter occurs <code>rawPos</code> will not have
273
* been updated and thus the processing can be restarted once further
274
* bytes have been read into <code>rawData</code>.
275
*/
276
private void processRaw() throws IOException {
277
int pos;
278
int i;
279
280
while (state != STATE_DONE) {
281
282
switch (state) {
283
284
/**
285
* We are awaiting a line with a chunk header
286
*/
287
case STATE_AWAITING_CHUNK_HEADER:
288
/*
289
* Find \n to indicate end of chunk header. If not found when there is
290
* insufficient bytes in the raw buffer to parse a chunk header.
291
*/
292
pos = rawPos;
293
while (pos < rawCount) {
294
if (rawData[pos] == '\n') {
295
break;
296
}
297
pos++;
298
if ((pos - rawPos) >= MAX_CHUNK_HEADER_SIZE) {
299
error = true;
300
throw new IOException("Chunk header too long");
301
}
302
}
303
if (pos >= rawCount) {
304
return;
305
}
306
307
/*
308
* Extract the chunk size from the header (ignoring extensions).
309
*/
310
String header = new String(rawData, rawPos, pos-rawPos+1,
311
US_ASCII.INSTANCE);
312
for (i=0; i < header.length(); i++) {
313
if (Character.digit(header.charAt(i), 16) == -1)
314
break;
315
}
316
try {
317
chunkSize = Integer.parseInt(header, 0, i, 16);
318
} catch (NumberFormatException e) {
319
error = true;
320
throw new IOException("Bogus chunk size");
321
}
322
323
/*
324
* Chunk has been parsed so move rawPos to first byte of chunk
325
* data.
326
*/
327
rawPos = pos + 1;
328
chunkRead = 0;
329
330
/*
331
* A chunk size of 0 means EOF.
332
*/
333
if (chunkSize > 0) {
334
state = STATE_READING_CHUNK;
335
} else {
336
state = STATE_AWAITING_TRAILERS;
337
}
338
break;
339
340
341
/**
342
* We are awaiting raw entity data (some may have already been
343
* read). chunkSize is the size of the chunk; chunkRead is the
344
* total read from the underlying stream to date.
345
*/
346
case STATE_READING_CHUNK :
347
/* no data available yet */
348
if (rawPos >= rawCount) {
349
return;
350
}
351
352
/*
353
* Compute the number of bytes of chunk data available in the
354
* raw buffer.
355
*/
356
int copyLen = Math.min( chunkSize-chunkRead, rawCount-rawPos );
357
358
/*
359
* Expand or compact chunkData if needed.
360
*/
361
if (chunkData.length < chunkCount + copyLen) {
362
int cnt = chunkCount - chunkPos;
363
if (chunkData.length < cnt + copyLen) {
364
byte tmp[] = new byte[cnt + copyLen];
365
System.arraycopy(chunkData, chunkPos, tmp, 0, cnt);
366
chunkData = tmp;
367
} else {
368
System.arraycopy(chunkData, chunkPos, chunkData, 0, cnt);
369
}
370
chunkPos = 0;
371
chunkCount = cnt;
372
}
373
374
/*
375
* Copy the chunk data into chunkData so that it's available
376
* to the read methods.
377
*/
378
System.arraycopy(rawData, rawPos, chunkData, chunkCount, copyLen);
379
rawPos += copyLen;
380
chunkCount += copyLen;
381
chunkRead += copyLen;
382
383
/*
384
* If all the chunk has been copied into chunkData then the next
385
* token should be CRLF.
386
*/
387
if (chunkSize - chunkRead <= 0) {
388
state = STATE_AWAITING_CHUNK_EOL;
389
} else {
390
return;
391
}
392
break;
393
394
395
/**
396
* Awaiting CRLF after the chunk
397
*/
398
case STATE_AWAITING_CHUNK_EOL:
399
/* not available yet */
400
if (rawPos + 1 >= rawCount) {
401
return;
402
}
403
404
if (rawData[rawPos] != '\r') {
405
error = true;
406
throw new IOException("missing CR");
407
}
408
if (rawData[rawPos+1] != '\n') {
409
error = true;
410
throw new IOException("missing LF");
411
}
412
rawPos += 2;
413
414
/*
415
* Move onto the next chunk
416
*/
417
state = STATE_AWAITING_CHUNK_HEADER;
418
break;
419
420
421
/**
422
* Last chunk has been read so not we're waiting for optional
423
* trailers.
424
*/
425
case STATE_AWAITING_TRAILERS:
426
427
/*
428
* Do we have an entire line in the raw buffer?
429
*/
430
pos = rawPos;
431
while (pos < rawCount) {
432
if (rawData[pos] == '\n') {
433
break;
434
}
435
pos++;
436
}
437
if (pos >= rawCount) {
438
return;
439
}
440
441
if (pos == rawPos) {
442
error = true;
443
throw new IOException("LF should be proceeded by CR");
444
}
445
if (rawData[pos-1] != '\r') {
446
error = true;
447
throw new IOException("LF should be proceeded by CR");
448
}
449
450
/*
451
* Stream done so close underlying stream.
452
*/
453
if (pos == (rawPos + 1)) {
454
455
state = STATE_DONE;
456
closeUnderlying();
457
458
return;
459
}
460
461
/*
462
* Extract any tailers and append them to the message
463
* headers.
464
*/
465
String trailer = new String(rawData, rawPos, pos-rawPos,
466
US_ASCII.INSTANCE);
467
i = trailer.indexOf(':');
468
if (i == -1) {
469
throw new IOException("Malformed tailer - format should be key:value");
470
}
471
String key = (trailer.substring(0, i)).trim();
472
String value = (trailer.substring(i+1, trailer.length())).trim();
473
474
responses.add(key, value);
475
476
/*
477
* Move onto the next trailer.
478
*/
479
rawPos = pos+1;
480
break;
481
482
} /* switch */
483
}
484
}
485
486
487
/**
488
* Reads any available bytes from the underlying stream into
489
* <code>rawData</code> and returns the number of bytes of
490
* chunk data available in <code>chunkData</code> that the
491
* application can read.
492
*/
493
private int readAheadNonBlocking() throws IOException {
494
495
/*
496
* If there's anything available on the underlying stream then we read
497
* it into the raw buffer and process it. Processing ensures that any
498
* available chunk data is made available in chunkData.
499
*/
500
int avail = in.available();
501
if (avail > 0) {
502
503
/* ensure that there is space in rawData to read the available */
504
ensureRawAvailable(avail);
505
506
int nread;
507
try {
508
nread = in.read(rawData, rawCount, avail);
509
} catch (IOException e) {
510
error = true;
511
throw e;
512
}
513
if (nread < 0) {
514
error = true; /* premature EOF ? */
515
return -1;
516
}
517
rawCount += nread;
518
519
/*
520
* Process the raw bytes that have been read.
521
*/
522
processRaw();
523
}
524
525
/*
526
* Return the number of chunked bytes available to read
527
*/
528
return chunkCount - chunkPos;
529
}
530
531
/**
532
* Reads from the underlying stream until there is chunk data
533
* available in <code>chunkData</code> for the application to
534
* read.
535
*/
536
private int readAheadBlocking() throws IOException {
537
538
do {
539
/*
540
* All of chunked response has been read to return EOF.
541
*/
542
if (state == STATE_DONE) {
543
return -1;
544
}
545
546
/*
547
* We must read into the raw buffer so make sure there is space
548
* available. We use a size of 32 to avoid too much chunk data
549
* being read into the raw buffer.
550
*/
551
ensureRawAvailable(32);
552
int nread;
553
try {
554
nread = in.read(rawData, rawCount, rawData.length-rawCount);
555
} catch (IOException e) {
556
error = true;
557
throw e;
558
}
559
560
/**
561
* If we hit EOF it means there's a problem as we should never
562
* attempt to read once the last chunk and trailers have been
563
* received.
564
*/
565
if (nread < 0) {
566
error = true;
567
throw new IOException("Premature EOF");
568
}
569
570
/**
571
* Process the bytes from the underlying stream
572
*/
573
rawCount += nread;
574
processRaw();
575
576
} while (chunkCount <= 0);
577
578
/*
579
* Return the number of chunked bytes available to read
580
*/
581
return chunkCount - chunkPos;
582
}
583
584
/**
585
* Read ahead in either blocking or non-blocking mode. This method
586
* is typically used when we run out of available bytes in
587
* <code>chunkData</code> or we need to determine how many bytes
588
* are available on the input stream.
589
*/
590
private int readAhead(boolean allowBlocking) throws IOException {
591
592
/*
593
* Last chunk already received - return EOF
594
*/
595
if (state == STATE_DONE) {
596
return -1;
597
}
598
599
/*
600
* Reset position/count if data in chunkData is exhausted.
601
*/
602
if (chunkPos >= chunkCount) {
603
chunkCount = 0;
604
chunkPos = 0;
605
}
606
607
/*
608
* Read ahead blocking or non-blocking
609
*/
610
if (allowBlocking) {
611
return readAheadBlocking();
612
} else {
613
return readAheadNonBlocking();
614
}
615
}
616
617
/**
618
* Creates a <code>ChunkedInputStream</code> and saves its arguments, for
619
* later use.
620
*
621
* @param in the underlying input stream.
622
* @param hc the HttpClient
623
* @param responses the MessageHeader that should be populated with optional
624
* trailers.
625
*/
626
public ChunkedInputStream(InputStream in, HttpClient hc, MessageHeader responses) throws IOException {
627
628
/* save arguments */
629
this.in = in;
630
this.responses = responses;
631
this.hc = hc;
632
633
/*
634
* Set our initial state to indicate that we are first starting to
635
* look for a chunk header.
636
*/
637
state = STATE_AWAITING_CHUNK_HEADER;
638
}
639
640
/**
641
* See
642
* the general contract of the <code>read</code>
643
* method of <code>InputStream</code>.
644
*
645
* @return the next byte of data, or <code>-1</code> if the end of the
646
* stream is reached.
647
* @exception IOException if an I/O error occurs.
648
* @see java.io.FilterInputStream#in
649
*/
650
public int read() throws IOException {
651
readLock.lock();
652
try {
653
ensureOpen();
654
if (chunkPos >= chunkCount) {
655
if (readAhead(true) <= 0) {
656
return -1;
657
}
658
}
659
return chunkData[chunkPos++] & 0xff;
660
} finally {
661
readLock.unlock();
662
}
663
}
664
665
666
/**
667
* Reads bytes from this stream into the specified byte array, starting at
668
* the given offset.
669
*
670
* @param b destination buffer.
671
* @param off offset at which to start storing bytes.
672
* @param len maximum number of bytes to read.
673
* @return the number of bytes read, or <code>-1</code> if the end of
674
* the stream has been reached.
675
* @exception IOException if an I/O error occurs.
676
*/
677
public int read(byte b[], int off, int len)
678
throws IOException
679
{
680
readLock.lock();
681
try {
682
ensureOpen();
683
if ((off < 0) || (off > b.length) || (len < 0) ||
684
((off + len) > b.length) || ((off + len) < 0)) {
685
throw new IndexOutOfBoundsException();
686
} else if (len == 0) {
687
return 0;
688
}
689
690
int avail = chunkCount - chunkPos;
691
if (avail <= 0) {
692
/*
693
* Optimization: if we're in the middle of the chunk read
694
* directly from the underlying stream into the caller's
695
* buffer
696
*/
697
if (state == STATE_READING_CHUNK) {
698
return fastRead(b, off, len);
699
}
700
701
/*
702
* We're not in the middle of a chunk so we must read ahead
703
* until there is some chunk data available.
704
*/
705
avail = readAhead(true);
706
if (avail < 0) {
707
return -1; /* EOF */
708
}
709
}
710
int cnt = (avail < len) ? avail : len;
711
System.arraycopy(chunkData, chunkPos, b, off, cnt);
712
chunkPos += cnt;
713
714
return cnt;
715
} finally {
716
readLock.unlock();
717
}
718
}
719
720
/**
721
* Returns the number of bytes that can be read from this input
722
* stream without blocking.
723
*
724
* @return the number of bytes that can be read from this input
725
* stream without blocking.
726
* @exception IOException if an I/O error occurs.
727
* @see java.io.FilterInputStream#in
728
*/
729
public int available() throws IOException {
730
readLock.lock();
731
try {
732
ensureOpen();
733
734
int avail = chunkCount - chunkPos;
735
if (avail > 0) {
736
return avail;
737
}
738
739
avail = readAhead(false);
740
741
if (avail < 0) {
742
return 0;
743
} else {
744
return avail;
745
}
746
} finally {
747
readLock.unlock();
748
}
749
}
750
751
/**
752
* Close the stream by either returning the connection to the
753
* keep alive cache or closing the underlying stream.
754
* <p>
755
* If the chunked response hasn't been completely read we
756
* try to "hurry" to the end of the response. If this is
757
* possible (without blocking) then the connection can be
758
* returned to the keep alive cache.
759
*
760
* @exception IOException if an I/O error occurs.
761
*/
762
public void close() throws IOException {
763
if (closed) return;
764
readLock.lock();
765
try {
766
if (closed) {
767
return;
768
}
769
closeUnderlying();
770
closed = true;
771
} finally {
772
readLock.unlock();
773
}
774
}
775
776
/**
777
* Hurry the input stream by reading everything from the underlying
778
* stream. If the last chunk (and optional trailers) can be read without
779
* blocking then the stream is considered hurried.
780
* <p>
781
* Note that if an error has occurred or we can't get to last chunk
782
* without blocking then this stream can't be hurried and should be
783
* closed.
784
*/
785
public boolean hurry() {
786
readLock.lock();
787
try {
788
if (in == null || error) {
789
return false;
790
}
791
792
try {
793
readAhead(false);
794
} catch (Exception e) {
795
return false;
796
}
797
798
if (error) {
799
return false;
800
}
801
802
return (state == STATE_DONE);
803
} finally {
804
readLock.unlock();
805
}
806
}
807
808
}
809
810