Search in sources :

Example 1 with ByteRange

use of io.undertow.util.ByteRange in project undertow by undertow-io.

the class DefaultServlet method serveFileBlocking.

private void serveFileBlocking(final HttpServletRequest req, final HttpServletResponse resp, final Resource resource) throws IOException {
    final ETag etag = resource.getETag();
    final Date lastModified = resource.getLastModified();
    if (req.getDispatcherType() != DispatcherType.INCLUDE) {
        if (!ETagUtils.handleIfMatch(req.getHeader(Headers.IF_MATCH_STRING), etag, false) || !DateUtils.handleIfUnmodifiedSince(req.getHeader(Headers.IF_UNMODIFIED_SINCE_STRING), lastModified)) {
            resp.setStatus(StatusCodes.PRECONDITION_FAILED);
            return;
        }
        if (!ETagUtils.handleIfNoneMatch(req.getHeader(Headers.IF_NONE_MATCH_STRING), etag, true) || !DateUtils.handleIfModifiedSince(req.getHeader(Headers.IF_MODIFIED_SINCE_STRING), lastModified)) {
            resp.setStatus(StatusCodes.NOT_MODIFIED);
            return;
        }
    }
    //we are going to proceed. Set the appropriate headers
    if (resp.getContentType() == null) {
        if (!resource.isDirectory()) {
            final String contentType = deployment.getServletContext().getMimeType(resource.getName());
            if (contentType != null) {
                resp.setContentType(contentType);
            } else {
                resp.setContentType("application/octet-stream");
            }
        }
    }
    if (lastModified != null) {
        resp.setHeader(Headers.LAST_MODIFIED_STRING, resource.getLastModifiedString());
    }
    if (etag != null) {
        resp.setHeader(Headers.ETAG_STRING, etag.toString());
    }
    ByteRange.RangeResponseResult rangeResponse = null;
    long start = -1, end = -1;
    try {
        //only set the content length if we are using a stream
        //if we are using a writer who knows what the length will end up being
        //todo: if someone installs a filter this can cause problems
        //not sure how best to deal with this
        //we also can't deal with range requests if a writer is in use
        Long contentLength = resource.getContentLength();
        if (contentLength != null) {
            resp.getOutputStream();
            if (contentLength > Integer.MAX_VALUE) {
                resp.setContentLengthLong(contentLength);
            } else {
                resp.setContentLength(contentLength.intValue());
            }
            if (resource instanceof RangeAwareResource && ((RangeAwareResource) resource).isRangeSupported() && resource.getContentLength() != null) {
                resp.setHeader(Headers.ACCEPT_RANGES_STRING, "bytes");
                //TODO: figure out what to do with the content encoded resource manager
                final ByteRange range = ByteRange.parse(req.getHeader(Headers.RANGE_STRING));
                if (range != null) {
                    rangeResponse = range.getResponseResult(resource.getContentLength(), req.getHeader(Headers.IF_RANGE_STRING), resource.getLastModified(), resource.getETag() == null ? null : resource.getETag().getTag());
                    if (rangeResponse != null) {
                        start = rangeResponse.getStart();
                        end = rangeResponse.getEnd();
                        resp.setStatus(rangeResponse.getStatusCode());
                        resp.setHeader(Headers.CONTENT_RANGE_STRING, rangeResponse.getContentRange());
                        long length = rangeResponse.getContentLength();
                        if (length > Integer.MAX_VALUE) {
                            resp.setContentLengthLong(length);
                        } else {
                            resp.setContentLength((int) length);
                        }
                        if (rangeResponse.getStatusCode() == StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE) {
                            return;
                        }
                    }
                }
            }
        }
    } catch (IllegalStateException e) {
    }
    final boolean include = req.getDispatcherType() == DispatcherType.INCLUDE;
    if (!req.getMethod().equals(Methods.HEAD_STRING)) {
        HttpServerExchange exchange = SecurityActions.requireCurrentServletRequestContext().getOriginalRequest().getExchange();
        if (rangeResponse == null) {
            resource.serve(exchange.getResponseSender(), exchange, completionCallback(include));
        } else {
            ((RangeAwareResource) resource).serveRange(exchange.getResponseSender(), exchange, start, end, completionCallback(include));
        }
    }
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) ETag(io.undertow.util.ETag) ByteRange(io.undertow.util.ByteRange) RangeAwareResource(io.undertow.server.handlers.resource.RangeAwareResource) Date(java.util.Date)

