Java Code Examples for org.apache.tomcat.util.buf.ByteChunk#getLength()

The following examples show how to use org.apache.tomcat.util.buf.ByteChunk#getLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InternalOutputBuffer.java    From Tomcat7.0.67 with Apache License 2.0 7 votes vote down vote up
/**
 * Write chunk.
 */
@Override
public int doWrite(ByteChunk chunk, Response res) 
    throws IOException {

    int length = chunk.getLength();
    if (useSocketBuffer) {
        socketBuffer.append(chunk.getBuffer(), chunk.getStart(), 
                            length);
    } else {
        outputStream.write(chunk.getBuffer(), chunk.getStart(), 
                           length);
    }
    byteCount += chunk.getLength();
    return chunk.getLength();
}
 
Example 2
Source File: CoyoteAdapter.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Character conversion of the a US-ASCII MessageBytes.
 */
protected void convertMB(MessageBytes mb) {

    // This is of course only meaningful for bytes
    if (mb.getType() != MessageBytes.T_BYTES) {
        return;
    }

    ByteChunk bc = mb.getByteChunk();
    CharChunk cc = mb.getCharChunk();
    int length = bc.getLength();
    cc.allocate(length, -1);

    // Default encoding: fast conversion
    byte[] bbuf = bc.getBuffer();
    char[] cbuf = cc.getBuffer();
    int start = bc.getStart();
    for (int i = 0; i < length; i++) {
        cbuf[i] = (char) (bbuf[i + start] & 0xff);
    }
    mb.setChars(cbuf, 0, length);

}
 
Example 3
Source File: TestHttp11Processor.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doTestBug53677(boolean flush) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Tomcat.addServlet(ctx, "LargeHeaderServlet",
            new LargeHeaderServlet(flush));
    ctx.addServletMappingDecoded("/test", "LargeHeaderServlet");

    tomcat.start();

    ByteChunk responseBody = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/test", responseBody, null);

    Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
    if (responseBody.getLength() > 0) {
        // It will be >0 if the standard error page handling has been
        // triggered
        Assert.assertFalse(responseBody.toString().contains("FAIL"));
    }
}
 
Example 4
Source File: Cookies.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Unescapes any double quotes in the given cookie value.
 *
 * @param bc The cookie value to modify
 */
private static void unescapeDoubleQuotes(ByteChunk bc) {

    if (bc == null || bc.getLength() == 0 || bc.indexOf('"', 0) == -1) {
        return;
    }

    int src = bc.getStart();
    int end = bc.getEnd();
    int dest = src;
    byte[] buffer = bc.getBuffer();

    while (src < end) {
        if (buffer[src] == '\\' && src < end && buffer[src+1]  == '"') {
            src++;
        }
        buffer[dest] = buffer[src];
        dest ++;
        src ++;
    }
    bc.setEnd(dest);
}
 
