Java Code Examples for org.apache.tomcat.util.buf.MessageBytes#getByteChunk()

The following examples show how to use org.apache.tomcat.util.buf.MessageBytes#getByteChunk() . 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: AjpMessage.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Write a MessageBytes out at the current write position.
 * A null MessageBytes is encoded as a string with length 0.  
 */
public void appendBytes(MessageBytes mb) {
    if (mb == null) {
        log.error(sm.getString("ajpmessage.null"), 
                new NullPointerException());
        appendInt(0);
        appendByte(0);
        return;
    }
    if (mb.getType() == MessageBytes.T_BYTES) {
        ByteChunk bc = mb.getByteChunk();
        appendByteChunk(bc);
    } else if (mb.getType() == MessageBytes.T_CHARS) {
        CharChunk cc = mb.getCharChunk();
        appendCharChunk(cc);
    } else {
        appendString(mb.toString());
    }
}
 
Example 3
Source File: CoyoteAdapter.java    From Tomcat7.0.67 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 4
Source File: BasicAuthAuthenticator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canHandle(Request request) {
    /*
    This is done to avoid every endpoint being able to use basic auth. Add the following to
    the required web.xml of the web app.
    <context-param>
        <param-name>basicAuth</param-name>
        <param-value>true</param-value>
 </context-param>
     */
    if (!isAuthenticationSupported(request)) {
        return false;
    }
    if (request.getCoyoteRequest() == null || request.getCoyoteRequest().getMimeHeaders() == null) {
        return false;
    }
    MessageBytes authorization =
            request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
    if (authorization != null) {
        authorization.toBytes();
        ByteChunk authBC = authorization.getByteChunk();
        if (authBC.startsWithIgnoreCase(AUTH_HEADER, 0)) {
            return true;
        }
    }
    return false;
}
 
Example 5
Source File: AjpMessage.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Write a MessageBytes out at the current write position. A null
 * MessageBytes is encoded as a string with length 0.
 *
 * @param mb The data to write
 */
public void appendBytes(MessageBytes mb) {
    if (mb == null) {
        log.error(sm.getString("ajpmessage.null"),
                new NullPointerException());
        appendInt(0);
        appendByte(0);
        return;
    }
    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] = ' ';
            }
        }
    }
    appendByteChunk(mb.getByteChunk());
}
 
Example 6
Source File: Parameters.java    From tomcatsrc 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 7
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 8
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 9
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 10
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 11
Source File: OAuthAuthenticator.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public boolean canHandle(org.apache.catalina.connector.Request request) {
    MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("Authorization");
    if (authorization != null) {
        authorization.toBytes();
        ByteChunk authBC = authorization.getByteChunk();
        String tokenValue = authBC.toString();
        Matcher matcher = PATTERN.matcher(tokenValue);
        if (matcher.find()) {
            return true;
        }
    }
    return false;
}
 
Example 12
Source File: BasicAuthenticator.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean authenticate(Request request,
                            HttpServletResponse response,
                            LoginConfig config)
    throws IOException {

    if (checkForCachedAuthentication(request, response, true)) {
        return true;
    }

    // Validate any credentials already included with this request
    String username = null;
    String password = null;

    MessageBytes authorization = 
        request.getCoyoteRequest().getMimeHeaders()
        .getValue("authorization");
    
    if (authorization != null) {
        authorization.toBytes();
        ByteChunk authorizationBC = authorization.getByteChunk();
        if (authorizationBC.startsWithIgnoreCase("basic ", 0)) {
            authorizationBC.setOffset(authorizationBC.getOffset() + 6);
            
            byte[] decoded = Base64.decodeBase64(
                    authorizationBC.getBuffer(),
                    authorizationBC.getOffset(),
                    authorizationBC.getLength());
            
            // Get username and password
            int colon = -1;
            for (int i = 0; i < decoded.length; i++) {
                if (decoded[i] == ':') {
                    colon = i;
                    break;
                }
            }

            if (colon < 0) {
                username = new String(decoded, B2CConverter.ISO_8859_1);
            } else {
                username = new String(
                        decoded, 0, colon, B2CConverter.ISO_8859_1);
                password = new String(
                        decoded, colon + 1, decoded.length - colon - 1,
                        B2CConverter.ISO_8859_1);
            }
            
            authorizationBC.setOffset(authorizationBC.getOffset() - 6);
        }

        Principal principal = context.getRealm().authenticate(username, password);
        if (principal != null) {
            register(request, response, principal,
                    HttpServletRequest.BASIC_AUTH, username, password);
            return (true);
        }
    }
    
    StringBuilder value = new StringBuilder(16);
    value.append("Basic realm=\"");
    if (config.getRealmName() == null) {
        value.append(REALM_NAME);
    } else {
        value.append(config.getRealmName());
    }
    value.append('\"');        
    response.setHeader(AUTH_HEADER_NAME, value.toString());
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return (false);

}
 
