示例#1
0
    def getChild(self, name, request):
        if name == '':
            return self

        td = '.twistd'

        if name[-len(td):] == td:
            username = name[:-len(td)]
            sub = 1
        else:
            username = name
            sub = 0
        try:
            pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
                     = self._pwd.getpwnam(username)
        except KeyError:
            return resource.NoResource()
        if sub:
            twistdsock = os.path.join(pw_dir, self.userSocketName)
            rs = ResourceSubscription('unix', twistdsock)
            self.putChild(name, rs)
            return rs
        else:
            path = os.path.join(pw_dir, self.userDirName)
            if not os.path.exists(path):
                return resource.NoResource()
            return static.File(path)
示例#2
0
 def _getResourceForRequest(self, request):
     """(Internal) Get the appropriate resource for the given host.
     """
     hostHeader = request.getHeader('host')
     if hostHeader == None:
         return self.default or resource.NoResource()
     else:
         host = hostHeader.lower().split(':', 1)[0]
     return (self.hosts.get(host, self.default) or resource.NoResource(
         "host %s not in vhost map" % repr(host)))
示例#3
0
    def getChild(self, path, request):
        fn = os.path.join(self.path, path)

        if os.path.isdir(fn):
            return ResourceScriptDirectory(fn, self.registry)
        if os.path.exists(fn):
            return ResourceScript(fn, self.registry)
        return resource.NoResource()
示例#4
0
    def render(self, request):
        """Render me to a web client.

        Load my file, execute it in a special namespace (with 'request' and
        '__file__' global vars) and finish the request.  Output to the web-page
        will NOT be handled with print - standard output goes to the log - but
        with request.write.
        """
        request.setHeader("x-powered-by","Twisted/%s" % copyright.version)
        namespace = {'request': request,
                     '__file__': self.filename,
                     'registry': self.registry}
        try:
            execfile(self.filename, namespace, namespace)
        except IOError, e:
            if e.errno == 2: #file not found
                request.setResponseCode(http.NOT_FOUND)
                request.write(resource.NoResource("File not found.").render(request))
示例#5
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.
    """

    contentTypes = loadMimeTypes()

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

    processors = {}

    indexNames = ["index", "index.html", "index.htm", "index.trp", "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.")

    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
示例#6
0
from zope.interface import implements

from cyclone.tw import server
from cyclone.tw import resource
from cyclone.tw import http
from cyclone.tw.util import redirectTo

from twisted.python import components, filepath, log
from twisted.internet import abstract, interfaces
from twisted.spread import pb
from twisted.persisted import styles
from twisted.python.util import InsensitiveDict
from twisted.python.runtime import platformType

dangerousPathError = resource.NoResource("Invalid request URL.")


def isDangerous(path):
    return path == '..' or '/' in path or os.sep in path


class Data(resource.Resource):
    """
    This is a static, in-memory resource.
    """
    def __init__(self, data, type):
        resource.Resource.__init__(self)
        self.data = data
        self.type = type
示例#7
0
 def render(self, request):
     return resource.NoResource().render(request)