Example 5
Source File: ChunkedOutputFilter.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * @deprecated Unused. Will be removed in Tomcat 9. Use
 *             {@link #doWrite(ByteBuffer)}
 */
@Deprecated
@Override
public int doWrite(ByteChunk chunk) throws IOException {

    int result = chunk.getLength();

    if (result <= 0) {
        return 0;
    }

    int pos = calculateChunkHeader(result);

    chunkHeader.position(pos).limit(10);
    buffer.doWrite(chunkHeader);

    buffer.doWrite(chunk);

    chunkHeader.position(8).limit(10);
    buffer.doWrite(chunkHeader);

    return result;
}
 
Example 6
Source File: InternalOutputBuffer.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Write chunk.
 */
@Override
public int doWrite(ByteChunk chunk, Response res) throws IOException {
    try {
        int length = chunk.getLength();
        if (useSocketBuffer) {
            socketBuffer.append(chunk.getBuffer(), chunk.getStart(),
                                length);
        } else {
            outputStream.write(chunk.getBuffer(), chunk.getStart(),
                               length);
        }
        byteCount += chunk.getLength();
        return chunk.getLength();
    } catch (IOException ioe) {
        response.action(ActionCode.CLOSE_NOW, ioe);
        // Re-throw
        throw ioe;
    }
}
 
Example 7
Source File: AjpProcessor.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * @deprecated Unused. Will be removed in Tomcat 9. Use
 *             {@link #writeData(ByteBuffer)}
 */
@Deprecated
private void writeData(ByteChunk chunk) throws IOException {
    boolean blocking = (response.getWriteListener() == null);

    int len = chunk.getLength();
    int off = 0;

    // Write this chunk
    while (len > 0) {
        int thisTime = Math.min(len, outputMaxChunkSize);

        responseMessage.reset();
        responseMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK);
        responseMessage.appendBytes(chunk.getBytes(), chunk.getOffset() + off, thisTime);
        responseMessage.end();
        socketWrapper.write(blocking, responseMessage.getBuffer(), 0, responseMessage.getLen());
        socketWrapper.flush(blocking);

        len -= thisTime;
        off += thisTime;
    }

    bytesWritten += off;
}
 
Example 8
Source File: TestAbstractHttp11Processor.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void doTestBug53677(boolean flush) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctxt = tomcat.addContext("", null);

    Tomcat.addServlet(ctxt, "LargeHeaderServlet",
            new LargeHeaderServlet(flush));
    ctxt.addServletMapping("/test", "LargeHeaderServlet");

    tomcat.start();

    ByteChunk responseBody = new ByteChunk();
    Map<String,List<String>> responseHeaders =
            new HashMap<String,List<String>>();
    int rc = getUrl("http://localhost:" + getPort() + "/test", responseBody,
            responseHeaders);

    assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
    if (responseBody.getLength() > 0) {
        // It will be >0 if the standard error page handlign has been
        // triggered
        assertFalse(responseBody.toString().contains("FAIL"));
    }
}
 
Example 9
Source File: Cookies.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Unescapes any double quotes in the given cookie value.
 *
 * @param bc The cookie value to modify
 */
private static void unescapeDoubleQuotes(ByteChunk bc) {

    if (bc == null || bc.getLength() == 0 || bc.indexOf('"', 0) == -1) {
        return;
    }

    int src = bc.getStart();
    int end = bc.getEnd();
    int dest = src;
    byte[] buffer = bc.getBuffer();

    while (src < end) {
        if (buffer[src] == '\\' && src < end && buffer[src+1]  == '"') {
            src++;
        }
        buffer[dest] = buffer[src];
        dest ++;
        src ++;
    }
    bc.setEnd(dest);
}
 
Example 10
Source File: IdentityOutputFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Write some bytes.
 * 
 * @return number of bytes written by the filter
 */
@Override
public int doWrite(ByteChunk chunk, Response res)
    throws IOException {

    int result = -1;

    if (contentLength >= 0) {
        if (remaining > 0) {
            result = chunk.getLength();
            if (result > remaining) {
                // The chunk is longer than the number of bytes remaining
                // in the body; changing the chunk length to the number
                // of bytes remaining
                chunk.setBytes(chunk.getBytes(), chunk.getStart(), 
                               (int) remaining);
                result = (int) remaining;
                remaining = 0;
            } else {
                remaining = remaining - result;
            }
            buffer.doWrite(chunk, res);
        } else {
            // No more bytes left to be written : return -1 and clear the 
            // buffer
            chunk.recycle();
            result = -1;
        }
    } else {
        // If no content length was set, just write the bytes
        buffer.doWrite(chunk, res);
        result = chunk.getLength();
    }

    return result;

}
 
Example 11
Source File: VoidOutputFilter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Write some bytes.
 * 
 * @return number of bytes written by the filter
 */
@Override
public int doWrite(ByteChunk chunk, Response res)
    throws IOException {

    return chunk.getLength();

}
 
