Path: blob/master/src/java.base/share/classes/sun/net/www/http/ChunkedOutputStream.java
41161 views
/*1* Copyright (c) 2004, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package sun.net.www.http;2526import java.io.*;27import java.util.concurrent.locks.Lock;28import java.util.concurrent.locks.ReentrantLock;2930import sun.nio.cs.US_ASCII;3132/**33* OutputStream that sends the output to the underlying stream using chunked34* encoding as specified in RFC 2068.35*/36public class ChunkedOutputStream extends OutputStream {3738/* Default chunk size (including chunk header) if not specified */39static final int DEFAULT_CHUNK_SIZE = 4096;40private static final byte[] CRLF = {'\r', '\n'};41private static final int CRLF_SIZE = CRLF.length;42private static final byte[] FOOTER = CRLF;43private static final int FOOTER_SIZE = CRLF_SIZE;44private static final byte[] EMPTY_CHUNK_HEADER = getHeader(0);45private static final int EMPTY_CHUNK_HEADER_SIZE = getHeaderSize(0);4647/* internal buffer */48private byte buf[];49/* size of data (excluding footers and headers) already stored in buf */50private int size;51/* current index in buf (i.e. buf[count] */52private int count;53/* number of bytes to be filled up to complete a data chunk54* currently being built */55private int spaceInCurrentChunk;5657/* underlying stream */58private PrintStream out;5960/* the chunk size we use */61private int preferredChunkDataSize;62private int preferedHeaderSize;63private int preferredChunkGrossSize;64/* header for a complete Chunk */65private byte[] completeHeader;6667private final Lock writeLock = new ReentrantLock();6869/* return the size of the header for a particular chunk size */70private static int getHeaderSize(int size) {71return (Integer.toHexString(size)).length() + CRLF_SIZE;72}7374/* return a header for a particular chunk size */75private static byte[] getHeader(int size) {76String hexStr = Integer.toHexString(size);77byte[] hexBytes = hexStr.getBytes(US_ASCII.INSTANCE);78byte[] header = new byte[getHeaderSize(size)];79for (int i=0; i<hexBytes.length; i++)80header[i] = hexBytes[i];81header[hexBytes.length] = CRLF[0];82header[hexBytes.length+1] = CRLF[1];83return header;84}8586public ChunkedOutputStream(PrintStream o) {87this(o, DEFAULT_CHUNK_SIZE);88}8990public ChunkedOutputStream(PrintStream o, int size) {91out = o;9293if (size <= 0) {94size = DEFAULT_CHUNK_SIZE;95}9697/* Adjust the size to cater for the chunk header - eg: if the98* preferred chunk size is 1k this means the chunk size should99* be 1017 bytes (differs by 7 from preferred size because of100* 3 bytes for chunk size in hex and CRLF (header) and CRLF (footer)).101*102* If headerSize(adjusted_size) is shorter then headerSize(size)103* then try to use the extra byte unless headerSize(adjusted_size+1)104* increases back to headerSize(size)105*/106if (size > 0) {107int adjusted_size = size - getHeaderSize(size) - FOOTER_SIZE;108if (getHeaderSize(adjusted_size+1) < getHeaderSize(size)){109adjusted_size++;110}111size = adjusted_size;112}113114if (size > 0) {115preferredChunkDataSize = size;116} else {117preferredChunkDataSize = DEFAULT_CHUNK_SIZE -118getHeaderSize(DEFAULT_CHUNK_SIZE) - FOOTER_SIZE;119}120121preferedHeaderSize = getHeaderSize(preferredChunkDataSize);122preferredChunkGrossSize = preferedHeaderSize + preferredChunkDataSize123+ FOOTER_SIZE;124completeHeader = getHeader(preferredChunkDataSize);125126/* start with an initial buffer */127buf = new byte[preferredChunkGrossSize];128reset();129}130131/*132* Flush a buffered, completed chunk to an underlying stream. If the data in133* the buffer is insufficient to build up a chunk of "preferredChunkSize"134* then the data do not get flushed unless flushAll is true. If flushAll is135* true then the remaining data builds up a last chunk which size is smaller136* than preferredChunkSize, and then the last chunk gets flushed to137* underlying stream. If flushAll is true and there is no data in a buffer138* at all then an empty chunk (containing a header only) gets flushed to139* underlying stream.140*/141private void flush(boolean flushAll) {142if (spaceInCurrentChunk == 0) {143/* flush a completed chunk to underlying stream */144out.write(buf, 0, preferredChunkGrossSize);145out.flush();146reset();147} else if (flushAll){148/* complete the last chunk and flush it to underlying stream */149if (size > 0) {150/* adjust a header start index in case the header of the last151* chunk is shorter then preferedHeaderSize */152153int adjustedHeaderStartIndex = preferedHeaderSize -154getHeaderSize(size);155156/* write header */157System.arraycopy(getHeader(size), 0, buf,158adjustedHeaderStartIndex, getHeaderSize(size));159160/* write footer */161buf[count++] = FOOTER[0];162buf[count++] = FOOTER[1];163164//send the last chunk to underlying stream165out.write(buf, adjustedHeaderStartIndex, count - adjustedHeaderStartIndex);166} else {167//send an empty chunk (containing just a header) to underlying stream168out.write(EMPTY_CHUNK_HEADER, 0, EMPTY_CHUNK_HEADER_SIZE);169}170171out.flush();172reset();173}174}175176public boolean checkError() {177var out = this.out;178return out == null || out.checkError();179}180181/* Check that the output stream is still open */182private void ensureOpen() throws IOException {183if (out == null)184throw new IOException("closed");185}186187/*188* Writes data from b[] to an internal buffer and stores the data as data189* chunks of a following format: {Data length in Hex}{CRLF}{data}{CRLF}190* The size of the data is preferredChunkSize. As soon as a completed chunk191* is read from b[] a process of reading from b[] suspends, the chunk gets192* flushed to the underlying stream and then the reading process from b[]193* continues. When there is no more sufficient data in b[] to build up a194* chunk of preferredChunkSize size the data get stored as an incomplete195* chunk of a following format: {space for data length}{CRLF}{data}196* The size of the data is of course smaller than preferredChunkSize.197*/198@Override199public void write(byte b[], int off, int len) throws IOException {200writeLock.lock();201try {202ensureOpen();203if ((off < 0) || (off > b.length) || (len < 0) ||204((off + len) > b.length) || ((off + len) < 0)) {205throw new IndexOutOfBoundsException();206} else if (len == 0) {207return;208}209210/* if b[] contains enough data then one loop cycle creates one complete211* data chunk with a header, body and a footer, and then flushes the212* chunk to the underlying stream. Otherwise, the last loop cycle213* creates incomplete data chunk with empty header and with no footer214* and stores this incomplete chunk in an internal buffer buf[]215*/216int bytesToWrite = len;217int inputIndex = off; /* the index of the byte[] currently being written */218219do {220/* enough data to complete a chunk */221if (bytesToWrite >= spaceInCurrentChunk) {222223/* header */224for (int i = 0; i < completeHeader.length; i++)225buf[i] = completeHeader[i];226227/* data */228System.arraycopy(b, inputIndex, buf, count, spaceInCurrentChunk);229inputIndex += spaceInCurrentChunk;230bytesToWrite -= spaceInCurrentChunk;231count += spaceInCurrentChunk;232233/* footer */234buf[count++] = FOOTER[0];235buf[count++] = FOOTER[1];236spaceInCurrentChunk = 0; //chunk is complete237238flush(false);239if (checkError()) {240break;241}242}243244/* not enough data to build a chunk */245else {246/* header */247/* do not write header if not enough bytes to build a chunk yet */248249/* data */250System.arraycopy(b, inputIndex, buf, count, bytesToWrite);251count += bytesToWrite;252size += bytesToWrite;253spaceInCurrentChunk -= bytesToWrite;254bytesToWrite = 0;255256/* footer */257/* do not write header if not enough bytes to build a chunk yet */258}259} while (bytesToWrite > 0);260} finally {261writeLock.unlock();262}263}264265@Override266public void write(int _b) throws IOException {267writeLock.lock();268try {269byte b[] = {(byte) _b};270write(b, 0, 1);271} finally {272writeLock.unlock();273}274}275276public void reset() {277writeLock.lock();278try {279count = preferedHeaderSize;280size = 0;281spaceInCurrentChunk = preferredChunkDataSize;282} finally {283writeLock.unlock();284}285}286287public int size() {288return size;289}290291@Override292public void close() {293writeLock.lock();294try {295if (out == null) return;296297/* if we have buffer a chunked send it */298if (size > 0) {299flush(true);300}301302/* send a zero length chunk */303flush(true);304305/* don't close the underlying stream */306out = null;307} finally {308writeLock.unlock();309}310}311312@Override313public void flush() throws IOException {314writeLock.lock();315try {316ensureOpen();317if (size > 0) {318flush(true);319}320} finally {321writeLock.unlock();322}323}324}325326327