Search in sources :

Example 41 with MessageBytes

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

the class TestLegacyCookieProcessor method testV0WithPath.

/*
     * https://bz.apache.org/bugzilla/show_bug.cgi?id=59925
     */
@Test
public void testV0WithPath() {
    LegacyCookieProcessor cp = new LegacyCookieProcessor();
    cp.setAllowHttpSepsInV0(true);
    cp.setForwardSlashIsSeparator(true);
    MimeHeaders mimeHeaders = new MimeHeaders();
    ServerCookies serverCookies = new ServerCookies(4);
    MessageBytes cookieHeaderValue = mimeHeaders.addValue("Cookie");
    byte[] bytes = "$Version=0;cname=cvalue;$Path=/example".getBytes(StandardCharsets.UTF_8);
    cookieHeaderValue.setBytes(bytes, 0, bytes.length);
    cp.parseCookieHeader(mimeHeaders, serverCookies);
    Assert.assertEquals(1, serverCookies.getCookieCount());
    for (int i = 0; i < 1; i++) {
        ServerCookie actual = serverCookies.getCookie(i);
        Assert.assertEquals(0, actual.getVersion());
        Assert.assertEquals("cname", actual.getName().toString());
        actual.getValue().getByteChunk().setCharset(StandardCharsets.UTF_8);
        Assert.assertEquals("cvalue", org.apache.tomcat.util.http.parser.Cookie.unescapeCookieValueRfc2109(actual.getValue().toString()));
        Assert.assertEquals("/example", actual.getPath().toString());
    }
}
Also used : MessageBytes(org.apache.tomcat.util.buf.MessageBytes) Test(org.junit.Test)

Example 42 with MessageBytes

use of org.apache.tomcat.util.buf.MessageBytes in project tomcat70 by apache.

the class StandardWrapperValve method invoke.