Example 12
Source File: Stream.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * @deprecated Unused. Will be removed in Tomcat 9. Use
 *             {@link #doWrite(ByteBuffer)}
 */
@Deprecated
@Override
public synchronized int doWrite(ByteChunk chunk) throws IOException {
    if (closed) {
        throw new IllegalStateException(
                sm.getString("stream.closed", getConnectionId(), getIdentifier()));
    }
    if (!coyoteResponse.isCommitted()) {
        coyoteResponse.sendHeaders();
    }
    int len = chunk.getLength();
    int offset = 0;
    while (len > 0) {
        int thisTime = Math.min(buffer.remaining(), len);
        buffer.put(chunk.getBytes(), chunk.getOffset() + offset, thisTime);
        offset += thisTime;
        len -= thisTime;
        if (len > 0 && !buffer.hasRemaining()) {
            // Only flush if we have more data to write and the buffer
            // is full
            if (flush(true, coyoteResponse.getWriteListener() == null)) {
                break;
            }
        }
    }
    written += offset;
    return offset;
}
 
Example 13
Source File: InternalAprOutputBuffer.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Write chunk.
 */
@Override
public int doWrite(ByteChunk chunk, Response res) throws IOException {
    try {
        int len = chunk.getLength();
        int start = chunk.getStart();
        byte[] b = chunk.getBuffer();
        while (len > 0) {
            int thisTime = len;
            if (bbuf.position() == bbuf.capacity()) {
                flushBuffer();
            }
            if (thisTime > bbuf.capacity() - bbuf.position()) {
                thisTime = bbuf.capacity() - bbuf.position();
            }
            bbuf.put(b, start, thisTime);
            len = len - thisTime;
            start = start + thisTime;
        }
        byteCount += chunk.getLength();
        return chunk.getLength();
    } catch (IOException ioe) {
        response.action(ActionCode.CLOSE_NOW, ioe);
        // Re-throw
        throw ioe;
    }
}
 
Example 14
Source File: ChunkedOutputFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Write some bytes.
 * 
 * @return number of bytes written by the filter
 */
@Override
public int doWrite(ByteChunk chunk, Response res)
    throws IOException {

    int result = chunk.getLength();

    if (result <= 0) {
        return 0;
    }

    // Calculate chunk header
    int pos = 7;
    int current = result;
    while (current > 0) {
        int digit = current % 16;
        current = current / 16;
        chunkLength[pos--] = HexUtils.getHex(digit);
    }
    chunkHeader.setBytes(chunkLength, pos + 1, 9 - pos);
    buffer.doWrite(chunkHeader, res);

    buffer.doWrite(chunk, res);

    chunkHeader.setBytes(chunkLength, 8, 2);
    buffer.doWrite(chunkHeader, res);

    return result;

}
 
Example 15
Source File: Http11OutputBuffer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Write chunk.
 *
 * @deprecated Unused. Will be removed in Tomcat 9. Use
 *             {@link #doWrite(ByteBuffer)}
 */
@Deprecated
@Override
public int doWrite(ByteChunk chunk) throws IOException {
    int len = chunk.getLength();
    int start = chunk.getStart();
    byte[] b = chunk.getBuffer();
    socketWrapper.write(isBlocking(), b, start, len);
    byteCount += len;
    return len;
}
 
Example 16
Source File: ChunkedOutputFilter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Write some bytes.
 * 
 * @return number of bytes written by the filter
 */
@Override
public int doWrite(ByteChunk chunk, Response res)
    throws IOException {

    int result = chunk.getLength();

    if (result <= 0) {
        return 0;
    }

    // Calculate chunk header
    int pos = 7;
    int current = result;
    while (current > 0) {
        int digit = current % 16;
        current = current / 16;
        chunkLength[pos--] = HexUtils.getHex(digit);
    }
    chunkHeader.setBytes(chunkLength, pos + 1, 9 - pos);
    buffer.doWrite(chunkHeader, res);

    buffer.doWrite(chunk, res);

    chunkHeader.setBytes(chunkLength, 8, 2);
    buffer.doWrite(chunkHeader, res);

    return result;

}
 
Example 17
Source File: InternalNioOutputBuffer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Write chunk.
 */
@Override
public int doWrite(ByteChunk chunk, Response res) 
    throws IOException {

    int len = chunk.getLength();
    int start = chunk.getStart();
    byte[] b = chunk.getBuffer();
    addToBB(b, start, len);
    byteCount += chunk.getLength();
    return chunk.getLength();
}
 
Example 18
Source File: GzipOutputFilter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Write some bytes.
 * 
 * @return number of bytes written by the filter
 */
@Override
public int doWrite(ByteChunk chunk, Response res)
    throws IOException {
    if (compressionStream == null) {
        compressionStream = new FlushableGZIPOutputStream(fakeOutputStream);
    }
    compressionStream.write(chunk.getBytes(), chunk.getStart(), 
                            chunk.getLength());
    return chunk.getLength();
}
 
Example 19
Source File: Cookies.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/** Add all Cookie found in the headers of a request.
 */
public  void processCookies( MimeHeaders headers ) {
    if( headers==null ) {
        return;// nothing to process
    }
    // process each "cookie" header
    int pos=0;
    while( pos>=0 ) {
        // Cookie2: version ? not needed
        pos=headers.findHeader( "Cookie", pos );
        // no more cookie headers headers
        if( pos<0 ) {
            break;
        }

        MessageBytes cookieValue=headers.getValue( pos );
        if( cookieValue==null || cookieValue.isNull() ) {
            pos++;
            continue;
        }

        if( cookieValue.getType() != MessageBytes.T_BYTES ) {
            Exception e = new Exception();
            log.warn("Cookies: Parsing cookie as String. Expected bytes.",
                    e);
            cookieValue.toBytes();
        }
        if(log.isDebugEnabled()) {
            log.debug("Cookies: Parsing b[]: " + cookieValue.toString());
        }
        ByteChunk bc=cookieValue.getByteChunk();
        if (CookieSupport.PRESERVE_COOKIE_HEADER) {
            int len = bc.getLength();
            if (len > 0) {
                byte[] buf = new byte[len];
                System.arraycopy(bc.getBytes(), bc.getOffset(), buf, 0, len);
                processCookieHeader(buf, 0, len);
            }
        } else {
            processCookieHeader( bc.getBytes(),
                    bc.getOffset(),
                    bc.getLength());
        }
        pos++;// search from the next position
    }
}
 
Example 20
Source File: AbstractProcessor.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
protected void parseHost(MessageBytes valueMB) {
    if (valueMB == null || valueMB.isNull()) {
        populateHost();
        populatePort();
        return;
    } else if (valueMB.getLength() == 0) {
        // Empty Host header so set sever name to empty string
        request.serverName().setString("");
        populatePort();
        return;
    }

    ByteChunk valueBC = valueMB.getByteChunk();
    byte[] valueB = valueBC.getBytes();
    int valueL = valueBC.getLength();
    int valueS = valueBC.getStart();
    if (hostNameC.length < valueL) {
        hostNameC = new char[valueL];
    }

    try {
        // Validates the host name
        int colonPos = Host.parse(valueMB);

        // Extract the port information first, if any
        if (colonPos != -1) {
            int port = 0;
            for (int i = colonPos + 1; i < valueL; i++) {
                char c = (char) valueB[i + valueS];
                if (c < '0' || c > '9') {
                    response.setStatus(400);
                    setErrorState(ErrorState.CLOSE_CLEAN, null);
                    return;
                }
                port = port * 10 + c - '0';
            }
            request.setServerPort(port);

            // Only need to copy the host name up to the :
            valueL = colonPos;
        }

        // Extract the host name
        for (int i = 0; i < valueL; i++) {
            hostNameC[i] = (char) valueB[i + valueS];
        }
        request.serverName().setChars(hostNameC, 0, valueL);

    } catch (IllegalArgumentException e) {
        // IllegalArgumentException indicates that the host name is invalid
        UserDataHelper.Mode logMode = userDataHelper.getNextMode();
        if (logMode != null) {
            String message = sm.getString("abstractProcessor.hostInvalid", valueMB.toString());
            switch (logMode) {
                case INFO_THEN_DEBUG:
                    message += sm.getString("abstractProcessor.fallToDebug");
                    //$FALL-THROUGH$
                case INFO:
                    getLog().info(message, e);
                    break;
                case DEBUG:
                    getLog().debug(message, e);
            }
        }

        response.setStatus(400);
        setErrorState(ErrorState.CLOSE_CLEAN, e);
    }
}