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

The following examples show how to use org.apache.tomcat.util.buf.ByteChunk#recycle() . 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: IdentityOutputFilter.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 int doWrite(ByteChunk chunk) 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);
        } 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);
        result = chunk.getLength();
    }

    return result;

}
 
Example 2
Source File: IdentityInputFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Read bytes.
 * 
 * @return If the filter does request length control, this value is
 * significant; it should be the number of bytes consumed from the buffer,
 * up until the end of the current request body, or the buffer length, 
 * whichever is greater. If the filter does not do request body length
 * control, the returned value should be -1.
 */
@Override
public int doRead(ByteChunk chunk, Request req)
    throws IOException {

    int result = -1;

    if (contentLength >= 0) {
        if (remaining > 0) {
            int nRead = buffer.doRead(chunk, req);
            if (nRead > 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;
            } else {
                result = nRead;
            }
            if (nRead > 0) {
                remaining = remaining - nRead;
            }
        } else {
            // No more bytes left to be read : return -1 and clear the 
            // buffer
            chunk.recycle();
            result = -1;
        }
    }

    return result;

}
 
Example 3
Source File: TestOutputBuffer.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteSpeed() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    for (int i = 1; i <= WritingServlet.EXPECTED_CONTENT_LENGTH; i*=10) {
        WritingServlet servlet = new WritingServlet(i);
        Tomcat.addServlet(root, "servlet" + i, servlet);
        root.addServletMapping("/servlet" + i, "servlet" + i);
    }

    tomcat.start();

    ByteChunk bc = new ByteChunk();

    for (int i = 1; i <= WritingServlet.EXPECTED_CONTENT_LENGTH; i*=10) {
        int rc = getUrl("http://localhost:" + getPort() +
                "/servlet" + i, bc, null, null);
        assertEquals(HttpServletResponse.SC_OK, rc);
        assertEquals(
                WritingServlet.EXPECTED_CONTENT_LENGTH, bc.getLength());

        bc.recycle();

        rc = getUrl("http://localhost:" + getPort() +
                "/servlet" + i + "?useBuffer=y", bc, null, null);
        assertEquals(HttpServletResponse.SC_OK, rc);
        assertEquals(
                WritingServlet.EXPECTED_CONTENT_LENGTH, bc.getLength());

        bc.recycle();
    }
}
 
Example 4
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 5
Source File: TestJspDocumentParser.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug54801() throws Exception {
    getTomcatInstanceTestWebapp(false, true);

    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() +
            "/test/bug5nnnn/bug54801a.jspx", bc, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    bc.recycle();
    rc = getUrl("http://localhost:" + getPort() +
            "/test/bug5nnnn/bug54801b.jspx", bc, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
}
 
Example 6
Source File: TestHttpServlet.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the same Content-Length is returned for both GET and HEAD
 * operations when a Servlet includes content from another Servlet
 */
@Test
public void testBug57602() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    Bug57602ServletOuter outer = new Bug57602ServletOuter();
    Tomcat.addServlet(ctx, "Bug57602ServletOuter", outer);
    ctx.addServletMapping("/outer", "Bug57602ServletOuter");

    Bug57602ServletInner inner = new Bug57602ServletInner();
    Tomcat.addServlet(ctx, "Bug57602ServletInner", inner);
    ctx.addServletMapping("/inner", "Bug57602ServletInner");

    tomcat.start();

    Map<String,List<String>> resHeaders= new HashMap<String,List<String>>();
    String path = "http://localhost:" + getPort() + "/outer";
    ByteChunk out = new ByteChunk();

    int rc = getUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    String length = resHeaders.get("Content-Length").get(0);
    Assert.assertEquals(Long.parseLong(length), out.getLength());
    out.recycle();

    rc = headUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertEquals(0, out.getLength());
    Assert.assertEquals(length, resHeaders.get("Content-Length").get(0));

    tomcat.stop();
}
 
