Search in sources :

Example 61 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class Rfc6265CookieProcessor method parseCookieHeader.

@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);
    }
}
Also used : ByteChunk(org.apache.tomcat.util.buf.ByteChunk) MessageBytes(org.apache.tomcat.util.buf.MessageBytes)

Example 62 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class TestPageContext method testBug49196.

@Test
public void testBug49196() throws Exception {
    getTomcatInstanceTestWebapp(false, true);
    ByteChunk res = getUrl("http://localhost:" + getPort() + "/test/bug49nnn/bug49196.jsp");
    String result = res.toString();
    assertTrue(result.contains("OK"));
}
Also used : ByteChunk(org.apache.tomcat.util.buf.ByteChunk) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 63 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class TestNonBlockingAPI method testNonBlockingWriteInternal.

private void testNonBlockingWriteInternal(boolean keepAlive) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    NBWriteServlet servlet = new NBWriteServlet();
    String servletName = NBWriteServlet.class.getName();
    Tomcat.addServlet(ctx, servletName, servlet);
    ctx.addServletMappingDecoded("/", servletName);
    tomcat.getConnector().setProperty("socket.txBufSize", "1024");
    tomcat.start();
    SocketFactory factory = SocketFactory.getDefault();
    Socket s = factory.createSocket("localhost", getPort());
    InputStream is = s.getInputStream();
    byte[] buffer = new byte[8192];
    ByteChunk result = new ByteChunk();
    OutputStream os = s.getOutputStream();
    if (keepAlive) {
        os.write(("OPTIONS * HTTP/1.1\r\n" + "Host: localhost:" + getPort() + "\r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
        os.flush();
        is.read(buffer);
    }
    os.write(("GET / HTTP/1.1\r\n" + "Host: localhost:" + getPort() + "\r\n" + "Connection: close\r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
    os.flush();
    int read = 0;
    int readSinceLastPause = 0;
    while (read != -1) {
        read = is.read(buffer);
        if (read > 0) {
            result.append(buffer, 0, read);
        }
        readSinceLastPause += read;
        if (readSinceLastPause > WRITE_SIZE / 16) {
            readSinceLastPause = 0;
            Thread.sleep(500);
        }
    }
    os.close();
    is.close();
    s.close();
    // Validate the result.
    // Response line
    String resultString = result.toString();
    log.info("Client read " + resultString.length() + " bytes");
    int lineStart = 0;
    int lineEnd = resultString.indexOf('\n', 0);
    String line = resultString.substring(lineStart, lineEnd + 1);
    Assert.assertEquals("HTTP/1.1 200 \r\n", line);
    // Check headers - looking to see if response is chunked (it should be)
    boolean chunked = false;
    while (line.length() > 2) {
        lineStart = lineEnd + 1;
        lineEnd = resultString.indexOf('\n', lineStart);
        line = resultString.substring(lineStart, lineEnd + 1);
        if (line.startsWith("Transfer-Encoding:")) {
            Assert.assertEquals("Transfer-Encoding: chunked\r\n", line);
            chunked = true;
        }
    }
    Assert.assertTrue(chunked);
    // Now check body size
    int totalBodyRead = 0;
    int chunkSize = -1;
    while (chunkSize != 0) {
        // Chunk size in hex
        lineStart = lineEnd + 1;
        lineEnd = resultString.indexOf('\n', lineStart);
        line = resultString.substring(lineStart, lineEnd + 1);
        Assert.assertTrue(line.endsWith("\r\n"));
        line = line.substring(0, line.length() - 2);
        log.info("[" + line + "]");
        chunkSize = Integer.parseInt(line, 16);
        // Read the chunk
        lineStart = lineEnd + 1;
        lineEnd = resultString.indexOf('\n', lineStart);
        log.info("Start : " + lineStart + ", End: " + lineEnd);
        if (lineEnd > lineStart) {
            line = resultString.substring(lineStart, lineEnd + 1);
        } else {
            line = resultString.substring(lineStart);
        }
        if (line.length() > 40) {
            log.info(line.substring(0, 32));
        } else {
            log.info(line);
        }
        if (chunkSize + 2 != line.length()) {
            log.error("Chunk wrong length. Was " + line.length() + " Expected " + (chunkSize + 2));
            byte[] resultBytes = resultString.getBytes();
            // Find error
            boolean found = false;
            for (int i = totalBodyRead; i < (totalBodyRead + line.length()); i++) {
                if (DATA[i] != resultBytes[lineStart + i - totalBodyRead]) {
                    int dataStart = i - 64;
                    if (dataStart < 0) {
                        dataStart = 0;
                    }
                    int dataEnd = i + 64;
                    if (dataEnd > DATA.length) {
                        dataEnd = DATA.length;
                    }
                    int resultStart = lineStart + i - totalBodyRead - 64;
                    if (resultStart < 0) {
                        resultStart = 0;
                    }
                    int resultEnd = lineStart + i - totalBodyRead + 64;
                    if (resultEnd > resultString.length()) {
                        resultEnd = resultString.length();
                    }
                    log.error("Mis-match tx: " + new String(DATA, dataStart, dataEnd - dataStart));
                    log.error("Mis-match rx: " + resultString.substring(resultStart, resultEnd));
                    found = true;
                    break;
                }
            }
            if (!found) {
                log.error("No mismatch. Data truncated");
            }
        }
        Assert.assertTrue(line.endsWith("\r\n"));
        Assert.assertEquals(chunkSize + 2, line.length());
        totalBodyRead += chunkSize;
    }
    Assert.assertEquals(WRITE_SIZE, totalBodyRead);
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) SocketFactory(javax.net.SocketFactory) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) Socket(java.net.Socket)

Example 64 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class TestNonBlockingAPI method testNonBlockingWriteError.

@Test
public void testNonBlockingWriteError() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);
    NBWriteServlet servlet = new NBWriteServlet();
    String servletName = NBWriteServlet.class.getName();
    Tomcat.addServlet(ctx, servletName, servlet);
    ctx.addServletMappingDecoded("/", servletName);
    tomcat.getConnector().setProperty("socket.txBufSize", "1024");
    tomcat.start();
    SocketFactory factory = SocketFactory.getDefault();
    Socket s = factory.createSocket("localhost", getPort());
    ByteChunk result = new ByteChunk();
    OutputStream os = s.getOutputStream();
    os.write(("GET / HTTP/1.1\r\n" + "Host: localhost:" + getPort() + "\r\n" + "Connection: close\r\n" + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
    os.flush();
    InputStream is = s.getInputStream();
    byte[] buffer = new byte[8192];
    int read = 0;
    int readSinceLastPause = 0;
    int readTotal = 0;
    while (read != -1 && readTotal < WRITE_SIZE / 32) {
        long start = System.currentTimeMillis();
        read = is.read(buffer);
        long end = System.currentTimeMillis();
        log.info("Client read [" + read + "] bytes in [" + (end - start) + "] ms");
        if (read > 0) {
            result.append(buffer, 0, read);
        }
        readSinceLastPause += read;
        readTotal += read;
        if (readSinceLastPause > WRITE_SIZE / 64) {
            readSinceLastPause = 0;
            Thread.sleep(WRITE_PAUSE_MS);
        }
    }
    os.close();
    is.close();
    s.close();
    String resultString = result.toString();
    log.info("Client read " + resultString.length() + " bytes");
    int lineStart = 0;
    int lineEnd = resultString.indexOf('\n', 0);
    String line = resultString.substring(lineStart, lineEnd + 1);
    Assert.assertEquals("HTTP/1.1 200 \r\n", line);
    // Listeners are invoked and access valve entries created on a different
    // thread so give that thread a chance to complete its work.
    int count = 0;
    while (count < 100 && !(servlet.wlistener.onErrorInvoked || servlet.rlistener.onErrorInvoked)) {
        Thread.sleep(100);
        count++;
    }
    while (count < 100 && alv.getEntryCount() < 1) {
        Thread.sleep(100);
        count++;
    }
    Assert.assertTrue("Error listener should have been invoked.", servlet.wlistener.onErrorInvoked || servlet.rlistener.onErrorInvoked);
    // TODO Figure out why non-blocking writes with the NIO connector appear
    // to be slower on Linux
    alv.validateAccessLog(1, 500, WRITE_PAUSE_MS, WRITE_PAUSE_MS + 30 * 1000);
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) SocketFactory(javax.net.SocketFactory) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) TesterAccessLogValve(org.apache.catalina.valves.TesterAccessLogValve) Socket(java.net.Socket) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 65 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class TestNonBlockingAPI method testBug55438NonBlockingReadWriteEmptyRead.

@Test
public void testBug55438NonBlockingReadWriteEmptyRead() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    NBReadWriteServlet servlet = new NBReadWriteServlet();
    String servletName = NBReadWriteServlet.class.getName();
    Tomcat.addServlet(ctx, servletName, servlet);
    ctx.addServletMappingDecoded("/", servletName);
    tomcat.start();
    Map<String, List<String>> resHeaders = new HashMap<>();
    int rc = postUrl(false, new BytesStreamer() {

        @Override
        public byte[] next() {
            return new byte[] {};
        }

        @Override
        public int getLength() {
            return 0;
        }

        @Override
        public int available() {
            return 0;
        }
    }, "http://localhost:" + getPort() + "/", new ByteChunk(), resHeaders, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) Tomcat(org.apache.catalina.startup.Tomcat) HashMap(java.util.HashMap) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) BytesStreamer(org.apache.catalina.startup.BytesStreamer) ArrayList(java.util.ArrayList) List(java.util.List) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Aggregations

ByteChunk (org.apache.tomcat.util.buf.ByteChunk)274 Test (org.junit.Test)201 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)180 Tomcat (org.apache.catalina.startup.Tomcat)129 Context (org.apache.catalina.Context)98 File (java.io.File)49 List (java.util.List)48 AsyncContext (javax.servlet.AsyncContext)40 HashMap (java.util.HashMap)35 Wrapper (org.apache.catalina.Wrapper)22 StandardContext (org.apache.catalina.core.StandardContext)21 ArrayList (java.util.ArrayList)20 TesterContext (org.apache.tomcat.unittest.TesterContext)18 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)16 ServletRequestWrapper (javax.servlet.ServletRequestWrapper)13 ServletResponseWrapper (javax.servlet.ServletResponseWrapper)13 ServletContext (javax.servlet.ServletContext)10 WsContextListener (org.apache.tomcat.websocket.server.WsContextListener)10 TesterAccessLogValve (org.apache.catalina.valves.TesterAccessLogValve)9 InitialContext (javax.naming.InitialContext)8