org.apache.tomcat.util.buf.MessageBytes Java Examples

The following examples show how to use org.apache.tomcat.util.buf.MessageBytes. 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: Http11OutputBuffer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * This method will write the contents of the specified message bytes
 * buffer to the output stream, without filtering. This method is meant to
 * be used to write the response header.
 *
 * @param mb data to be written
 */
private void write(MessageBytes mb) {
    if (mb.getType() != MessageBytes.T_BYTES) {
        mb.toBytes();
        ByteChunk bc = mb.getByteChunk();
        // Need to filter out CTLs excluding TAB. ISO-8859-1 and UTF-8
        // values will be OK. Strings using other encodings may be
        // corrupted.
        byte[] buffer = bc.getBuffer();
        for (int i = bc.getOffset(); i < bc.getLength(); i++) {
            // byte values are signed i.e. -128 to 127
            // The values are used unsigned. 0 to 31 are CTLs so they are
            // filtered (apart from TAB which is 9). 127 is a control (DEL).
            // The values 128 to 255 are all OK. Converting those to signed
            // gives -128 to -1.
            if ((buffer[i] > -1 && buffer[i] <= 31 && buffer[i] != 9) ||
                    buffer[i] == 127) {
                buffer[i] = ' ';
            }
        }
    }
    write(mb.getByteChunk());
}
 
Example #2
Source File: BSTAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This test case tests the canHandle method of the BSTAuthenticator under faulty conditions")
public void testCanHandleWithFalseConditions() throws IllegalAccessException {
    Request request = new Request();
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    request.setCoyoteRequest(coyoteRequest);
    Assert.assertFalse(bstAuthenticator.canHandle(request),
            "BST Authenticator can handle a request without content type");

    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue("content-type");
    bytes.setString("test");
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    Assert.assertFalse(bstAuthenticator.canHandle(request),
            "BST Authenticator can handle a request with content type test");
}
 
Example #3
Source File: WebappAuthenticationValveTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * To create a request with the given authorization header
 *
 * @param authorizationHeader Authorization header
 * @return the relevant request.
 * @throws IllegalAccessException Illegal Access Exception.
 * @throws NoSuchFieldException   No Such Field Exception.
 */
private Request createRequest(String authorizationHeader) throws IllegalAccessException, NoSuchFieldException {
    Request request = new TestRequest("", "");
    Context context = new StandardContext();
    context.addParameter("basicAuth", "true");
    context.addParameter("managed-api-enabled", "true");
    context.setPath("carbon1");
    context.addParameter("doAuthentication", String.valueOf(true));
    request.setContext(context);
    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER);
    bytes.setString(authorizationHeader);
    Field headersField = org.apache.coyote.Request.class.getDeclaredField("headers");
    headersField.setAccessible(true);
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    return request;
}
 
Example #4
Source File: TestMapperPerformance.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private long testPerformanceImpl(String requestedHostName) throws Exception {
    MappingData mappingData = new MappingData();
    MessageBytes host = MessageBytes.newInstance();
    host.setString(requestedHostName);
    MessageBytes uri = MessageBytes.newInstance();
    uri.setString("/foo/bar/blah/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        mappingData.recycle();
        mapper.map(host, uri, null, mappingData);
    }
    long time = System.currentTimeMillis() - start;
    return time;
}
 
Example #5
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 #6
Source File: AjpMessage.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doGetBytes(MessageBytes mb, boolean terminated) {
    int length = getInt();
    if ((length == 0xFFFF) || (length == -1)) {
        mb.recycle();
        return;
    }
    if (terminated) {
        validatePos(pos + length + 1);
    } else {
        validatePos(pos + length);
    }
    mb.setBytes(buf, pos, length);
    mb.getCharChunk().recycle(); // not valid anymore
    pos += length;
    if (terminated) {
        pos++; // Skip the terminating \0
    }
}
 
Example #7
Source File: TestMapper.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private long testPerformanceImpl() throws Exception {
    MappingData mappingData = new MappingData();
    MessageBytes host = MessageBytes.newInstance();
    host.setString("iowejoiejfoiew");
    MessageBytes uri = MessageBytes.newInstance();
    uri.setString("/foo/bar/blah/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        mappingData.recycle();
        mapper.map(host, uri, null, mappingData);
    }
    long time = System.currentTimeMillis() - start;
    return time;
}
 
Example #8
Source File: JWTAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * To create a JWT request with the given jwt header.
 *  @param jwtToken JWT token to be added to the header
 * @param requestUri Request URI to be added to the request.
 */