Example 7
Source File: TestConnector.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testStop() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Context root = tomcat.addContext("", TEMP_DIR);
    Wrapper w =
        Tomcat.addServlet(root, "tester", new TesterServlet());
    w.setAsyncSupported(true);
    root.addServletMappingDecoded("/", "tester");

    Connector connector = tomcat.getConnector();

    tomcat.start();

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

    Assert.assertEquals(200, rc);
    Assert.assertEquals("OK", bc.toString());

    rc = -1;
    bc.recycle();

    connector.stop();

    try {
        rc = getUrl("http://localhost:" + getPort() + "/", bc, 1000,
                null, null);
    } catch (SocketTimeoutException ste) {
        // May also see this with NIO
        // Make sure the test passes if we do
        rc = 503;
    }
    Assert.assertEquals(503, rc);
}
 
Example 8
Source File: TestOutputBuffer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testWriteSpeed() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Context root = tomcat.addContext("", TEMP_DIR);

    for (int i = 1; i <= WritingServlet.EXPECTED_CONTENT_LENGTH; i*=10) {
        WritingServlet servlet = new WritingServlet(i);
        Tomcat.addServlet(root, "servlet" + i, servlet);
        root.addServletMappingDecoded("/servlet" + i, "servlet" + i);
    }

    tomcat.start();

    ByteChunk bc = new ByteChunk();

    for (int i = 1; i <= WritingServlet.EXPECTED_CONTENT_LENGTH; i*=10) {
        int rc = getUrl("http://localhost:" + getPort() +
                "/servlet" + i, bc, null, null);
        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
        Assert.assertEquals(
                WritingServlet.EXPECTED_CONTENT_LENGTH, bc.getLength());

        bc.recycle();

        rc = getUrl("http://localhost:" + getPort() +
                "/servlet" + i + "?useBuffer=y", bc, null, null);
        Assert.assertEquals(HttpServletResponse.SC_OK, rc);
        Assert.assertEquals(
                WritingServlet.EXPECTED_CONTENT_LENGTH, bc.getLength());

        bc.recycle();
    }
}
 
Example 9
Source File: TestDefaultServlet.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the same Content-Length is returned for both GET and HEAD
 * operations when a static resource served by the DefaultServlet is
 * included.
 */
@Test
public void testBug57601() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    
    File appDir = new File("test/webapp-3.0");
    tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());

    tomcat.start();
    
    Map<String,List<String>> resHeaders= new HashMap<String,List<String>>();
    String path = "http://localhost:" + getPort() + "/test/bug5nnnn/bug57601.jsp";
    ByteChunk out = new ByteChunk();

    int rc = getUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    String length = resHeaders.get("Content-Length").get(0);
    Assert.assertEquals(Long.parseLong(length), out.getLength());
    out.recycle();

    rc = headUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertEquals(0, out.getLength());
    Assert.assertEquals(length, resHeaders.get("Content-Length").get(0));

    tomcat.stop();
}
 
Example 10
Source File: TestHttpServlet.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the same Content-Length is returned for both GET and HEAD
 * operations when a Servlet includes content from another Servlet
 */
@Test
public void testBug57602() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    Bug57602ServletOuter outer = new Bug57602ServletOuter();
    Tomcat.addServlet(ctx, "Bug57602ServletOuter", outer);
    ctx.addServletMapping("/outer", "Bug57602ServletOuter");

    Bug57602ServletInner inner = new Bug57602ServletInner();
    Tomcat.addServlet(ctx, "Bug57602ServletInner", inner);
    ctx.addServletMapping("/inner", "Bug57602ServletInner");

    tomcat.start();

    Map<String,List<String>> resHeaders= new HashMap<String,List<String>>();
    String path = "http://localhost:" + getPort() + "/outer";
    ByteChunk out = new ByteChunk();

    int rc = getUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    String length = resHeaders.get("Content-Length").get(0);
    Assert.assertEquals(Long.parseLong(length), out.getLength());
    out.recycle();

    rc = headUrl(path, out, resHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertEquals(0, out.getLength());
    Assert.assertEquals(length, resHeaders.get("Content-Length").get(0));

    tomcat.stop();
}
 
