    001// Copyright 2010, 2013 The Apache Software Foundation
    002//
    003// Licensed under the Apache License, Version 2.0 (the "License");
    004// you may not use this file except in compliance with the License.
    005// You may obtain a copy of the License at
    006//
    007// http://www.apache.org/licenses/LICENSE-2.0
    008//
    009// Unless required by applicable law or agreed to in writing, software
    010// distributed under the License is distributed on an "AS IS" BASIS,
    011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    012// See the License for the specific language governing permissions and
    013// limitations under the License.
    014
    015package org.apache.tapestry5.internal.services.assets;
    016
    017import org.apache.tapestry5.commons.Resource;
    018import org.apache.tapestry5.http.services.Request;
    019import org.apache.tapestry5.http.services.Response;
    020import org.apache.tapestry5.internal.services.ResourceStreamer;
    021import org.apache.tapestry5.services.assets.AssetRequestHandler;
    022
    023import java.io.IOException;
    024import java.util.regex.Pattern;
    025
    026/**
    027 * Handles requests for context assets, screening out attempt to
    028 * access anything under WEB-INF or META-INF.
    029 *
    030 * @since 5.2.0
    031 */
    032public class ContextAssetRequestHandler implements AssetRequestHandler
    033{
    034    private final ResourceStreamer resourceStreamer;
    035
    036    private final Resource rootContextResource;
    037
    038    private final Pattern illegal = Pattern.compile("^([\\\\/]*((web|meta)-inf.*)|(.*\\.tml$))", Pattern.CASE_INSENSITIVE);
    039
    040    public ContextAssetRequestHandler(ResourceStreamer resourceStreamer, Resource rootContextResource)
    041    {
    042        this.resourceStreamer = resourceStreamer;
    043        this.rootContextResource = rootContextResource;
    044    }
    045
    046    public boolean handleAssetRequest(Request request, Response response, String extraPath) throws IOException
    047    {
    048        ChecksumPath path = new ChecksumPath(resourceStreamer, null, extraPath);
    049
    050        if (illegal.matcher(path.resourcePath).matches())
    051        {
    052            return false;
    053        }
    054
    055        return path.stream(rootContextResource.forFile(path.resourcePath));
    056    }
    057
    058}