Example 13
Source File: AbstractAjpProcessor.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Parse host.
 */
protected void parseHost(MessageBytes valueMB) {

    if (valueMB == null || valueMB.isNull()) {
        // HTTP/1.0
        request.setServerPort(request.getLocalPort());
        try {
            request.serverName().duplicate(request.localName());
        } catch (IOException e) {
            response.setStatus(400);
            setErrorState(ErrorState.CLOSE_CLEAN, e);
        }
        return;
    }

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

    boolean ipv6 = (valueB[valueS] == '[');
    boolean bracketClosed = false;
    for (int i = 0; i < valueL; i++) {
        char b = (char) valueB[i + valueS];
        hostNameC[i] = b;
        if (b == ']') {
            bracketClosed = true;
        } else if (b == ':') {
            if (!ipv6 || bracketClosed) {
                colonPos = i;
                break;
            }
        }
    }

    if (colonPos < 0) {
        if (request.scheme().equalsIgnoreCase("https")) {
            // 443 - Default HTTPS port
            request.setServerPort(443);
        } else {
            // 80 - Default HTTTP port
            request.setServerPort(80);
        }
        request.serverName().setChars(hostNameC, 0, valueL);
    } else {

        request.serverName().setChars(hostNameC, 0, colonPos);

        int port = 0;
        int mult = 1;
        for (int i = valueL - 1; i > colonPos; i--) {
            int charValue = HexUtils.getDec(valueB[i + valueS]);
            if (charValue == -1) {
                // Invalid character
                // 400 - Bad request
                response.setStatus(400);
                setErrorState(ErrorState.CLOSE_CLEAN, null);
                break;
            }
            port = port + (charValue * mult);
            mult = 10 * mult;
        }
        request.setServerPort(port);
    }
}
 
Example 14
Source File: AbstractHttp11Processor.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Parse host.
 */
protected void parseHost(MessageBytes valueMB) {

    if (valueMB == null || valueMB.isNull()) {
        // HTTP/1.0
        // If no host header, use the port info from the endpoint
        // The host will be obtained lazily from the socket if required
        // using ActionCode#REQ_LOCAL_NAME_ATTRIBUTE
        request.setServerPort(endpoint.getPort());
        return;
    }

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

    boolean ipv6 = (valueB[valueS] == '[');
    boolean bracketClosed = false;
    for (int i = 0; i < valueL; i++) {
        char b = (char) valueB[i + valueS];
        hostNameC[i] = b;
        if (b == ']') {
            bracketClosed = true;
        } else if (b == ':') {
            if (!ipv6 || bracketClosed) {
                colonPos = i;
                break;
            }
        }
    }

    if (colonPos < 0) {
        if (!endpoint.isSSLEnabled()) {
            // 80 - Default HTTP port
            request.setServerPort(80);
        } else {
            // 443 - Default HTTPS port
            request.setServerPort(443);
        }
        request.serverName().setChars(hostNameC, 0, valueL);
    } else {
        request.serverName().setChars(hostNameC, 0, colonPos);

        int port = 0;
        int mult = 1;
        for (int i = valueL - 1; i > colonPos; i--) {
            int charValue = HexUtils.getDec(valueB[i + valueS]);
            if (charValue == -1 || charValue > 9) {
                // Invalid character
                // 400 - Bad request
                response.setStatus(400);
                setErrorState(ErrorState.CLOSE_CLEAN, null);
                break;
            }
            port = port + (charValue * mult);
            mult = 10 * mult;
        }
        request.setServerPort(port);
    }

}
 