Example 11
Source File: TestSSOnonLoginAndDigestAuthenticator.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public void doTestDigest(String user, String pwd, String uri,
        boolean expectedReject1, int expectedRC1,
        boolean useServerNonce, boolean useServerOpaque,
        String nc1, String cnonce,
        String qop, boolean req2expect200)
        throws Exception {

    String digestUri= uri;

    List<String> auth = new ArrayList<>();
    Map<String,List<String>> reqHeaders1 = new HashMap<>();
    Map<String,List<String>> respHeaders1 = new HashMap<>();

    // the first access attempt should be challenged
    auth.add(buildDigestResponse(user, pwd, digestUri, REALM, "null",
            "null", nc1, cnonce, qop));
    reqHeaders1.put(CLIENT_AUTH_HEADER, auth);

    ByteChunk bc = new ByteChunk();
    int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders1,
            respHeaders1);

    if (expectedReject1) {
        Assert.assertEquals(expectedRC1, rc);
        Assert.assertTrue(bc.getLength() > 0);
    }
    else {
        Assert.assertEquals(200, rc);
        Assert.assertEquals("OK", bc.toString());
        saveCookies(respHeaders1);
        return;
    }

    // Second request should succeed (if we use the server nonce)
    Map<String,List<String>> reqHeaders2 = new HashMap<>();
    Map<String,List<String>> respHeaders2 = new HashMap<>();

    auth.clear();
    if (useServerNonce) {
        if (useServerOpaque) {
            auth.add(buildDigestResponse(user, pwd, digestUri,
                    getAuthToken(respHeaders1, REALM),
                    getAuthToken(respHeaders1, NONCE),
                    getAuthToken(respHeaders1, OPAQUE),
                    nc1, cnonce, qop));
        } else {
            auth.add(buildDigestResponse(user, pwd, digestUri,
                    getAuthToken(respHeaders1, REALM),
                    getAuthToken(respHeaders1, NONCE),
                    "null", nc1, cnonce, qop));
        }
    } else {
        auth.add(buildDigestResponse(user, pwd, digestUri,
                getAuthToken(respHeaders2, REALM),
                "null", getAuthToken(respHeaders1, OPAQUE),
                nc1, cnonce, QOP));
    }
    reqHeaders2.put(CLIENT_AUTH_HEADER, auth);

    bc.recycle();
    rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders2,
            respHeaders2);

    if (req2expect200) {
        Assert.assertEquals(200, rc);
        Assert.assertEquals("OK", bc.toString());
        saveCookies(respHeaders2);
    } else {
        Assert.assertEquals(401, rc);
        Assert.assertTrue((bc.getLength() > 0));
    }
}
 
Example 12
Source File: TestDefaultServlet.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
public static int getUrl(String path, ByteChunk out,
        Map<String, List<String>> resHead) throws IOException {
    out.recycle();
    return TomcatBaseTest.getUrl(path, out, resHead);
}
 
Example 13
Source File: TestClientCert.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTestClientCertPost(int bodySize, boolean expectProtectedFail)
        throws Exception {
    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isRenegotiationSupported(getTomcatInstance()));

    getTomcatInstance().start();

    byte[] body = new byte[bodySize];
    Arrays.fill(body, TesterSupport.DATA);

    // Unprotected resource
    ByteChunk res = postUrl(body, "https://localhost:" + getPort() + "/unprotected");

    int count = TesterSupport.getLastClientAuthRequestedIssuerCount();
    if (log.isDebugEnabled()) {
        log.debug("Last client KeyManager usage: " + TesterSupport.getLastClientAuthKeyManagerUsage() +
                  ", " + count + " requested Issuers, first one: " +
                  (count > 0 ? TesterSupport.getLastClientAuthRequestedIssuer(0).getName() : "NONE"));
        log.debug("Expected requested Issuer: NONE");
    }

    // Unprotected resource with no preemptive authentication
    Assert.assertEquals(0, count);
    // No authentication no need to buffer POST body during TLS handshake so
    // no possibility of hitting buffer limit
    Assert.assertEquals("OK-" + bodySize, res.toString());

    // Protected resource
    res.recycle();
    int rc = postUrl(body, "https://localhost:" + getPort() + "/protected", res, null);

    count = TesterSupport.getLastClientAuthRequestedIssuerCount();
    if (log.isDebugEnabled()) {
        log.debug("Last client KeyManager usage: " + TesterSupport.getLastClientAuthKeyManagerUsage() +
                  ", " + count + " requested Issuers, first one: " +
                  (count > 0 ? TesterSupport.getLastClientAuthRequestedIssuer(0).getName() : "NONE"));
        log.debug("Expected requested Issuer: " + TesterSupport.getClientAuthExpectedIssuer());
    }

    if (expectProtectedFail) {
        Assert.assertEquals(401, rc);
        // POST body buffer fails so TLS handshake never happens
        Assert.assertEquals(0, count);
    } else {
        Assert.assertTrue("Checking requested client issuer against " +
                TesterSupport.getClientAuthExpectedIssuer(),
                TesterSupport.checkLastClientAuthRequestedIssuers());
        Assert.assertEquals("OK-" + bodySize, res.toString());
    }
}
 