private Request createJWTRequest(String jwtToken, String requestUri)
        throws IllegalAccessException, NoSuchFieldException {
    Request request = new Request();
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue(JWT_HEADER);
    bytes.setString(jwtToken);
    headersField.set(coyoteRequest, mimeHeaders);
    Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
    uriMB.setAccessible(true);
    bytes = MessageBytes.newInstance();
    bytes.setString(requestUri);
    uriMB.set(coyoteRequest, bytes);
    request.setCoyoteRequest(coyoteRequest);
    return request;
}
 
Example #9
Source File: BSTAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "This method tests the authenticate method of BST Authenticator when all the relevant "
        + "details", dependsOnMethods = "testInitWithRemote")
public void testAuthenticate() throws NoSuchFieldException, IllegalAccessException, IOException {
    Request request = createSoapRequest("CorrectBST.xml");
    org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
    Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
    uriMB.setAccessible(true);
    MessageBytes bytes = MessageBytes.newInstance();
    bytes.setString("test");
    uriMB.set(coyoteRequest, bytes);
    request.setCoyoteRequest(coyoteRequest);
    bstAuthenticator.canHandle(request);
    AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
            "Authentication status of authentication info is wrong");
    Assert.assertEquals(authenticationInfo.getUsername(), "admin",
            "User name in the authentication info is different than original user");
    OAuth2TokenValidationResponseDTO unAuthorizedValidationRespose = new OAuth2TokenValidationResponseDTO();
    unAuthorizedValidationRespose.setValid(false);
    unAuthorizedValidationRespose.setErrorMsg("User is not authorized");
    Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService)
            .findOAuthConsumerIfTokenIsValid(Mockito.any());
    oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(unAuthorizedValidationRespose);
    AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService);
    authenticationInfo = bstAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE,
            "Un-authorized user got authenticated with BST");
}
 
Example #10
Source File: MimeHeaders.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Finds and returns a header field with the given name.  If no such
 * field exists, null is returned.  If more than one such field is
 * in the header, an arbitrary one is returned.
 */
public MessageBytes getValue(String name) {
    for (int i = 0; i < count; i++) {
        if (headers[i].getName().equalsIgnoreCase(name)) {
            return headers[i].getValue();
        }
    }
    return null;
}
 
Example #11
Source File: CertificateAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * To create a request that can be understandable by Certificate Authenticator.
 *
 * @param headerName Name of the header
 * @param value      Value for the header
 * @return Request that is created.
 * @throws IllegalAccessException Illegal Access Exception.
 * @throws NoSuchFieldException   No Such Field Exception.
 */
private Request createRequest(String headerName, String value) throws IllegalAccessException, NoSuchFieldException {
    Request request = new Request();
    Context context = new StandardContext();
    request.setContext(context);
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue(headerName);
    bytes.setString(value);
    headersField.set(coyoteRequest, mimeHeaders);

    request.setCoyoteRequest(coyoteRequest);
    return request;
}
 
Example #12
Source File: Mapper.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Map the specified host name and URI, mutating the given mapping data.
 *
 * @param host Virtual host name
 * @param uri URI
 * @param mappingData This structure will contain the result of the mapping
 *                    operation
 */
public void map(MessageBytes host, MessageBytes uri, String version,
                MappingData mappingData)
    throws Exception {

    if (host.isNull()) {
        host.getCharChunk().append(defaultHostName);
    }
    host.toChars();
    uri.toChars();
    internalMap(host.getCharChunk(), uri.getCharChunk(), version,
            mappingData);

}
 
Example #13
Source File: AbstractOutputBuffer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * This method will write the contents of the specified message bytes 
 * buffer to the output stream, without filtering. This method is meant to
 * be used to write the response header.
 * 
 * @param mb data to be written
 */
protected void write(MessageBytes mb) {

    if (mb.getType() == MessageBytes.T_BYTES) {
        ByteChunk bc = mb.getByteChunk();
        write(bc);
    } else if (mb.getType() == MessageBytes.T_CHARS) {
        CharChunk cc = mb.getCharChunk();
        write(cc);
    } else {
        write(mb.toString());
    }

}
 
Example #14
Source File: TestCoyoteAdapter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void doTestNormalize(String input, String expected) {
    MessageBytes mb = MessageBytes.newInstance();
    byte[] b = input.getBytes(StandardCharsets.UTF_8);
    mb.setBytes(b, 0, b.length);

    boolean result = CoyoteAdapter.normalize(mb);
    mb.toString();

    if (expected == null) {
        Assert.assertFalse(result);
    } else {
        Assert.assertTrue(result);
        Assert.assertEquals(expected, mb.toString());
    }
}
 
