Esempio n. 1
0
 def getChild(self, path, request):
     """
     By default this resource will yield a ForbiddenResource instance unless
     a request is made for a static child i.e. a child added using putChild
     """
     # override this method if you want to serve dynamic child resources
     return resource.ForbiddenResource("This is a resource namespace.")
Esempio n. 2
0
    def render_GET(self, request):
        """
        Begin sending the contents of this L{File} (or a subset of the
        contents, based on the 'range' header) to the given request.
        """
        self.restat(False)

        if self.type is None:
            self.type, self.encoding = getTypeAndEncoding(
                self.basename(), self.contentTypes, self.contentEncodings,
                self.defaultType)

        if not self.exists():
            return self.childNotFound.render(request)

        if self.isdir():
            return self.redirect(request)

        request.setHeader('accept-ranges', 'bytes')

        try:
            fileForReading = self.openForReading()
        except IOError, e:
            import errno
            if e[0] == errno.EACCES:
                return resource.ForbiddenResource().render(request)
            else:
                raise
Esempio n. 3
0
    def __init__(self):
        resource.Resource.__init__(self)
        self.newFull = NewFullResource()
        self.putChild('new_full', self.newFull)
        self.newDelta = NewDeltaResource()
        self.putChild('new_delta', self.newDelta)
        self.switch = SwitchResource()
        self.putChild('switch', self.switch)

        self.mac = resource.ForbiddenResource()
        self.newMacFull = NewMacFullResource()
        self.mac.putChild('new_full', self.newMacFull)
        self.macEdit = MacEditResource()
        self.mac.putChild('edit', self.macEdit)
        self.macDelete = MacDeleteResource()
        self.mac.putChild('delete', self.macDelete)
        self.putChild('mac', self.mac)

        self.uncensor_manage = UncensorManageResource()
        self.putChild('uncensor', self.uncensor_manage)

        self.uncensor_proxy_manage = UncensorProxyManageResource()
        self.putChild('uncensorp', self.uncensor_proxy_manage)

        self.putChild('', self)