Example 14
Source File: TestCustomSsl.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTestCustomTrustManager(TrustType trustType)
        throws Exception {

    Tomcat tomcat = getTomcatInstance();

    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isRenegotiationSupported(getTomcatInstance()));

    TesterSupport.configureClientCertContext(tomcat);

    // Override the defaults
    ProtocolHandler handler = tomcat.getConnector().getProtocolHandler();
    if (handler instanceof AbstractHttp11JsseProtocol) {
        ((AbstractHttp11JsseProtocol<?>) handler).setTruststoreFile(null);
    } else {
        // Unexpected
        Assert.fail("Unexpected handler type");
    }
    if (trustType.equals(TrustType.ALL)) {
        tomcat.getConnector().setAttribute("trustManagerClassName",
                "org.apache.tomcat.util.net.TesterSupport$TrustAllCerts");
    } else if (trustType.equals(TrustType.CA)) {
        tomcat.getConnector().setAttribute("trustManagerClassName",
                "org.apache.tomcat.util.net.TesterSupport$SequentialTrustManager");
    }

    // Start Tomcat
    tomcat.start();

    TesterSupport.configureClientSsl();

    // Unprotected resource
    ByteChunk res =
            getUrl("https://localhost:" + getPort() + "/unprotected");
    Assert.assertEquals("OK", res.toString());

    // Protected resource
    res.recycle();
    int rc = -1;
    try {
        rc = getUrl("https://localhost:" + getPort() + "/protected", res,
            null, null);
    } catch (SocketException se) {
        if (!trustType.equals(TrustType.NONE)) {
            Assert.fail(se.getMessage());
            se.printStackTrace();
        }
    } catch (SSLException he) {
        if (!trustType.equals(TrustType.NONE)) {
            Assert.fail(he.getMessage());
            he.printStackTrace();
        }
    }

    if (trustType.equals(TrustType.CA)) {
        if (log.isDebugEnabled()) {
            int count = TesterSupport.getLastClientAuthRequestedIssuerCount();
            log.debug("Last client KeyManager usage: " + TesterSupport.getLastClientAuthKeyManagerUsage() +
                      ", " + count + " requested Issuers, first one: " +
                      (count > 0 ? TesterSupport.getLastClientAuthRequestedIssuer(0).getName() : "NONE"));
            log.debug("Expected requested Issuer: " + TesterSupport.getClientAuthExpectedIssuer());
        }
        Assert.assertTrue("Checking requested client issuer against " +
                TesterSupport.getClientAuthExpectedIssuer(),
                TesterSupport.checkLastClientAuthRequestedIssuers());
    }

    if (trustType.equals(TrustType.NONE)) {
        Assert.assertTrue(rc != 200);
        Assert.assertEquals("", res.toString());
    } else {
        Assert.assertEquals(200, rc);
        Assert.assertEquals("OK-" + TesterSupport.ROLE, res.toString());
    }
}
 
Example 15
Source File: TestDefaultServlet.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
public static int getUrl(String path, ByteChunk out,
        Map<String, List<String>> resHead) throws IOException {
    out.recycle();
    return TomcatBaseTest.getUrl(path, out, resHead);
}
 