Example #15
Source File: Parameters.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
public void processParameters( MessageBytes data, String encoding ) {
    if( data==null || data.isNull() || data.getLength() <= 0 ) {
        return;
    }

    if( data.getType() != MessageBytes.T_BYTES ) {
        data.toBytes();
    }
    ByteChunk bc=data.getByteChunk();
    processParameters( bc.getBytes(), bc.getOffset(),
                       bc.getLength(), getCharset(encoding));
}
 
Example #16
Source File: MimeHeaders.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Finds and returns a unique header field with the given name. If no such
 * field exists, null is returned. If the specified header field is not
 * unique then an {@link IllegalArgumentException} is thrown.
 */
public MessageBytes getUniqueValue(String name) {
    MessageBytes result = null;
    for (int i = 0; i < count; i++) {
        if (headers[i].getName().equalsIgnoreCase(name)) {
            if (result == null) {
                result = headers[i].getValue();
            } else {
                throw new IllegalArgumentException();
            }
        }
    }
    return result;
}
 
Example #17
Source File: AbstractOutputBuffer.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Send a header.
 * 
 * @param name Header name
 * @param value Header value
 */
public void sendHeader(MessageBytes name, MessageBytes value) {

    write(name);
    buf[pos++] = Constants.COLON;
    buf[pos++] = Constants.SP;
    write(value);
    buf[pos++] = Constants.CR;
    buf[pos++] = Constants.LF;

}
 
Example #18
Source File: AbstractHttp11Processor.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private boolean isConnectionClose(MimeHeaders headers) {
    MessageBytes connection = headers.getValue(Constants.CONNECTION);
    if (connection == null) {
        return false;
    }
    return connection.equals(Constants.CLOSE);
}
 
Example #19
Source File: MimeHeaders.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private void findNext() {
    next=null;
    for(; pos< size; pos++ ) {
        MessageBytes n1=headers.getName( pos );
        if( n1.equalsIgnoreCase( name )) {
            next=headers.getValue( pos );
            break;
        }
    }
    pos++;
}
 
Example #20
Source File: AbstractHttp11Processor.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the resource could be compressed, if the client supports it.
 */
private boolean isCompressable() {

    // Check if content is not already gzipped
    MessageBytes contentEncodingMB =
        response.getMimeHeaders().getValue("Content-Encoding");

    if ((contentEncodingMB != null)
        && (contentEncodingMB.indexOf("gzip") != -1)) {
        return false;
    }

    // If force mode, always compress (test purposes only)
    if (compressionLevel == 2) {
        return true;
    }

    // Check if sufficient length to trigger the compression
    long contentLength = response.getContentLengthLong();
    if ((contentLength == -1)
        || (contentLength > compressionMinSize)) {
        // Check for compatible MIME-TYPE
        if (compressableMimeTypes != null) {
            return (startsWithStringArray(compressableMimeTypes,
                                          response.getContentType()));
        }
    }

    return false;
}
 
Example #21
Source File: Mapper.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Map the specified URI relative to the context,
 * mutating the given mapping data.
 *
 * @param uri URI
 * @param mappingData This structure will contain the result of the mapping
 *                    operation
 */
public void map(MessageBytes uri, MappingData mappingData)
    throws Exception {

    uri.toChars();
    CharChunk uricc = uri.getCharChunk();
    uricc.setLimit(-1);
    internalMapWrapper(context, uricc, mappingData);

}
 
Example #22
Source File: Rfc6265CookieProcessor.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void parseCookieHeader(MimeHeaders headers,
        ServerCookies serverCookies) {

    if (headers == null) {
        // nothing to process
        return;
    }

    // process each "cookie" header
    int pos = headers.findHeader("Cookie", 0);
    while (pos >= 0) {
        MessageBytes cookieValue = headers.getValue(pos);

        if (cookieValue != null && !cookieValue.isNull() ) {
            if (cookieValue.getType() != MessageBytes.T_BYTES ) {
                if (log.isDebugEnabled()) {
                    Exception e = new Exception();
                    // TODO: Review this in light of HTTP/2
                    log.debug("Cookies: Parsing cookie as String. Expected bytes.", e);
                }
                cookieValue.toBytes();
            }
            if (log.isDebugEnabled()) {
                log.debug("Cookies: Parsing b[]: " + cookieValue.toString());
            }
            ByteChunk bc = cookieValue.getByteChunk();

            Cookie.parseCookie(bc.getBytes(), bc.getOffset(), bc.getLength(),
                    serverCookies);
        }

        // search from the next position
        pos = headers.findHeader("Cookie", ++pos);
    }
}
 
Example #23
Source File: MimeHeaders.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/** Create a new named header using un-translated byte[].
    The conversion to chars can be delayed until
    encoding is known.
 */