Example 2 with ByteRange

use of io.undertow.util.ByteRange in project undertow by undertow-io.

the class ByteRangeHandler method handleRequest.

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    //range requests are only support for GET requests as per the RFC
    if (!Methods.GET.equals(exchange.getRequestMethod()) && !Methods.HEAD.equals(exchange.getRequestMethod())) {
        next.handleRequest(exchange);
        return;
    }
    if (sendAcceptRanges) {
        exchange.addResponseCommitListener(ACCEPT_RANGE_LISTENER);
    }
    final ByteRange range = ByteRange.parse(exchange.getRequestHeaders().getFirst(Headers.RANGE));
    if (range != null && range.getRanges() == 1) {
        exchange.addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() {

            @Override
            public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) {
                if (exchange.getStatusCode() != StatusCodes.OK) {
                    return factory.create();
                }
                String length = exchange.getResponseHeaders().getFirst(Headers.CONTENT_LENGTH);
                if (length == null) {
                    return factory.create();
                }
                long responseLength = Long.parseLong(length);
                ByteRange.RangeResponseResult rangeResponse = range.getResponseResult(responseLength, exchange.getRequestHeaders().getFirst(Headers.IF_RANGE), DateUtils.parseDate(exchange.getResponseHeaders().getFirst(Headers.LAST_MODIFIED)), exchange.getResponseHeaders().getFirst(Headers.ETAG));
                if (rangeResponse != null) {
                    long start = rangeResponse.getStart();
                    long end = rangeResponse.getEnd();
                    exchange.setStatusCode(rangeResponse.getStatusCode());
                    exchange.getResponseHeaders().put(Headers.CONTENT_RANGE, rangeResponse.getContentRange());
                    exchange.setResponseContentLength(rangeResponse.getContentLength());
                    if (rangeResponse.getStatusCode() == StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE) {
                        return new HeadStreamSinkConduit(factory.create(), null, true);
                    }
                    return new RangeStreamSinkConduit(factory.create(), start, end, responseLength);
                } else {
                    return factory.create();
                }
            }
        });
    }
    next.handleRequest(exchange);
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) RangeStreamSinkConduit(io.undertow.conduits.RangeStreamSinkConduit) ByteRange(io.undertow.util.ByteRange) HeadStreamSinkConduit(io.undertow.conduits.HeadStreamSinkConduit) RangeStreamSinkConduit(io.undertow.conduits.RangeStreamSinkConduit) StreamSinkConduit(org.xnio.conduits.StreamSinkConduit) HeadStreamSinkConduit(io.undertow.conduits.HeadStreamSinkConduit)

Example 3 with ByteRange

use of io.undertow.util.ByteRange in project undertow by undertow-io.

the class ResourceHandler method serveResource.