// --------------------------------------------------------- Public Methods
/**
 * Invoke the servlet we are managing, respecting the rules regarding
 * servlet lifecycle and SingleThreadModel support.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response) throws IOException, ServletException {
    // Initialize local variables we may need
    boolean unavailable = false;
    Throwable throwable = null;
    // This should be a Request attribute...
    long t1 = System.currentTimeMillis();
    requestCount.incrementAndGet();
    StandardWrapper wrapper = (StandardWrapper) getContainer();
    Servlet servlet = null;
    Context context = (Context) wrapper.getParent();
    // Check for the application being marked unavailable
    if (!context.getState().isAvailable()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable"));
        unavailable = true;
    }
    // Check for the servlet being marked unavailable
    if (!unavailable && wrapper.isUnavailable()) {
        container.getLogger().info(sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
        unavailable = true;
    }
    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            servlet = wrapper.allocate();
        }
    } catch (UnavailableException e) {
        container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e);
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
    } catch (ServletException e) {
        container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e));
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e);
        throwable = e;
        exception(request, response, e);
        servlet = null;
    }
    // Identify if the request is Comet related now that the servlet has been allocated
    boolean comet = false;
    if (servlet instanceof CometProcessor && Boolean.TRUE.equals(request.getAttribute(Globals.COMET_SUPPORTED_ATTR))) {
        comet = true;
        request.setComet(true);
    }
    MessageBytes requestPathMB = request.getRequestPathMB();
    DispatcherType dispatcherType = DispatcherType.REQUEST;
    if (request.getDispatcherType() == DispatcherType.ASYNC)
        dispatcherType = DispatcherType.ASYNC;
    request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, dispatcherType);
    request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB);
    // Create the filter chain for this request
    ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance();
    ApplicationFilterChain filterChain = factory.createFilterChain(request, wrapper, servlet);
    // Reset comet flag value after creating the filter chain
    request.setComet(false);
    // NOTE: This also calls the servlet's service() method
    try {
        if ((servlet != null) && (filterChain != null)) {
            // Swallow output if needed
            if (context.getSwallowOutput()) {
                try {
                    SystemLogHandler.startCapture();
                    if (request.isAsyncDispatching()) {
                        request.getAsyncContextInternal().doInternalDispatch();
                    } else if (comet) {
                        filterChain.doFilterEvent(request.getEvent());
                        request.setComet(true);
                    } else {
                        filterChain.doFilter(request.getRequest(), response.getResponse());
                    }
                } finally {
                    String log = SystemLogHandler.stopCapture();
                    if (log != null && log.length() > 0) {
                        context.getLogger().info(log);
                    }
                }
            } else {
                if (request.isAsyncDispatching()) {
                    request.getAsyncContextInternal().doInternalDispatch();
                } else if (comet) {
                    request.setComet(true);
                    filterChain.doFilterEvent(request.getEvent());
                } else {
                    filterChain.doFilter(request.getRequest(), response.getResponse());
                }
            }
        }
    } catch (ClientAbortException e) {
        throwable = e;
        exception(request, response, e);
    } catch (IOException e) {
        container.getLogger().error(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
        throwable = e;
        exception(request, response, e);
    } catch (UnavailableException e) {
        container.getLogger().error(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
        // throwable = e;
        // exception(request, response, e);
        wrapper.unavailable(e);
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
    // Do not save exception in 'throwable', because we
    // do not want to do exception(request, response, e) processing
    } catch (ServletException e) {
        Throwable rootCause = StandardWrapper.getRootCause(e);
        if (!(rootCause instanceof ClientAbortException)) {
            container.getLogger().error(sm.getString("standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause);
        }
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
        throwable = e;
        exception(request, response, e);
    }
    // Release the filter chain (if any) for this request
    if (filterChain != null) {
        if (request.isComet()) {
            // If this is a Comet request, then the same chain will be used for the
            // processing of all subsequent events.
            filterChain.reuse();
        } else {
            filterChain.release();
        }
    }
    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }
    // unload it and release this instance
    try {
        if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) {
            wrapper.unload();
        }
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }
    long t2 = System.currentTimeMillis();
    long time = t2 - t1;
    processingTime += time;
    if (time > maxTime)
        maxTime = time;
    if (time < minTime)
        minTime = time;
}
Also used : Context(org.apache.catalina.Context) UnavailableException(javax.servlet.UnavailableException) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) CometProcessor(org.apache.catalina.comet.CometProcessor) Servlet(javax.servlet.Servlet) ClientAbortException(org.apache.catalina.connector.ClientAbortException) DispatcherType(javax.servlet.DispatcherType)

Example 43 with MessageBytes

use of org.apache.tomcat.util.buf.MessageBytes in project tomcat70 by apache.

the class TestMapper method testReloadContextVersion.

@Test
public void testReloadContextVersion() throws Exception {
    final String hostName = "iowejoiejfoiew";
    final int iowPos = 3;
    final String contextPath = "/foo/bar";
    final int contextPos = 2;
    MappingData mappingData = new MappingData();
    MessageBytes hostMB = MessageBytes.newInstance();
    MessageBytes uriMB = MessageBytes.newInstance();
    hostMB.setString(hostName);
    uriMB.setString("/foo/bar/blah/bobou/foo");
    // Verifying configuration created by setUp()
    Mapper.Host mappedHost = mapper.hosts[iowPos];
    Assert.assertEquals(hostName, mappedHost.name);
    Mapper.Context mappedContext = mappedHost.contextList.contexts[contextPos];
    Assert.assertEquals(contextPath, mappedContext.name);
    Assert.assertEquals(1, mappedContext.versions.length);
    Assert.assertEquals("0", mappedContext.versions[0].name);
    Object oldHost = mappedHost.object;
    Object oldContext = mappedContext.versions[0].object;
    Assert.assertEquals("context2", oldContext.toString());
    Object oldContext1 = mappedHost.contextList.contexts[contextPos - 1].versions[0].object;
    Assert.assertEquals("context1", oldContext1.toString());
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host.toString());
    Assert.assertEquals("context2", mappingData.context.toString());
    Assert.assertEquals("wrapper5", mappingData.wrapper.toString());
    mappingData.recycle();
    mapperForContext2.map(uriMB, mappingData);
    Assert.assertEquals("wrapper5", mappingData.wrapper.toString());
    // Mark context as paused
    // This is what happens when context reload starts
    mapper.pauseContextVersion(oldContext, hostName, contextPath, "0");
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host.toString());
    Assert.assertEquals("context2", mappingData.context.toString());
    // Wrapper is not mapped for incoming requests if context is paused
    Assert.assertNull(mappingData.wrapper);
    // Re-add the same context, but different list of wrappers
    // This is what happens when context reload completes
    mapper.addContextVersion(hostName, oldHost, contextPath, "0", oldContext, null, null, Arrays.asList(new WrapperMappingInfo[] { new WrapperMappingInfo("/", "newDefaultWrapper", false, false) }), false, false);
    mappedContext = mappedHost.contextList.contexts[contextPos];
    Assert.assertEquals(contextPath, mappedContext.name);
    Assert.assertEquals(1, mappedContext.versions.length);
    Assert.assertEquals("0", mappedContext.versions[0].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host.toString());
    Assert.assertEquals("context2", mappingData.context.toString());
    Assert.assertEquals("newDefaultWrapper", mappingData.wrapper.toString());
}
Also used : MessageBytes(org.apache.tomcat.util.buf.MessageBytes) Test(org.junit.Test) LoggingBaseTest(org.apache.catalina.startup.LoggingBaseTest)

Example 44 with MessageBytes

use of org.apache.tomcat.util.buf.MessageBytes in project tomcat70 by apache.

the class TestMapper method testMap.

@Test
public void testMap() throws Exception {
    MappingData mappingData = new MappingData();
    MessageBytes host = MessageBytes.newInstance();
    host.setString("iowejoiejfoiew");
    MessageBytes alias = MessageBytes.newInstance();
    alias.setString("iowejoiejfoiew_alias");
    MessageBytes uri = MessageBytes.newInstance();
    uri.setString("/foo/bar/blah/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);
    mapper.map(host, uri, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host);
    Assert.assertEquals("context2", mappingData.context);
    Assert.assertEquals("wrapper5", mappingData.wrapper);
    Assert.assertEquals("/foo/bar", mappingData.contextPath.toString());
    Assert.assertEquals("/blah/bobou", mappingData.wrapperPath.toString());
    Assert.assertEquals("/foo", mappingData.pathInfo.toString());
    Assert.assertTrue(mappingData.redirectPath.isNull());
    mappingData.recycle();
    uri.recycle();
    uri.setString("/foo/bar/bla/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);
    mapper.map(host, uri, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host);
    Assert.assertEquals("context3", mappingData.context);
    Assert.assertEquals("wrapper7", mappingData.wrapper);
    Assert.assertEquals("/foo/bar/bla", mappingData.contextPath.toString());
    Assert.assertEquals("/bobou", mappingData.wrapperPath.toString());
    Assert.assertEquals("/foo", mappingData.pathInfo.toString());
    Assert.assertTrue(mappingData.redirectPath.isNull());
    mappingData.recycle();
    uri.setString("/foo/bar/bla/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);
    mapper.map(alias, uri, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host);
    Assert.assertEquals("context3", mappingData.context);
    Assert.assertEquals("wrapper7", mappingData.wrapper);
    Assert.assertEquals("/foo/bar/bla", mappingData.contextPath.toString());
    Assert.assertEquals("/bobou", mappingData.wrapperPath.toString());
    Assert.assertEquals("/foo", mappingData.pathInfo.toString());
    Assert.assertTrue(mappingData.redirectPath.isNull());
}
Also used : MessageBytes(org.apache.tomcat.util.buf.MessageBytes) Test(org.junit.Test) LoggingBaseTest(org.apache.catalina.startup.LoggingBaseTest)

Example 45 with MessageBytes

use of org.apache.tomcat.util.buf.MessageBytes in project tomcat70 by apache.

the class TestMapper method testAddRemoveContextVersion.

@Test
public void testAddRemoveContextVersion() throws Exception {
    final String hostName = "iowejoiejfoiew";
    final int iowPos = 3;
    final String contextPath = "/foo/bar";
    final int contextPos = 2;
    MappingData mappingData = new MappingData();
    MessageBytes hostMB = MessageBytes.newInstance();
    MessageBytes uriMB = MessageBytes.newInstance();
    hostMB.setString(hostName);
    uriMB.setString("/foo/bar/blah/bobou/foo");
    // Verifying configuration created by setUp()
    Mapper.Host mappedHost = mapper.hosts[iowPos];
    Assert.assertEquals(hostName, mappedHost.name);
    Mapper.Context mappedContext = mappedHost.contextList.contexts[contextPos];
    Assert.assertEquals(contextPath, mappedContext.name);
    Assert.assertEquals(1, mappedContext.versions.length);
    Assert.assertEquals("0", mappedContext.versions[0].name);
    Object oldHost = mappedHost.object;
    Object oldContext = mappedContext.versions[0].object;
    Assert.assertEquals("context2", oldContext.toString());
    Object oldContext1 = mappedHost.contextList.contexts[contextPos - 1].versions[0].object;
    Assert.assertEquals("context1", oldContext1.toString());
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host.toString());
    Assert.assertEquals("context2", mappingData.context.toString());
    Assert.assertEquals("wrapper5", mappingData.wrapper.toString());
    mappingData.recycle();
    mapperForContext2.map(uriMB, mappingData);
    Assert.assertEquals("wrapper5", mappingData.wrapper.toString());
    Object newContext = "newContext";
    mapper.addContextVersion(hostName, oldHost, contextPath, "1", newContext, null, null, Arrays.asList(new WrapperMappingInfo[] { new WrapperMappingInfo("/", "newContext-default", false, false) }), false, false);
    Assert.assertEquals(2, mappedContext.versions.length);
    Assert.assertEquals("0", mappedContext.versions[0].name);
    Assert.assertEquals("1", mappedContext.versions[1].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    Assert.assertEquals("newContext", mappingData.context.toString());
    Assert.assertEquals("newContext-default", mappingData.wrapper.toString());
    mapper.removeContextVersion(hostName, contextPath, "0");
    Assert.assertEquals(1, mappedContext.versions.length);
    Assert.assertEquals("1", mappedContext.versions[0].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    Assert.assertEquals("newContext", mappingData.context.toString());
    Assert.assertEquals("newContext-default", mappingData.wrapper.toString());
    mapper.removeContextVersion(hostName, contextPath, "1");
    Assert.assertNotSame(mappedContext, mappedHost.contextList.contexts[contextPos]);
    Assert.assertEquals("/foo/bar/bla", mappedHost.contextList.contexts[contextPos].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    Assert.assertEquals("context1", mappingData.context.toString());
    Assert.assertEquals("context1-defaultWrapper", mappingData.wrapper.toString());
    mappingData.recycle();
    mapperForContext1.map(uriMB, mappingData);
    Assert.assertEquals("context1-defaultWrapper", mappingData.wrapper.toString());
    mapper.addContextVersion(hostName, oldHost, contextPath, "0", newContext, null, null, Arrays.asList(new WrapperMappingInfo[] { new WrapperMappingInfo("/", "newContext-defaultWrapper2", false, false) }), false, false);
    mappedContext = mappedHost.contextList.contexts[contextPos];
    Assert.assertEquals(contextPath, mappedContext.name);
    Assert.assertEquals(1, mappedContext.versions.length);
    Assert.assertEquals("0", mappedContext.versions[0].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    Assert.assertEquals("newContext", mappingData.context.toString());
    Assert.assertEquals("newContext-defaultWrapper2", mappingData.wrapper.toString());
}
Also used : MessageBytes(org.apache.tomcat.util.buf.MessageBytes) Test(org.junit.Test) LoggingBaseTest(org.apache.catalina.startup.LoggingBaseTest)

Aggregations

MessageBytes (org.apache.tomcat.util.buf.MessageBytes)73 MimeHeaders (org.apache.tomcat.util.http.MimeHeaders)15 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)14 IOException (java.io.IOException)11 Test (org.junit.Test)11 Context (org.apache.catalina.Context)10 LoggingBaseTest (org.apache.catalina.startup.LoggingBaseTest)8 Pattern (java.util.regex.Pattern)6 AbstractEndpoint (org.apache.tomcat.util.net.AbstractEndpoint)6 Principal (java.security.Principal)5 Wrapper (org.apache.catalina.Wrapper)5 CharChunk (org.apache.tomcat.util.buf.CharChunk)5 Host (org.apache.catalina.Host)4 ServletException (jakarta.servlet.ServletException)3 Cookie (jakarta.servlet.http.Cookie)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 HashSet (java.util.HashSet)3 ServletException (javax.servlet.ServletException)3 Cookie (javax.servlet.http.Cookie)3 Container (org.apache.catalina.Container)3