Search in sources :

Example 16 with HttpURI

use of org.eclipse.jetty.http.HttpURI in project processdash by dtuma.

the class DashboardHttpRequestInterceptor method handle.

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    // add the dashboard startup timestamp header to the response.
    response.addHeader(WebServer.TIMESTAMP_HEADER, startupTimestamp);
    // make the URI canonical
    HttpURI uri = baseRequest.getUri();
    String origUri = uri.toString();
    String origPath = uri.getPath();
    String path = canonicalizePath(origPath);
    if (path == null || !path.startsWith("/") || path.contains("/../")) {
        baseRequest.setHandled(true);
        response.sendError(SC_BAD_REQUEST, "Bad filename.");
        return;
    }
    // Separate out the hierarchy prefix if the URI contains one
    String[] pathSplit = splitPath(path, "//", "/+/");
    String prefix = "";
    if (pathSplit != null) {
        prefix = pathSplit[0];
        path = pathSplit[1];
    }
    if (path.contains("//")) {
        baseRequest.setHandled(true);
        response.sendError(SC_BAD_REQUEST, "Bad path/filename.");
        return;
    }
    if (!origPath.equals(path)) {
        String newUri = replaceUriPath(origUri, origPath, path);
        if (newUri == null) {
            baseRequest.setHandled(true);
            response.sendError(SC_BAD_REQUEST, "Bad uri/filename.");
        } else {
            uri.parse(newUri);
        }
    }
    // add the "pdash" object to the request.
    baseRequest.setAttribute(PDashContext.REQUEST_ATTR, new PdashContextImpl(baseRequest, prefix));
    // pass the request on to the rest of the processing chain
    super.handle(path, baseRequest, request, response);
}
Also used : HttpURI(org.eclipse.jetty.http.HttpURI)

Example 17 with HttpURI

use of org.eclipse.jetty.http.HttpURI in project dropwizard by dropwizard.

the class DropwizardSlf4jRequestLogTest method setUp.

@Before
public void setUp() throws Exception {
    when(channelState.isInitial()).thenReturn(true);
    when(request.getRemoteAddr()).thenReturn("10.0.0.1");
    when(request.getTimeStamp()).thenReturn(TimeUnit.SECONDS.toMillis(1353042047));
    when(request.getMethod()).thenReturn("GET");
    when(request.getHttpURI()).thenReturn(new HttpURI("/test/things?yay"));
    when(request.getProtocol()).thenReturn("HTTP/1.1");
    when(request.getHttpChannelState()).thenReturn(channelState);
    when(request.getTimeStamp()).thenReturn(TimeUnit.SECONDS.toMillis(1353042048));
    when(response.getCommittedMetaData().getStatus()).thenReturn(200);
    when(response.getHttpChannel().getBytesWritten()).thenReturn(8290L);
    appenders.addAppender(appender);
    slf4jRequestLog.start();
}
Also used : HttpURI(org.eclipse.jetty.http.HttpURI) Before(org.junit.Before)

Example 18 with HttpURI

use of org.eclipse.jetty.http.HttpURI in project jetty.project by eclipse.

the class RawHTTP2ProxyTest method testRawHTTP2Proxy.