Example 16
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug54178() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Bug54178ServletA bug54178ServletA = new Bug54178ServletA();
    Wrapper wrapper =
        Tomcat.addServlet(ctx, "bug54178ServletA", bug54178ServletA);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/bug54178ServletA", "bug54178ServletA");

    Bug54178ServletB bug54178ServletB = new Bug54178ServletB();
    Tomcat.addServlet(ctx, "bug54178ServletB", bug54178ServletB);
    ctx.addServletMapping("/bug54178ServletB", "bug54178ServletB");

    tomcat.start();

    ByteChunk body = new ByteChunk();
    int rc = -1;

    try {
        rc = getUrl("http://localhost:" + getPort() + "/bug54178ServletA?" +
                Bug54178ServletA.PARAM_NAME + "=bar",
                body, null);
    } catch (IOException ioe) {
        // This may happen if test fails. Output the exception in case it is
        // useful and let asserts handle the failure
        ioe.printStackTrace();
    }

    assertEquals(HttpServletResponse.SC_OK, rc);

    body.recycle();

    rc = getUrl("http://localhost:" + getPort() + "/bug54178ServletB",
            body, null);

    assertEquals(HttpServletResponse.SC_OK, rc);
    assertEquals("OK", body.toString());
}
 
Example 17
Source File: TestWebdavServlet.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
public static int getUrl(String path, ByteChunk out,
        Map<String, List<String>> resHead) throws IOException {
    out.recycle();
    return TomcatBaseTest.getUrl(path, out, resHead);
}
 
Example 18
Source File: TestSSOnonLoginAndDigestAuthenticator.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
public void doTestDigest(String user, String pwd, String uri,
        boolean expectedReject1, int expectedRC1,
        boolean useServerNonce, boolean useServerOpaque,
        String nc1, String cnonce,
        String qop, boolean req2expect200)
        throws Exception {

    String digestUri= uri;

    List<String> auth = new ArrayList<String>();
    Map<String,List<String>> reqHeaders1 =
            new HashMap<String,List<String>>();
    Map<String,List<String>> respHeaders1 =
            new HashMap<String,List<String>>();

    // the first access attempt should be challenged
    auth.add(buildDigestResponse(user, pwd, digestUri, REALM, "null",
            "null", nc1, cnonce, qop));
    reqHeaders1.put(CLIENT_AUTH_HEADER, auth);

    ByteChunk bc = new ByteChunk();
    int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders1,
            respHeaders1);

    if (expectedReject1) {
        assertEquals(expectedRC1, rc);
        assertTrue(bc.getLength() > 0);
    }
    else {
        assertEquals(200, rc);
        assertEquals("OK", bc.toString());
        saveCookies(respHeaders1);
        return;
    }

    // Second request should succeed (if we use the server nonce)
    Map<String,List<String>> reqHeaders2 =
            new HashMap<String,List<String>>();
    Map<String,List<String>> respHeaders2 =
            new HashMap<String,List<String>>();

    auth.clear();
    if (useServerNonce) {
        if (useServerOpaque) {
            auth.add(buildDigestResponse(user, pwd, digestUri,
                    getAuthToken(respHeaders1, REALM),
                    getAuthToken(respHeaders1, NONCE),
                    getAuthToken(respHeaders1, OPAQUE),
                    nc1, cnonce, qop));
        } else {
            auth.add(buildDigestResponse(user, pwd, digestUri,
                    getAuthToken(respHeaders1, REALM),
                    getAuthToken(respHeaders1, NONCE),
                    "null", nc1, cnonce, qop));
        }
    } else {
        auth.add(buildDigestResponse(user, pwd, digestUri,
                getAuthToken(respHeaders2, REALM),
                "null", getAuthToken(respHeaders1, OPAQUE),
                nc1, cnonce, QOP));
    }
    reqHeaders2.put(CLIENT_AUTH_HEADER, auth);

    bc.recycle();
    rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders2,
            respHeaders2);

    if (req2expect200) {
        assertEquals(200, rc);
        assertEquals("OK", bc.toString());
        saveCookies(respHeaders2);
    } else {
        assertEquals(401, rc);
        assertTrue((bc.getLength() > 0));
    }
}
 