private void serveResource(final HttpServerExchange exchange, final boolean sendContent) throws Exception {
    if (DirectoryUtils.sendRequestedBlobs(exchange)) {
        return;
    }
    if (!allowed.resolve(exchange)) {
        exchange.setStatusCode(StatusCodes.FORBIDDEN);
        exchange.endExchange();
        return;
    }
    ResponseCache cache = exchange.getAttachment(ResponseCache.ATTACHMENT_KEY);
    final boolean cachable = this.cachable.resolve(exchange);
    //we set caching headers before we try and serve from the cache
    if (cachable && cacheTime != null) {
        exchange.getResponseHeaders().put(Headers.CACHE_CONTROL, "public, max-age=" + cacheTime);
        long date = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(cacheTime);
        String dateHeader = DateUtils.toDateString(new Date(date));
        exchange.getResponseHeaders().put(Headers.EXPIRES, dateHeader);
    }
    if (cache != null && cachable) {
        if (cache.tryServeResponse()) {
            return;
        }
    }
    //we now dispatch to a worker thread
    //as resource manager methods are potentially blocking
    HttpHandler dispatchTask = new HttpHandler() {

        @Override
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            Resource resource = null;
            try {
                if (File.separatorChar == '/' || !exchange.getRelativePath().contains(File.separator)) {
                    //we don't process resources that contain the sperator character if this is not /
                    //this prevents attacks where people use windows path seperators in file URLS's
                    resource = resourceManager.getResource(canonicalize(exchange.getRelativePath()));
                }
            } catch (IOException e) {
                clearCacheHeaders(exchange);
                UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
                exchange.endExchange();
                return;
            }
            if (resource == null) {
                clearCacheHeaders(exchange);
                //usually a 404 handler
                next.handleRequest(exchange);
                return;
            }
            if (resource.isDirectory()) {
                Resource indexResource;
                try {
                    indexResource = getIndexFiles(resourceManager, resource.getPath(), welcomeFiles);
                } catch (IOException e) {
                    UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                    exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
                    exchange.endExchange();
                    return;
                }
                if (indexResource == null) {
                    if (directoryListingEnabled) {
                        DirectoryUtils.renderDirectoryListing(exchange, resource);
                        return;
                    } else {
                        exchange.setStatusCode(StatusCodes.FORBIDDEN);
                        exchange.endExchange();
                        return;
                    }
                } else if (!exchange.getRequestPath().endsWith("/")) {
                    exchange.setStatusCode(StatusCodes.FOUND);
                    exchange.getResponseHeaders().put(Headers.LOCATION, RedirectBuilder.redirect(exchange, exchange.getRelativePath() + "/", true));
                    exchange.endExchange();
                    return;
                }
                resource = indexResource;
            } else if (exchange.getRelativePath().endsWith("/")) {
                //UNDERTOW-432
                exchange.setStatusCode(StatusCodes.NOT_FOUND);
                exchange.endExchange();
                return;
            }
            final ETag etag = resource.getETag();
            final Date lastModified = resource.getLastModified();
            if (!ETagUtils.handleIfMatch(exchange, etag, false) || !DateUtils.handleIfUnmodifiedSince(exchange, lastModified)) {
                exchange.setStatusCode(StatusCodes.PRECONDITION_FAILED);
                exchange.endExchange();
                return;
            }
            if (!ETagUtils.handleIfNoneMatch(exchange, etag, true) || !DateUtils.handleIfModifiedSince(exchange, lastModified)) {
                exchange.setStatusCode(StatusCodes.NOT_MODIFIED);
                exchange.endExchange();
                return;
            }
            final ContentEncodedResourceManager contentEncodedResourceManager = ResourceHandler.this.contentEncodedResourceManager;
            Long contentLength = resource.getContentLength();
            if (contentLength != null && !exchange.getResponseHeaders().contains(Headers.TRANSFER_ENCODING)) {
                exchange.setResponseContentLength(contentLength);
            }
            ByteRange.RangeResponseResult rangeResponse = null;
            long start = -1, end = -1;
            if (resource instanceof RangeAwareResource && ((RangeAwareResource) resource).isRangeSupported() && contentLength != null && contentEncodedResourceManager == null) {
                exchange.getResponseHeaders().put(Headers.ACCEPT_RANGES, "bytes");
                //TODO: figure out what to do with the content encoded resource manager
                ByteRange range = ByteRange.parse(exchange.getRequestHeaders().getFirst(Headers.RANGE));
                if (range != null && range.getRanges() == 1 && resource.getContentLength() != null) {
                    rangeResponse = range.getResponseResult(resource.getContentLength(), exchange.getRequestHeaders().getFirst(Headers.IF_RANGE), resource.getLastModified(), resource.getETag() == null ? null : resource.getETag().getTag());
                    if (rangeResponse != null) {
                        start = rangeResponse.getStart();
                        end = rangeResponse.getEnd();
                        exchange.setStatusCode(rangeResponse.getStatusCode());
                        exchange.getResponseHeaders().put(Headers.CONTENT_RANGE, rangeResponse.getContentRange());
                        long length = rangeResponse.getContentLength();
                        exchange.setResponseContentLength(length);
                        if (rangeResponse.getStatusCode() == StatusCodes.REQUEST_RANGE_NOT_SATISFIABLE) {
                            return;
                        }
                    }
                }
            }
            if (!exchange.getResponseHeaders().contains(Headers.CONTENT_TYPE)) {
                final String contentType = resource.getContentType(mimeMappings);
                if (contentType != null) {
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, contentType);
                } else {
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/octet-stream");
                }
            }
            if (lastModified != null) {
                exchange.getResponseHeaders().put(Headers.LAST_MODIFIED, resource.getLastModifiedString());
            }
            if (etag != null) {
                exchange.getResponseHeaders().put(Headers.ETAG, etag.toString());
            }
            if (contentEncodedResourceManager != null) {
                try {
                    ContentEncodedResource encoded = contentEncodedResourceManager.getResource(resource, exchange);
                    if (encoded != null) {
                        exchange.getResponseHeaders().put(Headers.CONTENT_ENCODING, encoded.getContentEncoding());
                        exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, encoded.getResource().getContentLength());
                        encoded.getResource().serve(exchange.getResponseSender(), exchange, IoCallback.END_EXCHANGE);
                        return;
                    }
                } catch (IOException e) {
                    //TODO: should this be fatal
                    UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
                    exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
                    exchange.endExchange();
                    return;
                }
            }
            if (!sendContent) {
                exchange.endExchange();
            } else if (rangeResponse != null) {
                ((RangeAwareResource) resource).serveRange(exchange.getResponseSender(), exchange, start, end, IoCallback.END_EXCHANGE);
            } else {
                resource.serve(exchange.getResponseSender(), exchange, IoCallback.END_EXCHANGE);
            }
        }
    };
    if (exchange.isInIoThread()) {
        exchange.dispatch(dispatchTask);
    } else {
        dispatchTask.handleRequest(exchange);
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) ByteRange(io.undertow.util.ByteRange) ContentEncodedResource(io.undertow.server.handlers.encoding.ContentEncodedResource) HttpString(io.undertow.util.HttpString) IOException(java.io.IOException) ContentEncodedResource(io.undertow.server.handlers.encoding.ContentEncodedResource) Date(java.util.Date) HttpServerExchange(io.undertow.server.HttpServerExchange) ContentEncodedResourceManager(io.undertow.server.handlers.encoding.ContentEncodedResourceManager) ETag(io.undertow.util.ETag) ResponseCache(io.undertow.server.handlers.cache.ResponseCache)

Aggregations

HttpServerExchange (io.undertow.server.HttpServerExchange)3 ByteRange (io.undertow.util.ByteRange)3 ETag (io.undertow.util.ETag)2 Date (java.util.Date)2 HeadStreamSinkConduit (io.undertow.conduits.HeadStreamSinkConduit)1 RangeStreamSinkConduit (io.undertow.conduits.RangeStreamSinkConduit)1 HttpHandler (io.undertow.server.HttpHandler)1 ResponseCache (io.undertow.server.handlers.cache.ResponseCache)1 ContentEncodedResource (io.undertow.server.handlers.encoding.ContentEncodedResource)1 ContentEncodedResourceManager (io.undertow.server.handlers.encoding.ContentEncodedResourceManager)1 RangeAwareResource (io.undertow.server.handlers.resource.RangeAwareResource)1 HttpString (io.undertow.util.HttpString)1 IOException (java.io.IOException)1 StreamSinkConduit (org.xnio.conduits.StreamSinkConduit)1