Example 15
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 16
Source File: BasicAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config    Login configuration describing how authentication
 *              should be performed
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean authenticate(Request request,
                            HttpServletResponse response,
                            LoginConfig config)
    throws IOException {

    if (checkForCachedAuthentication(request, response, true)) {
        return true;
    }

    // Validate any credentials already included with this request
    String username = null;
    String password = null;

    MessageBytes authorization = 
        request.getCoyoteRequest().getMimeHeaders()
        .getValue("authorization");
    
    if (authorization != null) {
        authorization.toBytes();
        ByteChunk authorizationBC = authorization.getByteChunk();
        if (authorizationBC.startsWithIgnoreCase("basic ", 0)) {
            authorizationBC.setOffset(authorizationBC.getOffset() + 6);
            
            byte[] decoded = Base64.decodeBase64(
                    authorizationBC.getBuffer(),
                    authorizationBC.getOffset(),
                    authorizationBC.getLength());
            
            // Get username and password
            int colon = -1;
            for (int i = 0; i < decoded.length; i++) {
                if (decoded[i] == ':') {
                    colon = i;
                    break;
                }
            }

            if (colon < 0) {
                username = new String(decoded, B2CConverter.ISO_8859_1);
            } else {
                username = new String(
                        decoded, 0, colon, B2CConverter.ISO_8859_1);
                password = new String(
                        decoded, colon + 1, decoded.length - colon - 1,
                        B2CConverter.ISO_8859_1);
            }
            
            authorizationBC.setOffset(authorizationBC.getOffset() - 6);
        }

        Principal principal = context.getRealm().authenticate(username, password);
        if (principal != null) {
            register(request, response, principal,
                    HttpServletRequest.BASIC_AUTH, username, password);
            return (true);
        }
    }
    
    StringBuilder value = new StringBuilder(16);
    value.append("Basic realm=\"");
    if (config.getRealmName() == null) {
        value.append(REALM_NAME);
    } else {
        value.append(config.getRealmName());
    }
    value.append('\"');        
    response.setHeader(AUTH_HEADER_NAME, value.toString());
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return (false);

}
 
Example 17
Source File: AbstractHttp11Processor.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Parse host.
 */
protected void parseHost(MessageBytes valueMB) {

    if (valueMB == null || valueMB.isNull()) {
        // HTTP/1.0
        // If no host header, use the port info from the endpoint
        // The host will be obtained lazily from the socket if required
        // using ActionCode#REQ_LOCAL_NAME_ATTRIBUTE
        request.setServerPort(endpoint.getPort());
        return;
    }

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

    boolean ipv6 = (valueB[valueS] == '[');
    boolean bracketClosed = false;
    for (int i = 0; i < valueL; i++) {
        char b = (char) valueB[i + valueS];
        hostNameC[i] = b;
        if (b == ']') {
            bracketClosed = true;
        } else if (b == ':') {
            if (!ipv6 || bracketClosed) {
                colonPos = i;
                break;
            }
        }
    }

    if (colonPos < 0) {
        if (!endpoint.isSSLEnabled()) {
            // 80 - Default HTTP port
            request.setServerPort(80);
        } else {
            // 443 - Default HTTPS port
            request.setServerPort(443);
        }
        request.serverName().setChars(hostNameC, 0, valueL);
    } else {
        request.serverName().setChars(hostNameC, 0, colonPos);

        int port = 0;
        int mult = 1;
        for (int i = valueL - 1; i > colonPos; i--) {
            int charValue = HexUtils.getDec(valueB[i + valueS]);
            if (charValue == -1 || charValue > 9) {
                // Invalid character
                // 400 - Bad request
                response.setStatus(400);
                setErrorState(ErrorState.CLOSE_CLEAN, null);
                break;
            }
            port = port + (charValue * mult);
            mult = 10 * mult;
        }
        request.setServerPort(port);
    }

}
 
Example 18
Source File: Host.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public MessageBytesReader(MessageBytes mb) {
    ByteChunk bc = mb.getByteChunk();
    bytes = bc.getBytes();
    pos = bc.getOffset();
    end = bc.getEnd();
}
 
Example 19
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);
    }
}
 
Example 20
Source File: BasicAuthenticator.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
protected boolean doAuthenticate(Request request, HttpServletResponse response)
        throws IOException {

    if (checkForCachedAuthentication(request, response, true)) {
        return true;
    }

    // Validate any credentials already included with this request
    MessageBytes authorization =
        request.getCoyoteRequest().getMimeHeaders()
        .getValue("authorization");

    if (authorization != null) {
        authorization.toBytes();
        ByteChunk authorizationBC = authorization.getByteChunk();
        BasicCredentials credentials = null;
        try {
            credentials = new BasicCredentials(authorizationBC, charset, getTrimCredentials());
            String username = credentials.getUsername();
            String password = credentials.getPassword();

            Principal principal = context.getRealm().authenticate(username, password);
            if (principal != null) {
                register(request, response, principal,
                    HttpServletRequest.BASIC_AUTH, username, password);
                return true;
            }
        }
        catch (IllegalArgumentException iae) {
            if (log.isDebugEnabled()) {
                log.debug("Invalid Authorization" + iae.getMessage());
            }
        }
    }

    // the request could not be authenticated, so reissue the challenge
    StringBuilder value = new StringBuilder(16);
    value.append("Basic realm=\"");
    value.append(getRealmName(context));
    value.append('\"');
    if (charsetString != null && !charsetString.isEmpty()) {
        value.append(", charset=");
        value.append(charsetString);
    }
    response.setHeader(AUTH_HEADER_NAME, value.toString());
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return false;

}