@Test
public void testRawHTTP2Proxy() throws Exception {
    byte[] data1 = new byte[1024];
    new Random().nextBytes(data1);
    ByteBuffer buffer1 = ByteBuffer.wrap(data1);
    Server server1 = startServer("server1", new ServerSessionListener.Adapter() {

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("SERVER1 received {}", frame);
            return new Stream.Listener.Adapter() {

                @Override
                public void onHeaders(Stream stream, HeadersFrame frame) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("SERVER1 received {}", frame);
                    if (frame.isEndStream()) {
                        MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields());
                        HeadersFrame reply = new HeadersFrame(stream.getId(), response, null, false);
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug("SERVER1 sending {}", reply);
                        stream.headers(reply, new Callback() {

                            @Override
                            public void succeeded() {
                                DataFrame data = new DataFrame(stream.getId(), buffer1.slice(), true);
                                if (LOGGER.isDebugEnabled())
                                    LOGGER.debug("SERVER1 sending {}", data);
                                stream.data(data, NOOP);
                            }
                        });
                    }
                }
            };
        }
    });
    ServerConnector connector1 = (ServerConnector) server1.getAttribute("connector");
    Server server2 = startServer("server2", new ServerSessionListener.Adapter() {

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("SERVER2 received {}", frame);
            return new Stream.Listener.Adapter() {

                @Override
                public void onData(Stream stream, DataFrame frame, Callback callback) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("SERVER2 received {}", frame);
                    callback.succeeded();
                    MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields());
                    Callback.Completable completable1 = new Callback.Completable();
                    HeadersFrame reply = new HeadersFrame(stream.getId(), response, null, false);
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("SERVER2 sending {}", reply);
                    stream.headers(reply, completable1);
                    completable1.thenCompose(ignored -> {
                        Callback.Completable completable2 = new Callback.Completable();
                        DataFrame data = new DataFrame(stream.getId(), buffer1.slice(), false);
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug("SERVER2 sending {}", data);
                        stream.data(data, completable2);
                        return completable2;
                    }).thenRun(() -> {
                        MetaData trailer = new MetaData(HttpVersion.HTTP_2, new HttpFields());
                        HeadersFrame end = new HeadersFrame(stream.getId(), trailer, null, true);
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug("SERVER2 sending {}", end);
                        stream.headers(end, Callback.NOOP);
                    });
                }
            };
        }
    });
    ServerConnector connector2 = (ServerConnector) server2.getAttribute("connector");
    HTTP2Client proxyClient = startClient("proxyClient");
    Server proxyServer = startServer("proxyServer", new ClientToProxySessionListener(proxyClient));
    ServerConnector proxyConnector = (ServerConnector) proxyServer.getAttribute("connector");
    InetSocketAddress proxyAddress = new InetSocketAddress("localhost", proxyConnector.getLocalPort());
    HTTP2Client client = startClient("client");
    FuturePromise<Session> clientPromise = new FuturePromise<>();
    client.connect(proxyAddress, new Session.Listener.Adapter(), clientPromise);
    Session clientSession = clientPromise.get(5, TimeUnit.SECONDS);
    // Send a request with trailers for server1.
    HttpFields fields1 = new HttpFields();
    fields1.put("X-Target", String.valueOf(connector1.getLocalPort()));
    MetaData.Request request1 = new MetaData.Request("GET", new HttpURI("http://localhost/server1"), HttpVersion.HTTP_2, fields1);
    FuturePromise<Stream> streamPromise1 = new FuturePromise<>();
    CountDownLatch latch1 = new CountDownLatch(1);
    clientSession.newStream(new HeadersFrame(request1, null, false), streamPromise1, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("CLIENT received {}", frame);
        }

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("CLIENT received {}", frame);
            Assert.assertEquals(buffer1.slice(), frame.getData());
            callback.succeeded();
            latch1.countDown();
        }
    });
    Stream stream1 = streamPromise1.get(5, TimeUnit.SECONDS);
    stream1.headers(new HeadersFrame(stream1.getId(), new MetaData(HttpVersion.HTTP_2, new HttpFields()), null, true), Callback.NOOP);
    // Send a request for server2.
    HttpFields fields2 = new HttpFields();
    fields2.put("X-Target", String.valueOf(connector2.getLocalPort()));
    MetaData.Request request2 = new MetaData.Request("GET", new HttpURI("http://localhost/server1"), HttpVersion.HTTP_2, fields2);
    FuturePromise<Stream> streamPromise2 = new FuturePromise<>();
    CountDownLatch latch2 = new CountDownLatch(1);
    clientSession.newStream(new HeadersFrame(request2, null, false), streamPromise2, new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("CLIENT received {}", frame);
            if (frame.isEndStream())
                latch2.countDown();
        }

        @Override
        public void onData(Stream stream, DataFrame frame, Callback callback) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("CLIENT received {}", frame);
            callback.succeeded();
        }
    });
    Stream stream2 = streamPromise2.get(5, TimeUnit.SECONDS);
    stream2.data(new DataFrame(stream2.getId(), buffer1.slice(), true), Callback.NOOP);
    Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS));
}
Also used : ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Server(org.eclipse.jetty.server.Server) InetSocketAddress(java.net.InetSocketAddress) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) ServerConnector(org.eclipse.jetty.server.ServerConnector) Random(java.util.Random) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) FuturePromise(org.eclipse.jetty.util.FuturePromise) DataFrame(org.eclipse.jetty.http2.frames.DataFrame) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) HttpURI(org.eclipse.jetty.http.HttpURI) Callback(org.eclipse.jetty.util.Callback) IteratingCallback(org.eclipse.jetty.util.IteratingCallback) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 19 with HttpURI