public MessageBytes addValue(byte b[], int startN, int len)
{
    MimeHeaderField mhf=createHeader();
    mhf.getName().setBytes(b, startN, len);
    return mhf.getValue();
}
 
Example #24
Source File: ApplicationHttpRequest.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Merge the parameters from the saved query parameter string (if any), and
 * the parameters already present on this request (if any), such that the
 * parameter values from the query string show up first if there are
 * duplicate parameter names.
 */
private void mergeParameters() {

    if ((queryParamString == null) || (queryParamString.length() < 1))
        return;

    // Parse the query string from the dispatch target
    Parameters paramParser = new Parameters();
    MessageBytes queryMB = MessageBytes.newInstance();
    queryMB.setString(queryParamString);

    String encoding = getCharacterEncoding();
    // No need to process null value, as ISO-8859-1 is the default encoding
    // in MessageBytes.toBytes().
    if (encoding != null) {
        try {
            queryMB.setCharset(B2CConverter.getCharset(encoding));
        } catch (UnsupportedEncodingException ignored) {
            // Fall-back to ISO-8859-1
        }
    }

    paramParser.setQuery(queryMB);
    paramParser.setQueryStringEncoding(encoding);
    paramParser.handleQueryParameters();

    // Insert the additional parameters from the dispatch target
    Enumeration<String> dispParamNames = paramParser.getParameterNames();
    while (dispParamNames.hasMoreElements()) {
        String dispParamName = dispParamNames.nextElement();
        String[] dispParamValues = paramParser.getParameterValues(dispParamName);
        String[] originalValues = parameters.get(dispParamName);
        if (originalValues == null) {
            parameters.put(dispParamName, dispParamValues);
            continue;
        }
        parameters.put(dispParamName, mergeValues(dispParamValues, originalValues));
    }
}
 
Example #25
Source File: MimeHeaders.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/** Create a new named header using un-translated byte[].
    The conversion to chars can be delayed until
    encoding is known.
 */
public MessageBytes addValue(byte b[], int startN, int len)
{
    MimeHeaderField mhf=createHeader();
    mhf.getName().setBytes(b, startN, len);
    return mhf.getValue();
}
 
Example #26
Source File: Parameters.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public void processParameters(MessageBytes data, Charset charset) {
    if( data==null || data.isNull() || data.getLength() <= 0 ) {
        return;
    }

    if( data.getType() != MessageBytes.T_BYTES ) {
        data.toBytes();
    }
    ByteChunk bc=data.getByteChunk();
    processParameters(bc.getBytes(), bc.getOffset(), bc.getLength(), charset);
}
 
Example #27
Source File: OAuthAuthenticator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
private String getBearerToken(org.apache.catalina.connector.Request request) {
    MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("Authorization");

    String tokenValue = null;
    if (authorization != null) {
        authorization.toBytes();
        ByteChunk authBC = authorization.getByteChunk();
        tokenValue = authBC.toString();
        Matcher matcher = PATTERN.matcher(tokenValue);
        if (matcher.find()) {
            tokenValue = tokenValue.substring(matcher.end());
        }
    }
    return tokenValue;
}
 
Example #28
Source File: MimeHeaders.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Finds and returns a header field with the given name.  If no such
 * field exists, null is returned.  If more than one such field is
 * in the header, an arbitrary one is returned.
 * @param name The header name
 * @return the value
 */
public MessageBytes getValue(String name) {
    for (int i = 0; i < count; i++) {
        if (headers[i].getName().equalsIgnoreCase(name)) {
            return headers[i].getValue();
        }
    }
    return null;
}
 
Example #29
Source File: MimeHeaders.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Finds and returns a unique header field with the given name. If no such
 * field exists, null is returned. If the specified header field is not
 * unique then an {@link IllegalArgumentException} is thrown.
 * @param name The header name
 * @return the value if unique
 * @throws IllegalArgumentException if the header has multiple values
 */
public MessageBytes getUniqueValue(String name) {
    MessageBytes result = null;
    for (int i = 0; i < count; i++) {
        if (headers[i].getName().equalsIgnoreCase(name)) {
            if (result == null) {
                result = headers[i].getValue();
            } else {
                throw new IllegalArgumentException();
            }
        }
    }
    return result;
}
 
Example #30
Source File: MimeHeaders.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void findNext() {
    next=null;
    for(; pos< size; pos++ ) {
        MessageBytes n1=headers.getName( pos );
        if( n1.equalsIgnoreCase( name )) {
            next=headers.getValue( pos );
            break;
        }
    }
    pos++;
}