Example 19
Source File: TestHttpServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testChunkingWithHead() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    ChunkingServlet s = new ChunkingServlet();
    Tomcat.addServlet(ctx, "ChunkingServlet", s);
    ctx.addServletMappingDecoded("/chunking", "ChunkingServlet");

    tomcat.start();

    Map<String,List<String>> getHeaders = new CaseInsensitiveKeyMap<>();
    String path = "http://localhost:" + getPort() + "/chunking";
    ByteChunk out = new ByteChunk();

    int rc = getUrl(path, out, getHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    out.recycle();

    Map<String,List<String>> headHeaders = new HashMap<>();
    rc = headUrl(path, out, headHeaders);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);

    // Headers should be the same (apart from Date)
    Assert.assertEquals(getHeaders.size(), headHeaders.size());
    for (Map.Entry<String, List<String>> getHeader : getHeaders.entrySet()) {
        String headerName = getHeader.getKey();
        if ("date".equalsIgnoreCase(headerName)) {
            continue;
        }
        Assert.assertTrue(headerName, headHeaders.containsKey(headerName));
        List<String> getValues = getHeader.getValue();
        List<String> headValues = headHeaders.get(headerName);
        Assert.assertEquals(getValues.size(), headValues.size());
        for (String value : getValues) {
            Assert.assertTrue(headValues.contains(value));
        }
    }

    tomcat.stop();
}
 
Example 20
Source File: Base64.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Decodes Base64 data into octets
 *
 * @param base64DataBC Byte array containing Base64 data
 * @param decodedDataBC The decoded data bytes
 */
public static void decode( ByteChunk base64DataBC, ByteChunk decodedDataBC)
{
    int start = base64DataBC.getStart();
    int end = base64DataBC.getEnd();
    byte[] base64Data = base64DataBC.getBuffer();
    
    decodedDataBC.recycle();
    
    // handle the edge case, so we don't have to worry about it later
    if(end - start == 0) { return; }

    int      numberQuadruple    = (end - start)/FOURBYTE;
    byte     b1=0,b2=0,b3=0, b4=0, marker0=0, marker1=0;

    // Throw away anything not in base64Data

    int encodedIndex = 0;
    int dataIndex = start;
    byte[] decodedData = null;
    
    {
        // this sizes the output array properly - rlw
        int lastData = end - start;
        // ignore the '=' padding
        while (base64Data[start+lastData-1] == PAD)
        {
            if (--lastData == 0)
            {
                return;
            }
        }
        decodedDataBC.allocate(lastData - numberQuadruple, -1);
        decodedDataBC.setEnd(lastData - numberQuadruple);
        decodedData = decodedDataBC.getBuffer();
    }

    for (int i = 0; i < numberQuadruple; i++)
    {
        dataIndex = start + i * 4;
        marker0   = base64Data[dataIndex + 2];
        marker1   = base64Data[dataIndex + 3];

        b1 = base64Alphabet[base64Data[dataIndex]];
        b2 = base64Alphabet[base64Data[dataIndex +1]];

        if (marker0 != PAD && marker1 != PAD)
        {
            //No PAD e.g 3cQl
            b3 = base64Alphabet[ marker0 ];
            b4 = base64Alphabet[ marker1 ];

            decodedData[encodedIndex]   = (byte) ((  b1 <<2 | b2>>4 ) & 0xff);
            decodedData[encodedIndex + 1] =
                (byte) ((((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ) & 0xff);
            decodedData[encodedIndex + 2] = (byte) (( b3<<6 | b4 ) & 0xff);
        }
        else if (marker0 == PAD)
        {
            //Two PAD e.g. 3c[Pad][Pad]
            decodedData[encodedIndex]   = (byte) ((  b1 <<2 | b2>>4 ) & 0xff);
        }
        else if (marker1 == PAD)
        {
            //One PAD e.g. 3cQ[Pad]
            b3 = base64Alphabet[ marker0 ];

            decodedData[encodedIndex]   = (byte) ((  b1 <<2 | b2>>4 ) & 0xff);
            decodedData[encodedIndex + 1] =
                (byte) ((((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ) & 0xff);
        }
        encodedIndex += 3;
    }
}