use of org.eclipse.jetty.http.HttpURI in project jetty.project by eclipse.

the class ProxyProtocolTest method test_PROXY_GET_v2.

@Test
public void test_PROXY_GET_v2() throws Exception {
    startServer(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            try {
                Assert.assertEquals("10.0.0.4", request.getRemoteAddr());
                Assert.assertEquals(33824, request.getRemotePort());
                Assert.assertEquals("10.0.0.4", request.getLocalAddr());
                Assert.assertEquals(8888, request.getLocalPort());
            } catch (Throwable th) {
                th.printStackTrace();
                response.setStatus(500);
            }
            baseRequest.setHandled(true);
        }
    });
    String request1 = "0D0A0D0A000D0A515549540A211100140A0000040A000004842022B82000050000000000";
    SocketChannel channel = SocketChannel.open();
    channel.connect(new InetSocketAddress("localhost", connector.getLocalPort()));
    channel.write(ByteBuffer.wrap(TypeUtil.fromHexString(request1)));
    FuturePromise<Session> promise = new FuturePromise<>();
    client.accept(null, channel, new Session.Listener.Adapter(), promise);
    Session session = promise.get(5, TimeUnit.SECONDS);
    HttpFields fields = new HttpFields();
    String uri = "http://localhost:" + connector.getLocalPort() + "/";
    MetaData.Request metaData = new MetaData.Request("GET", new HttpURI(uri), HttpVersion.HTTP_2, fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, true);
    CountDownLatch latch = new CountDownLatch(1);
    session.newStream(frame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            MetaData.Response response = (MetaData.Response) frame.getMetaData();
            Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
            if (frame.isEndStream())
                latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) FuturePromise(org.eclipse.jetty.util.FuturePromise) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) HttpURI(org.eclipse.jetty.http.HttpURI) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) FuturePromise(org.eclipse.jetty.util.FuturePromise) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 20 with HttpURI

use of org.eclipse.jetty.http.HttpURI in project jetty.project by eclipse.