Esempio n. 4
0
class File(resource.Resource, filepath.FilePath):
    """
    File is a resource that represents a plain non-interpreted file
    (although it can look for an extension like .rpy or .cgi and hand the
    file to a processor for interpretation if you wish). Its constructor
    takes a file path.

    Alternatively, you can give a directory path to the constructor. In this
    case the resource will represent that directory, and its children will
    be files underneath that directory. This provides access to an entire
    filesystem tree with a single Resource.

    If you map the URL 'http://server/FILE' to a resource created as
    File('/tmp'), then http://server/FILE/ will return an HTML-formatted
    listing of the /tmp/ directory, and http://server/FILE/foo/bar.html will
    return the contents of /tmp/foo/bar.html .

    @cvar childNotFound: L{Resource} used to render 404 Not Found error pages.
    @cvar forbidden: L{Resource} used to render 403 Forbidden error pages.

    @ivar contentTypes: a mapping of extensions to MIME types used to set the
        default value for the Content-Type header.
        It is initialized with the values returned by L{loadMimeTypes}.
    @type contentTypes: C{dict}

    @ivar contentEncodings: a mapping of extensions to encoding types used to
        set default value for the Content-Encoding header.
    @type contentEncodings: C{dict}
    """

    contentTypes = loadMimeTypes()

    contentEncodings = {".gz": "gzip", ".bz2": "bzip2"}

    processors = {}

    indexNames = ["index", "index.html", "index.htm", "index.rpy"]

    type = None

    def __init__(self,
                 path,
                 defaultType="text/html",
                 ignoredExts=(),
                 registry=None,
                 allowExt=0):
        """
        Create a file with the given path.

        @param path: The filename of the file from which this L{File} will
            serve data.
        @type path: C{str}

        @param defaultType: A I{major/minor}-style MIME type specifier
            indicating the I{Content-Type} with which this L{File}'s data
            will be served if a MIME type cannot be determined based on
            C{path}'s extension.
        @type defaultType: C{str}

        @param ignoredExts: A sequence giving the extensions of paths in the
            filesystem which will be ignored for the purposes of child
            lookup.  For example, if C{ignoredExts} is C{(".bar",)} and
            C{path} is a directory containing a file named C{"foo.bar"}, a
            request for the C{"foo"} child of this resource will succeed
            with a L{File} pointing to C{"foo.bar"}.

        @param registry: The registry object being used to handle this
            request.  If L{None}, one will be created.
        @type registry: L{Registry}

        @param allowExt: Ignored parameter, only present for backwards
            compatibility.  Do not pass a value for this parameter.
        """
        resource.Resource.__init__(self)
        filepath.FilePath.__init__(self, path)
        self.defaultType = defaultType
        if ignoredExts in (0, 1) or allowExt:
            warnings.warn("ignoredExts should receive a list, not a boolean")
            if ignoredExts or allowExt:
                self.ignoredExts = ['*']
            else:
                self.ignoredExts = []
        else:
            self.ignoredExts = list(ignoredExts)
        self.registry = registry or Registry()

    def ignoreExt(self, ext):
        """Ignore the given extension.

        Serve file.ext if file is requested
        """
        self.ignoredExts.append(ext)

    childNotFound = resource.NoResource("File not found.")
    forbidden = resource.ForbiddenResource()

    def directoryListing(self):
        """
        Return a resource that generates an HTML listing of the
        directory this path represents.

        @return: A resource that renders the directory to HTML.
        @rtype: L{DirectoryLister}
        """
        if _PY3:
            path = self.path
            names = self.listNames()
        else:
            # DirectoryLister works in terms of native strings, so on
            # Python 2, ensure we have a bytes paths for this
            # directory and its contents.  We use the asBytesMode
            # method inherited from FilePath to ensure consistent
            # encoding of the actual path.  This returns a FilePath
            # instance even when called on subclasses, however, so we
            # have to create a new File instance.
            nativeStringPath = self.createSimilarFile(self.asBytesMode().path)
            path = nativeStringPath.path
            names = nativeStringPath.listNames()
        return DirectoryLister(path, names, self.contentTypes,
                               self.contentEncodings, self.defaultType)

    def getChild(self, path, request):
        """
        If this L{File}"s path refers to a directory, return a L{File}
        referring to the file named C{path} in that directory.

        If C{path} is the empty string, return a L{DirectoryLister}
        instead.

        @param path: The current path segment.
        @type path: L{bytes}

        @param request: The incoming request.
        @type request: An that provides L{twisted.web.iweb.IRequest}.

        @return: A resource representing the requested file or
            directory, or L{NoResource} if the path cannot be
            accessed.
        @rtype: An object that provides L{resource.IResource}.
        """
        if isinstance(path, bytes):
            try:
                # Request calls urllib.unquote on each path segment,
                # leaving us with raw bytes.
                path = path.decode('utf-8')
            except UnicodeDecodeError:
                log.err(
                    None,
                    "Could not decode path segment as utf-8: %r" % (path, ))
                return self.childNotFound

        self.restat(reraise=False)

        if not self.isdir():
            return self.childNotFound

        if path:
            try:
                fpath = self.child(path)
            except filepath.InsecurePath:
                return self.childNotFound
        else:
            fpath = self.childSearchPreauth(*self.indexNames)
            if fpath is None:
                return self.directoryListing()

        if not fpath.exists():
            fpath = fpath.siblingExtensionSearch(*self.ignoredExts)
            if fpath is None:
                return self.childNotFound

        extension = fpath.splitext()[1]
        if platformType == "win32":
            # don't want .RPY to be different than .rpy, since that would allow
            # source disclosure.
            processor = InsensitiveDict(self.processors).get(extension)
        else:
            processor = self.processors.get(extension)
        if processor:
            return resource.IResource(processor(fpath.path, self.registry))
        return self.createSimilarFile(fpath.path)

    # methods to allow subclasses to e.g. decrypt files on the fly:
    def openForReading(self):
        """Open a file and return it."""
        return self.open()

    def getFileSize(self):
        """Return file size."""
        return self.getsize()

    def _parseRangeHeader(self, range):
        """
        Parse the value of a Range header into (start, stop) pairs.

        In a given pair, either of start or stop can be None, signifying that
        no value was provided, but not both.

        @return: A list C{[(start, stop)]} of pairs of length at least one.

        @raise ValueError: if the header is syntactically invalid or if the
            Bytes-Unit is anything other than "bytes'.
        """
        try:
            kind, value = range.split(b'=', 1)
        except ValueError:
            raise ValueError("Missing '=' separator")
        kind = kind.strip()
        if kind != b'bytes':
            raise ValueError("Unsupported Bytes-Unit: %r" % (kind, ))
        unparsedRanges = list(filter(None, map(bytes.strip,
                                               value.split(b','))))
        parsedRanges = []
        for byteRange in unparsedRanges:
            try:
                start, end = byteRange.split(b'-', 1)
            except ValueError:
                raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            if start:
                try:
                    start = int(start)
                except ValueError:
                    raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            else:
                start = None
            if end:
                try:
                    end = int(end)
                except ValueError:
                    raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            else:
                end = None
            if start is not None:
                if end is not None and start > end:
                    # Start must be less than or equal to end or it is invalid.
                    raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            elif end is None:
                # One or both of start and end must be specified.  Omitting
                # both is invalid.
                raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            parsedRanges.append((start, end))
        return parsedRanges

    def _rangeToOffsetAndSize(self, start, end):
        """
        Convert a start and end from a Range header to an offset and size.

        This method checks that the resulting range overlaps with the resource
        being served (and so has the value of C{getFileSize()} as an indirect
        input).

        Either but not both of start or end can be L{None}:

         - Omitted start means that the end value is actually a start value
           relative to the end of the resource.

         - Omitted end means the end of the resource should be the end of
           the range.

        End is interpreted as inclusive, as per RFC 2616.

        If this range doesn't overlap with any of this resource, C{(0, 0)} is
        returned, which is not otherwise a value return value.

        @param start: The start value from the header, or L{None} if one was
            not present.
        @param end: The end value from the header, or L{None} if one was not
            present.
        @return: C{(offset, size)} where offset is how far into this resource
            this resource the range begins and size is how long the range is,
            or C{(0, 0)} if the range does not overlap this resource.
        """
        size = self.getFileSize()
        if start is None:
            start = size - end
            end = size
        elif end is None:
            end = size
        elif end < size:
            end += 1
        elif end > size:
            end = size
        if start >= size:
            start = end = 0
        return start, (end - start)

    def _contentRange(self, offset, size):
        """
        Return a string suitable for the value of a Content-Range header for a
        range with the given offset and size.

        The offset and size are not sanity checked in any way.

        @param offset: How far into this resource the range begins.
        @param size: How long the range is.
        @return: The value as appropriate for the value of a Content-Range
            header.
        """
        return networkString('bytes %d-%d/%d' %
                             (offset, offset + size - 1, self.getFileSize()))

    def _doSingleRangeRequest(self, request, startAndEnd):
        """
        Set up the response for Range headers that specify a single range.

        This method checks if the request is satisfiable and sets the response
        code and Content-Range header appropriately.  The return value
        indicates which part of the resource to return.

        @param request: The Request object.
        @param startAndEnd: A 2-tuple of start of the byte range as specified by
            the header and the end of the byte range as specified by the header.
            At most one of the start and end may be L{None}.
        @return: A 2-tuple of the offset and size of the range to return.
            offset == size == 0 indicates that the request is not satisfiable.
        """
        start, end = startAndEnd
        offset, size = self._rangeToOffsetAndSize(start, end)
        if offset == size == 0:
            # This range doesn't overlap with any of this resource, so the
            # request is unsatisfiable.
            request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
            request.setHeader(
                b'content-range',
                networkString('bytes */%d' % (self.getFileSize(), )))
        else:
            request.setResponseCode(http.PARTIAL_CONTENT)
            request.setHeader(b'content-range',
                              self._contentRange(offset, size))
        return offset, size

    def _doMultipleRangeRequest(self, request, byteRanges):
        """
        Set up the response for Range headers that specify a single range.

        This method checks if the request is satisfiable and sets the response
        code and Content-Type and Content-Length headers appropriately.  The
        return value, which is a little complicated, indicates which parts of
        the resource to return and the boundaries that should separate the
        parts.

        In detail, the return value is a tuple rangeInfo C{rangeInfo} is a
        list of 3-tuples C{(partSeparator, partOffset, partSize)}.  The
        response to this request should be, for each element of C{rangeInfo},
        C{partSeparator} followed by C{partSize} bytes of the resource
        starting at C{partOffset}.  Each C{partSeparator} includes the
        MIME-style boundary and the part-specific Content-type and
        Content-range headers.  It is convenient to return the separator as a
        concrete string from this method, because this method needs to compute
        the number of bytes that will make up the response to be able to set
        the Content-Length header of the response accurately.

        @param request: The Request object.
        @param byteRanges: A list of C{(start, end)} values as specified by
            the header.  For each range, at most one of C{start} and C{end}
            may be L{None}.
        @return: See above.
        """
        matchingRangeFound = False
        rangeInfo = []
        contentLength = 0
        boundary = networkString("%x%x" %
                                 (int(time.time() * 1000000), os.getpid()))
        if self.type:
            contentType = self.type
        else:
            contentType = b'bytes'  # It's what Apache does...
        for start, end in byteRanges:
            partOffset, partSize = self._rangeToOffsetAndSize(start, end)
            if partOffset == partSize == 0:
                continue
            contentLength += partSize
            matchingRangeFound = True
            partContentRange = self._contentRange(partOffset, partSize)
            partSeparator = networkString(
                ("\r\n"
                 "--%s\r\n"
                 "Content-type: %s\r\n"
                 "Content-range: %s\r\n"
                 "\r\n") % (nativeString(boundary), nativeString(contentType),
                            nativeString(partContentRange)))
            contentLength += len(partSeparator)
            rangeInfo.append((partSeparator, partOffset, partSize))
        if not matchingRangeFound:
            request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
            request.setHeader(b'content-length', b'0')
            request.setHeader(
                b'content-range',
                networkString('bytes */%d' % (self.getFileSize(), )))
            return [], b''
        finalBoundary = b"\r\n--" + boundary + b"--\r\n"
        rangeInfo.append((finalBoundary, 0, 0))
        request.setResponseCode(http.PARTIAL_CONTENT)
        request.setHeader(
            b'content-type',
            networkString('multipart/byteranges; boundary="%s"' %
                          (nativeString(boundary), )))
        request.setHeader(b'content-length',
                          intToBytes(contentLength + len(finalBoundary)))
        return rangeInfo

    def _setContentHeaders(self, request, size=None):
        """
        Set the Content-length and Content-type headers for this request.

        This method is not appropriate for requests for multiple byte ranges;
        L{_doMultipleRangeRequest} will set these headers in that case.

        @param request: The L{twisted.web.http.Request} object.
        @param size: The size of the response.  If not specified, default to
            C{self.getFileSize()}.
        """
        if size is None:
            size = self.getFileSize()
        request.setHeader(b'content-length', intToBytes(size))
        if self.type:
            request.setHeader(b'content-type', networkString(self.type))
        if self.encoding:
            request.setHeader(b'content-encoding',
                              networkString(self.encoding))

    def makeProducer(self, request, fileForReading):
        """
        Make a L{StaticProducer} that will produce the body of this response.

        This method will also set the response code and Content-* headers.

        @param request: The L{twisted.web.http.Request} object.
        @param fileForReading: The file object containing the resource.
        @return: A L{StaticProducer}.  Calling C{.start()} on this will begin
            producing the response.
        """
        byteRange = request.getHeader(b'range')
        if byteRange is None:
            self._setContentHeaders(request)
            request.setResponseCode(http.OK)
            return NoRangeStaticProducer(request, fileForReading)
        try:
            parsedRanges = self._parseRangeHeader(byteRange)
        except ValueError:
            log.msg("Ignoring malformed Range header %r" %
                    (byteRange.decode(), ))
            self._setContentHeaders(request)
            request.setResponseCode(http.OK)
            return NoRangeStaticProducer(request, fileForReading)

        if len(parsedRanges) == 1:
            offset, size = self._doSingleRangeRequest(request, parsedRanges[0])
            self._setContentHeaders(request, size)
            return SingleRangeStaticProducer(request, fileForReading, offset,
                                             size)
        else:
            rangeInfo = self._doMultipleRangeRequest(request, parsedRanges)
            return MultipleRangeStaticProducer(request, fileForReading,
                                               rangeInfo)

    def render_GET(self, request):
        """
        Begin sending the contents of this L{File} (or a subset of the
        contents, based on the 'range' header) to the given request.
        """
        self.restat(False)

        if self.type is None:
            self.type, self.encoding = getTypeAndEncoding(
                self.basename(), self.contentTypes, self.contentEncodings,
                self.defaultType)

        if not self.exists():
            return self.childNotFound.render(request)

        if self.isdir():
            return self.redirect(request)

        request.setHeader(b'accept-ranges', b'bytes')

        try:
            fileForReading = self.openForReading()
        except IOError as e:
            if e.errno == errno.EACCES:
                return self.forbidden.render(request)
            else:
                raise

        if request.setLastModified(self.getModificationTime()) is http.CACHED:
            # `setLastModified` also sets the response code for us, so if the
            # request is cached, we close the file now that we've made sure that
            # the request would otherwise succeed and return an empty body.
            fileForReading.close()
            return b''

        if request.method == b'HEAD':
            # Set the content headers here, rather than making a producer.
            self._setContentHeaders(request)
            # We've opened the file to make sure it's accessible, so close it
            # now that we don't need it.
            fileForReading.close()
            return b''

        producer = self.makeProducer(request, fileForReading)
        producer.start()

        # and make sure the connection doesn't get closed
        return server.NOT_DONE_YET

    render_HEAD = render_GET

    def redirect(self, request):
        return redirectTo(_addSlash(request), request)

    def listNames(self):
        if not self.isdir():
            return []
        directory = self.listdir()
        directory.sort()
        return directory

    def listEntities(self):
        return list(
            map(lambda fileName, self=self: self.createSimilarFile(
                os.path.join(self.path, fileName)),
                self.listNames()))

    def createSimilarFile(self, path):
        f = self.__class__(path, self.defaultType, self.ignoredExts,
                           self.registry)
        # refactoring by steps, here - constructor should almost certainly take these
        f.processors = self.processors
        f.indexNames = self.indexNames[:]
        f.childNotFound = self.childNotFound
        return f