the class PushCacheFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    Request jettyRequest = Request.getBaseRequest(request);
    if (HttpVersion.fromString(request.getProtocol()).getVersion() < 20 || !HttpMethod.GET.is(request.getMethod()) || !jettyRequest.isPushSupported()) {
        chain.doFilter(req, resp);
        return;
    }
    long now = System.nanoTime();
    // Iterating over fields is more efficient than multiple gets
    HttpFields fields = jettyRequest.getHttpFields();
    boolean conditional = false;
    String referrer = null;
    loop: for (int i = 0; i < fields.size(); i++) {
        HttpField field = fields.getField(i);
        HttpHeader header = field.getHeader();
        if (header == null)
            continue;
        switch(header) {
            case IF_MATCH:
            case IF_MODIFIED_SINCE:
            case IF_NONE_MATCH:
            case IF_UNMODIFIED_SINCE:
                conditional = true;
                break loop;
            case REFERER:
                referrer = field.getValue();
                break;
            default:
                break;
        }
    }
    if (LOG.isDebugEnabled())
        LOG.debug("{} {} referrer={} conditional={}", request.getMethod(), request.getRequestURI(), referrer, conditional);
    String path = request.getRequestURI();
    String query = request.getQueryString();
    if (_useQueryInKey && query != null)
        path += "?" + query;
    if (referrer != null) {
        HttpURI referrerURI = new HttpURI(referrer);
        String host = referrerURI.getHost();
        int port = referrerURI.getPort();
        if (port <= 0)
            port = request.isSecure() ? 443 : 80;
        boolean referredFromHere = _hosts.size() > 0 ? _hosts.contains(host) : host.equals(request.getServerName());
        referredFromHere &= _ports.size() > 0 ? _ports.contains(port) : port == request.getServerPort();
        if (referredFromHere) {
            if (HttpMethod.GET.is(request.getMethod())) {
                String referrerPath = _useQueryInKey ? referrerURI.getPathQuery() : referrerURI.getPath();
                if (referrerPath == null)
                    referrerPath = "/";
                if (referrerPath.startsWith(request.getContextPath() + "/")) {
                    if (!referrerPath.equals(path)) {
                        PrimaryResource primaryResource = _cache.get(referrerPath);
                        if (primaryResource != null) {
                            long primaryTimestamp = primaryResource._timestamp.get();
                            if (primaryTimestamp != 0) {
                                if (now - primaryTimestamp < TimeUnit.MILLISECONDS.toNanos(_associatePeriod)) {
                                    Set<String> associated = primaryResource._associated;
                                    // Not strictly concurrent-safe, just best effort to limit associations.
                                    if (associated.size() <= _maxAssociations) {
                                        if (associated.add(path)) {
                                            if (LOG.isDebugEnabled())
                                                LOG.debug("Associated {} to {}", path, referrerPath);
                                        }
                                    } else {
                                        if (LOG.isDebugEnabled())
                                            LOG.debug("Not associated {} to {}, exceeded max associations of {}", path, referrerPath, _maxAssociations);
                                    }
                                } else {
                                    if (LOG.isDebugEnabled())
                                        LOG.debug("Not associated {} to {}, outside associate period of {}ms", path, referrerPath, _associatePeriod);
                                }
                            }
                        }
                    } else {
                        if (LOG.isDebugEnabled())
                            LOG.debug("Not associated {} to {}, referring to self", path, referrerPath);
                    }
                } else {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Not associated {} to {}, different context", path, referrerPath);
                }
            }
        } else {
            if (LOG.isDebugEnabled())
                LOG.debug("External referrer {}", referrer);
        }
    }
    PrimaryResource primaryResource = _cache.get(path);
    if (primaryResource == null) {
        PrimaryResource r = new PrimaryResource();
        primaryResource = _cache.putIfAbsent(path, r);
        primaryResource = primaryResource == null ? r : primaryResource;
        primaryResource._timestamp.compareAndSet(0, now);
        if (LOG.isDebugEnabled())
            LOG.debug("Cached primary resource {}", path);
    } else {
        long last = primaryResource._timestamp.get();
        if (last < _renew && primaryResource._timestamp.compareAndSet(last, now)) {
            primaryResource._associated.clear();
            if (LOG.isDebugEnabled())
                LOG.debug("Clear associated resources for {}", path);
        }
    }
    // Push associated resources.
    if (!conditional && !primaryResource._associated.isEmpty()) {
        PushBuilder pushBuilder = jettyRequest.getPushBuilder();
        // Breadth-first push of associated resources.
        Queue<PrimaryResource> queue = new ArrayDeque<>();
        queue.offer(primaryResource);
        while (!queue.isEmpty()) {
            PrimaryResource parent = queue.poll();
            for (String childPath : parent._associated) {
                PrimaryResource child = _cache.get(childPath);
                if (child != null)
                    queue.offer(child);
                if (LOG.isDebugEnabled())
                    LOG.debug("Pushing {} for {}", childPath, path);
                pushBuilder.path(childPath).push();
            }
        }
    }
    chain.doFilter(request, resp);
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpURI(org.eclipse.jetty.http.HttpURI) ArrayDeque(java.util.ArrayDeque) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpField(org.eclipse.jetty.http.HttpField) HttpFields(org.eclipse.jetty.http.HttpFields) PushBuilder(org.eclipse.jetty.server.PushBuilder)

Aggregations

HttpURI (org.eclipse.jetty.http.HttpURI)24 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 Request (org.eclipse.jetty.server.Request)10 MetaData (org.eclipse.jetty.http.MetaData)9 HttpFields (org.eclipse.jetty.http.HttpFields)8 Stream (org.eclipse.jetty.http2.api.Stream)7 HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)7 Test (org.junit.Test)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 InetSocketAddress (java.net.InetSocketAddress)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 Session (org.eclipse.jetty.http2.api.Session)5 FuturePromise (org.eclipse.jetty.util.FuturePromise)5 Promise (org.eclipse.jetty.util.Promise)5 DataFrame (org.eclipse.jetty.http2.frames.DataFrame)4 HttpChannel (org.eclipse.jetty.server.HttpChannel)4 HttpInput (org.eclipse.jetty.server.HttpInput)4 ServerConfigService (com.thoughtworks.go.server.service.ServerConfigService)3 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)3 Callback (org.eclipse.jetty.util.Callback)3