Esempio n. 5
0
    def render(self, request):
        # print ''
        # print 'BufferFile', request

        # FIXME detect when request is REALLY finished
        if request is None or request.finished:
            logger.info('No request to render!')
            return ''
        '''You know what you doing.'''
        self.restat()

        if self.type is None:
            self.type, self.encoding = static.getTypeAndEncoding(
                self.basename(), self.contentTypes, self.contentEncodings,
                self.defaultType)

        if not self.exists():
            return self.childNotFound.render(request)

        if self.isdir():
            return self.redirect(request)

        # for content-length
        if (self.target_size > 0):
            fsize = size = int(self.target_size)
        else:
            fsize = size = int(self.getFileSize())

        # print fsize

        if size == int(self.getFileSize()):
            request.setHeader(b'accept-ranges', b'bytes')

        if self.type:
            request.setHeader(b'content-type', to_bytes(self.type))
        if self.encoding:
            request.setHeader(b'content-encoding', to_bytes(self.encoding))

        try:
            f = self.openForReading()
        except IOError as e:
            import errno
            if e.errno == errno.EACCES:
                return resource.ForbiddenResource().render(request)
            else:
                raise
        if request.setLastModified(self.getmtime()) is http.CACHED:
            return ''
        trans = True

        range = request.getHeader('range')
        # print 'StaticFile', range

        tsize = size
        if range is not None:
            # This is a request for partial data...
            bytesrange = range.split('=')
            assert bytesrange[0] == 'bytes', \
                'Syntactically invalid http range header!'
            start, end = bytesrange[1].split('-', 1)
            if start:
                start = int(start)
                # Are we requesting something
                # beyond the current size of the file?
                if (start >= self.getFileSize()):
                    # Retry later!
                    logger.info(bytesrange)
                    logger.info('Requesting data beyond current scope -> '
                                'postpone rendering!')
                    self.upnp_retry = reactor.callLater(
                        1.0, self.render, request)
                    return server.NOT_DONE_YET

                f.seek(start)
                if end:
                    # print(f':{end}')
                    end = int(end)
                else:
                    end = size - 1
            else:
                lastbytes = int(end)
                if size < lastbytes:
                    lastbytes = size
                start = size - lastbytes
                f.seek(start)
                fsize = lastbytes
                end = size - 1
            size = end + 1
            fsize = end - int(start) + 1
            # start is the byte offset to begin, and end is the byte offset
            # to end..  fsize is size to send, tsize is the real size of
            # the file, and size is the byte position to stop sending.
            if fsize <= 0:
                request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
                fsize = tsize
                trans = False
            else:
                request.setResponseCode(http.PARTIAL_CONTENT)
                request.setHeader(
                    b'content-range',
                    (f'bytes {str(start)}-{str(end)}/{str(tsize)} '
                     ).encode('ascii'))
                # print 'StaticFile', start, end, tsize

        request.setHeader('content-length', str(fsize))

        if request.method == b'HEAD' or trans is False:
            # pretend we're a HEAD request, so content-length
            # won't be overwritten.
            request.method = b'HEAD'
            return ''
        # print 'StaticFile out', request.headers, request.code

        # return data
        # size is the byte position to stop sending, not how many bytes to send

        BufferFileTransfer(f, size - f.tell(), request)
        # and make sure the connection doesn't get closed
        return server.NOT_DONE_YET
Esempio n. 6
0
 def directoryListing(self):
     # Override to forbid directory listing
     return resource.ForbiddenResource()
Esempio n. 7
0
 def directoryListing(self):
     return resource.ForbiddenResource()
Esempio n. 8
0
class File(resource.Resource, styles.Versioned, filepath.FilePath):
    """
    File is a resource that represents a plain non-interpreted file
    (although it can look for an extension like .rpy or .cgi and hand the
    file to a processor for interpretation if you wish). Its constructor
    takes a file path.

    Alternatively, you can give a directory path to the constructor. In this
    case the resource will represent that directory, and its children will
    be files underneath that directory. This provides access to an entire
    filesystem tree with a single Resource.

    If you map the URL 'http://server/FILE' to a resource created as
    File('/tmp'), then http://server/FILE/ will return an HTML-formatted
    listing of the /tmp/ directory, and http://server/FILE/foo/bar.html will
    return the contents of /tmp/foo/bar.html .

    @cvar childNotFound: L{Resource} used to render 404 Not Found error pages.
    @cvar forbidden: L{Resource} used to render 403 Forbidden error pages.
    """

    contentTypes = loadMimeTypes()

    contentEncodings = {".gz": "gzip", ".bz2": "bzip2"}

    processors = {}

    indexNames = ["index", "index.html", "index.htm", "index.rpy"]

    type = None

    ### Versioning

    persistenceVersion = 6

    def upgradeToVersion6(self):
        self.ignoredExts = []
        if self.allowExt:
            self.ignoreExt("*")
        del self.allowExt

    def upgradeToVersion5(self):
        if not isinstance(self.registry, Registry):
            self.registry = Registry()

    def upgradeToVersion4(self):
        if not hasattr(self, 'registry'):
            self.registry = {}

    def upgradeToVersion3(self):
        if not hasattr(self, 'allowExt'):
            self.allowExt = 0

    def upgradeToVersion2(self):
        self.defaultType = "text/html"

    def upgradeToVersion1(self):
        if hasattr(self, 'indexName'):
            self.indexNames = [self.indexName]
            del self.indexName

    def __init__(self,
                 path,
                 defaultType="text/html",
                 ignoredExts=(),
                 registry=None,
                 allowExt=0):
        """
        Create a file with the given path.

        @param path: The filename of the file from which this L{File} will
            serve data.
        @type path: C{str}

        @param defaultType: A I{major/minor}-style MIME type specifier
            indicating the I{Content-Type} with which this L{File}'s data
            will be served if a MIME type cannot be determined based on
            C{path}'s extension.
        @type defaultType: C{str}

        @param ignoredExts: A sequence giving the extensions of paths in the
            filesystem which will be ignored for the purposes of child
            lookup.  For example, if C{ignoredExts} is C{(".bar",)} and
            C{path} is a directory containing a file named C{"foo.bar"}, a
            request for the C{"foo"} child of this resource will succeed
            with a L{File} pointing to C{"foo.bar"}.

        @param registry: The registry object being used to handle this
            request.  If C{None}, one will be created.
        @type registry: L{Registry}

        @param allowExt: Ignored parameter, only present for backwards
            compatibility.  Do not pass a value for this parameter.
        """
        resource.Resource.__init__(self)
        filepath.FilePath.__init__(self, path)
        self.defaultType = defaultType
        if ignoredExts in (0, 1) or allowExt:
            warnings.warn("ignoredExts should receive a list, not a boolean")
            if ignoredExts or allowExt:
                self.ignoredExts = ['*']
            else:
                self.ignoredExts = []
        else:
            self.ignoredExts = list(ignoredExts)
        self.registry = registry or Registry()

    def ignoreExt(self, ext):
        """Ignore the given extension.

        Serve file.ext if file is requested
        """
        self.ignoredExts.append(ext)

    childNotFound = resource.NoResource("File not found.")
    forbidden = resource.ForbiddenResource()

    def directoryListing(self):
        return DirectoryLister(self.path, self.listNames(), self.contentTypes,
                               self.contentEncodings, self.defaultType)

    def getChild(self, path, request):
        """
        If this L{File}'s path refers to a directory, return a L{File}
        referring to the file named C{path} in that directory.

        If C{path} is the empty string, return a L{DirectoryLister} instead.
        """
        self.restat(reraise=False)

        if not self.isdir():
            return self.childNotFound

        if path:
            try:
                fpath = self.child(path)
            except filepath.InsecurePath:
                return self.childNotFound
        else:
            fpath = self.childSearchPreauth(*self.indexNames)
            if fpath is None:
                return self.directoryListing()

        if not fpath.exists():
            fpath = fpath.siblingExtensionSearch(*self.ignoredExts)
            if fpath is None:
                return self.childNotFound

        if platformType == "win32":
            # don't want .RPY to be different than .rpy, since that would allow
            # source disclosure.
            processor = InsensitiveDict(self.processors).get(
                fpath.splitext()[1])
        else:
            processor = self.processors.get(fpath.splitext()[1])
        if processor:
            return resource.IResource(processor(fpath.path, self.registry))
        return self.createSimilarFile(fpath.path)

    # methods to allow subclasses to e.g. decrypt files on the fly:
    def openForReading(self):
        """Open a file and return it."""
        return self.open()

    def getFileSize(self):
        """Return file size."""
        return self.getsize()

    def _parseRangeHeader(self, range):
        """
        Parse the value of a Range header into (start, stop) pairs.

        In a given pair, either of start or stop can be None, signifying that
        no value was provided, but not both.

        @return: A list C{[(start, stop)]} of pairs of length at least one.

        @raise ValueError: if the header is syntactically invalid or if the
            Bytes-Unit is anything other than 'bytes'.
        """
        try:
            kind, value = range.split('=', 1)
        except ValueError:
            raise ValueError("Missing '=' separator")
        kind = kind.strip()
        if kind != 'bytes':
            raise ValueError("Unsupported Bytes-Unit: %r" % (kind, ))
        unparsedRanges = filter(None, map(str.strip, value.split(',')))
        parsedRanges = []
        for byteRange in unparsedRanges:
            try:
                start, end = byteRange.split('-', 1)
            except ValueError:
                raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            if start:
                try:
                    start = int(start)
                except ValueError:
                    raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            else:
                start = None
            if end:
                try:
                    end = int(end)
                except ValueError:
                    raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            else:
                end = None
            if start is not None:
                if end is not None and start > end:
                    # Start must be less than or equal to end or it is invalid.
                    raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            elif end is None:
                # One or both of start and end must be specified.  Omitting
                # both is invalid.
                raise ValueError("Invalid Byte-Range: %r" % (byteRange, ))
            parsedRanges.append((start, end))
        return parsedRanges

    def _rangeToOffsetAndSize(self, start, end):
        """
        Convert a start and end from a Range header to an offset and size.

        This method checks that the resulting range overlaps with the resource
        being served (and so has the value of C{getFileSize()} as an indirect
        input).

        Either but not both of start or end can be C{None}:

         - Omitted start means that the end value is actually a start value
           relative to the end of the resource.

         - Omitted end means the end of the resource should be the end of
           the range.

        End is interpreted as inclusive, as per RFC 2616.

        If this range doesn't overlap with any of this resource, C{(0, 0)} is
        returned, which is not otherwise a value return value.

        @param start: The start value from the header, or C{None} if one was
            not present.
        @param end: The end value from the header, or C{None} if one was not
            present.
        @return: C{(offset, size)} where offset is how far into this resource
            this resource the range begins and size is how long the range is,
            or C{(0, 0)} if the range does not overlap this resource.
        """
        size = self.getFileSize()
        if start is None:
            start = size - end
            end = size
        elif end is None:
            end = size
        elif end < size:
            end += 1
        elif end > size:
            end = size
        if start >= size:
            start = end = 0
        return start, (end - start)

    def _contentRange(self, offset, size):
        """
        Return a string suitable for the value of a Content-Range header for a
        range with the given offset and size.

        The offset and size are not sanity checked in any way.

        @param offset: How far into this resource the range begins.
        @param size: How long the range is.
        @return: The value as appropriate for the value of a Content-Range
            header.
        """
        return 'bytes %d-%d/%d' % (offset, offset + size - 1,
                                   self.getFileSize())

    def _doSingleRangeRequest(self, request, (start, end)):
        """
        Set up the response for Range headers that specify a single range.

        This method checks if the request is satisfiable and sets the response
        code and Content-Range header appropriately.  The return value
        indicates which part of the resource to return.

        @param request: The Request object.
        @param start: The start of the byte range as specified by the header.
        @param end: The end of the byte range as specified by the header.  At
            most one of C{start} and C{end} may be C{None}.
        @return: A 2-tuple of the offset and size of the range to return.
            offset == size == 0 indicates that the request is not satisfiable.
        """
        offset, size = self._rangeToOffsetAndSize(start, end)
        if offset == size == 0:
            # This range doesn't overlap with any of this resource, so the
            # request is unsatisfiable.
            request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
            request.setHeader('content-range',
                              'bytes */%d' % (self.getFileSize(), ))
        else:
            request.setResponseCode(http.PARTIAL_CONTENT)
            request.setHeader('content-range',
                              self._contentRange(offset, size))
        return offset, size