Ejemplo n.º 1
0
    def renderHTTP(self, request):
        """
        Authenticate the request then return the result of calling renderHTTP
        on C{self.wrappedResource}
        """
        if request.method not in self.allowedMethods():
            response = http.Response(responsecode.NOT_ALLOWED)
            response.headers.setHeader("allow", self.allowedMethods())
            return response

        def _renderResource(resource):
            return resource.renderHTTP(request)

        def _finished_reading(ignore, result):
            data = ''.join(result)
            request.attachment = data
            d = self.authenticate(request)
            d.addCallback(_renderResource)
            return d

        if request.method in ('PUT', 'DELETE'):
            # we need to authenticate the request after all the attachment stream
            # has been read
            # QQQ DELETE doesn't have any attachments, does it? nor does GET.
            # QQQ Reading attachment when there isn't one won't hurt, will it?
            # QQQ So why don't we just do it all the time for all requests?
            data = []
            d = stream.readStream(request.stream, data.append)
            d.addCallback(_finished_reading, data)
            return d
        else:
            d = self.authenticate(request)
            d.addCallback(_renderResource)

        return d
Ejemplo n.º 2
0
 def renderHTTP(self, request):
     application = getApplicationForURI(request.xcap_uri)
     if not application:
         return http.Response(responsecode.NOT_FOUND,
                              stream="Application not supported")
     resource = self.resourceForURI(request.xcap_uri)
     return resource.renderHTTP(request)
Ejemplo n.º 3
0
    def render(self, request):
        title = "Directory listing for %s" % urllib.unquote(request.path)

        s = """<html><head><title>%s</title><style>
          th, .even td, .odd td { padding-right: 0.5em; font-family: monospace}
          .even-dir { background-color: #efe0ef }
          .even { background-color: #eee }
          .odd-dir {background-color: #f0d0ef }
          .odd { background-color: #dedede }
          .icon { text-align: center }
          .listing {
              margin-left: auto;
              margin-right: auto;
              width: 50%%;
              padding: 0.1em;
              }

          body { border: 0; padding: 0; margin: 0; background-color: #efefef;}
          h1 {padding: 0.1em; background-color: #777; color: white; border-bottom: thin white dashed;}
</style></head><body><div class="directory-listing"><h1>%s</h1>""" % (title,
                                                                      title)
        s += "<table>"
        s += "<tr><th>Filename</th><th>Size</th><th>Last Modified</th><th>File Type</th></tr>"
        even = False
        for row in self.data_listing(request, None):
            s += '<tr class="%s">' % (even and 'even' or 'odd', )
            s += '<td><a href="%(link)s">%(linktext)s</a></td><td align="right">%(size)s</td><td>%(lastmod)s</td><td>%(type)s</td></tr>' % row
            even = not even

        s += "</table></div></body></html>"
        response = http.Response(200, {}, s)
        response.headers.setHeader("content-type",
                                   http_headers.MimeType('text', 'html'))
        return response
Ejemplo n.º 4
0
def makeUnsatisfiable(request, oldresponse):
    if request.headers.hasHeader('if-range'):
        return oldresponse  # Return resource instead of error
    response = http.Response(responsecode.REQUESTED_RANGE_NOT_SATISFIABLE)
    response.headers.setHeader(
        "content-range", ('bytes', None, None, oldresponse.stream.length))
    return response
Ejemplo n.º 5
0
    def renderHTTP(self, request):
        """
        See L{iweb.IResource.renderHTTP}.

        This implementation will dispatch the given C{request} to another method
        of C{self} named C{http_}METHOD, where METHOD is the HTTP method used by
        C{request} (eg. C{http_GET}, C{http_POST}, etc.).

        Generally, a subclass should implement those methods instead of
        overriding this one.

        C{http_*} methods are expected provide the same interface and return the
        same results as L{iweb.IResource}C{.renderHTTP} (and therefore this method).

        C{etag} and C{last-modified} are added to the response returned by the
        C{http_*} header, if known.

        If an appropriate C{http_*} method is not found, a
        L{responsecode.NOT_ALLOWED}-status response is returned, with an
        appropriate C{allow} header.

        @param request: the request to process.
        @return: an object adaptable to L{iweb.IResponse}.
        """
        method = getattr(self, "http_" + request.method, None)
        if not method:
            response = http.Response(responsecode.NOT_ALLOWED)
            response.headers.setHeader("allow", self.allowedMethods())
            return response

        d = self.checkPreconditions(request)
        if d is None:
            return method(request)
        else:
            return d.addCallback(lambda _: method(request))
Ejemplo n.º 6
0
 def __init__(self, request):
     from xcap.web import http
     components.Componentized.__init__(self)
     self.request = request
     self.response = http.Response(stream=stream.ProducerStream())
     # This deferred will be fired by the first call to write on OldRequestAdapter
     # and will cause the headers to be output.
     self.deferredResponse = defer.Deferred()
Ejemplo n.º 7
0
 def http_OPTIONS(self, request):
     """
     Respond to a OPTIONS request.
     @param request: the request to process.
     @return: an object adaptable to L{iweb.IResponse}.
     """
     response = http.Response(responsecode.OK)
     response.headers.setHeader("allow", self.allowedMethods())
     return response
Ejemplo n.º 8
0
    def renderHTTP_exception(self, req, reason):
        log.msg("Exception rendering:", isErr=1)
        log.err(reason)

        body = (
            "<html><head><title>Internal Server Error</title></head>"
            "<body><h1>Internal Server Error</h1>An error occurred rendering the requested page. More information is available in the server log.</body></html>"
        )

        return http.Response(
            responsecode.INTERNAL_SERVER_ERROR,
            {'content-type': http_headers.MimeType('text', 'html')}, body)
Ejemplo n.º 9
0
    def preprocessRequest(self):
        """Do any request processing that doesn't follow the normal
        resource lookup procedure. "OPTIONS *" is handled here, for
        example. This would also be the place to do any CONNECT
        processing."""

        if self.method == "OPTIONS" and self.uri == "*":
            response = http.Response(responsecode.OK)
            response.headers.setHeader('allow',
                                       ('GET', 'HEAD', 'OPTIONS', 'TRACE'))
            return response
        # This is where CONNECT would go if we wanted it
        return None
Ejemplo n.º 10
0
    def _processingReallyFailed(self, reason, origReason):
        log.msg("Exception rendering error page:", isErr=1)
        log.err(reason)
        log.msg("Original exception:", isErr=1)
        log.err(origReason)

        body = (
            "<html><head><title>Internal Server Error</title></head>"
            "<body><h1>Internal Server Error</h1>An error occurred rendering the requested page. Additionally, an error occured rendering the error page.</body></html>"
        )

        response = http.Response(
            responsecode.INTERNAL_SERVER_ERROR,
            {'content-type': http_headers.MimeType('text', 'html')}, body)
        self.writeResponse(response)
Ejemplo n.º 11
0
def doTrace(request):
    request = iweb.IRequest(request)
    txt = "%s %s HTTP/%d.%d\r\n" % (request.method, request.uri,
                                    request.clientproto[0],
                                    request.clientproto[1])

    l = []
    for name, valuelist in request.headers.getAllRawHeaders():
        for value in valuelist:
            l.append("%s: %s\r\n" % (name, value))
    txt += ''.join(l)

    return http.Response(
        responsecode.OK,
        {'content-type': http_headers.MimeType('message', 'http')}, txt)
Ejemplo n.º 12
0
class File(StaticRenderMixin):
    """
    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 .
    """
    implements(iweb.IResource)

    def _getContentTypes(self):
        if not hasattr(File, "_sharedContentTypes"):
            File._sharedContentTypes = loadMimeTypes()
        return File._sharedContentTypes

    contentTypes = property(_getContentTypes)

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

    processors = {}

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

    type = None

    def __init__(self,
                 path,
                 defaultType="text/plain",
                 ignoredExts=(),
                 processors=None,
                 indexNames=None):
        """Create a file with the given path.
        """
        super(File, self).__init__()

        self.putChildren = {}
        self.fp = filepath.FilePath(path)
        # Remove the dots from the path to split
        self.defaultType = defaultType
        self.ignoredExts = list(ignoredExts)
        if processors is not None:
            self.processors = dict([(key.lower(), value)
                                    for key, value in processors.items()])

        if indexNames is not None:
            self.indexNames = indexNames

    def exists(self):
        return self.fp.exists()

    def etag(self):
        if not self.fp.exists(): return None

        st = self.fp.statinfo

        #
        # Mark ETag as weak if it was modified more recently than we can
        # measure and report, as it could be modified again in that span
        # and we then wouldn't know to provide a new ETag.
        #
        weak = (time.time() - st.st_mtime <= 1)

        return http_headers.ETag("%X-%X-%X" %
                                 (st.st_ino, st.st_size, st.st_mtime),
                                 weak=weak)

    def lastModified(self):
        if self.fp.exists():
            return self.fp.getmtime()
        else:
            return None

    def creationDate(self):
        if self.fp.exists():
            return self.fp.getmtime()
        else:
            return None

    def contentLength(self):
        if self.fp.exists():
            if self.fp.isfile():
                return self.fp.getsize()
            else:
                # Computing this would require rendering the resource; let's
                # punt instead.
                return None
        else:
            return None

    def _initTypeAndEncoding(self):
        self._type, self._encoding = getTypeAndEncoding(
            self.fp.basename(), self.contentTypes, self.contentEncodings,
            self.defaultType)

        # Handle cases not covered by getTypeAndEncoding()
        if self.fp.isdir(): self._type = "httpd/unix-directory"

    def contentType(self):
        if not hasattr(self, "_type"):
            self._initTypeAndEncoding()
        return http_headers.MimeType.fromString(self._type)

    def contentEncoding(self):
        if not hasattr(self, "_encoding"):
            self._initTypeAndEncoding()
        return self._encoding

    def displayName(self):
        if self.fp.exists():
            return self.fp.basename()
        else:
            return None

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

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

    def directoryListing(self):
        return dirlist.DirectoryLister(self.fp.path, self.listChildren(),
                                       self.contentTypes,
                                       self.contentEncodings, self.defaultType)

    def putChild(self, name, child):
        """
        Register a child with the given name with this resource.
        @param name: the name of the child (a URI path segment)
        @param child: the child to register
        """
        self.putChildren[name] = child

    def getChild(self, name):
        """
        Look up a child resource.
        @return: the child of this resource with the given name.
        """
        if name == "":
            return self

        child = self.putChildren.get(name, None)
        if child: return child

        child_fp = self.fp.child(name)
        if child_fp.exists():
            return self.createSimilarFile(child_fp.path)
        else:
            return None

    def listChildren(self):
        """
        @return: a sequence of the names of all known children of this resource.
        """
        children = self.putChildren.keys()
        if self.fp.isdir():
            children += [c for c in self.fp.listdir() if c not in children]
        return children

    def locateChild(self, req, segments):
        """
        See L{IResource}C{.locateChild}.
        """
        # If getChild() finds a child resource, return it
        child = self.getChild(segments[0])
        if child is not None: return (child, segments[1:])

        # If we're not backed by a directory, we have no children.
        # But check for existance first; we might be a collection resource
        # that the request wants created.
        self.fp.restat(False)
        if self.fp.exists() and not self.fp.isdir(): return (None, ())

        # OK, we need to return a child corresponding to the first segment
        path = segments[0]

        if path:
            fpath = self.fp.child(path)
        else:
            # Request is for a directory (collection) resource
            return (self, server.StopTraversal)

        # Don't run processors on directories - if someone wants their own
        # customized directory rendering, subclass File instead.
        if fpath.isfile():
            processor = self.processors.get(fpath.splitext()[1].lower())
            if processor:
                return (processor(fpath.path), segments[1:])

        elif not fpath.exists():
            sibling_fpath = fpath.siblingExtensionSearch(*self.ignoredExts)
            if sibling_fpath is not None:
                fpath = sibling_fpath

        return self.createSimilarFile(fpath.path), segments[1:]

    def renderHTTP(self, req):
        self.fp.restat(False)
        return super(File, self).renderHTTP(req)

    def render(self, req):
        """You know what you doing."""
        if not self.fp.exists():
            return responsecode.NOT_FOUND

        if self.fp.isdir():
            if req.uri[-1] != "/":
                # Redirect to include trailing '/' in URI
                return http.RedirectResponse(
                    req.unparseURL(path=req.path + '/'))
            else:
                ifp = self.fp.childSearchPreauth(*self.indexNames)
                if ifp:
                    # Render from the index file
                    standin = self.createSimilarFile(ifp.path)
                else:
                    # Render from a DirectoryLister
                    standin = dirlist.DirectoryLister(self.fp.path,
                                                      self.listChildren(),
                                                      self.contentTypes,
                                                      self.contentEncodings,
                                                      self.defaultType)
                return standin.render(req)

        try:
            f = self.fp.open()
        except IOError, e:
            import errno
            if e[0] == errno.EACCES:
                return responsecode.FORBIDDEN
            elif e[0] == errno.ENOENT:
                return responsecode.NOT_FOUND
            else:
                raise

        response = http.Response()
        response.stream = stream.FileStream(f, 0, self.fp.getsize())

        for (header, value) in (
            ("content-type", self.contentType()),
            ("content-encoding", self.contentEncoding()),
        ):
            if value is not None:
                response.headers.setHeader(header, value)

        return response
Ejemplo n.º 13
0
 def render(self, req):
     return http.Response(responsecode.OK,
                          http_headers.Headers(
                              {'content-type': self.contentType()}),
                          stream=self.data)
Ejemplo n.º 14
0
                if fieldName in self.expectedFields:
                    for finfo in req.files[fieldName]:
                        try:
                            outname = self.writeFile(*finfo)
                            content.append("Saved file %s<br />" % outname)
                        except IOError, err:
                            content.append(str(err) + "<br />")
                else:
                    content.append("%s is not a valid field" % fieldName)

        else:
            content.append("No files given")

        content.append("</body></html>")

        return http.Response(responsecode.OK, {}, stream='\n'.join(content))


# FIXME: hi there I am a broken class
# """I contain AsIsProcessor, which serves files 'As Is'
#    Inspired by Apache's mod_asis
# """
#
# class ASISProcessor:
#     implements(iweb.IResource)
#
#     def __init__(self, path):
#         self.path = path
#
#     def renderHTTP(self, request):
#         request.startedWriting = 1
Ejemplo n.º 15
0
def rangefilter(request, oldresponse):
    if oldresponse.stream is None:
        return oldresponse
    size = oldresponse.stream.length
    if size is None:
        # Does not deal with indeterminate length outputs
        return oldresponse

    oldresponse.headers.setHeader('accept-ranges', ('bytes', ))

    rangespec = request.headers.getHeader('range')

    # If we've got a range header and the If-Range header check passes, and
    # the range type is bytes, do a partial response.
    if (rangespec is not None and http.checkIfRange(request, oldresponse)
            and rangespec[0] == 'bytes'):
        # If it's a single range, return a simple response
        if len(rangespec[1]) == 1:
            try:
                start, end = canonicalizeRange(rangespec[1][0], size)
            except UnsatisfiableRangeRequest:
                return makeUnsatisfiable(request, oldresponse)

            response = http.Response(responsecode.PARTIAL_CONTENT,
                                     oldresponse.headers)
            response.headers.setHeader('content-range',
                                       ('bytes', start, end, size))

            content, after = makeSegment(oldresponse.stream, 0, start, end)
            after.close()
            response.stream = content
            return response
        else:
            # Return a multipart/byteranges response
            lastOffset = -1
            offsetList = []
            for arange in rangespec[1]:
                try:
                    start, end = canonicalizeRange(arange, size)
                except UnsatisfiableRangeRequest:
                    continue
                if start <= lastOffset:
                    # Stupid client asking for out-of-order or overlapping ranges, PUNT!
                    return oldresponse
                offsetList.append((start, end))
                lastOffset = end

            if not offsetList:
                return makeUnsatisfiable(request, oldresponse)

            content_type = oldresponse.headers.getRawHeaders('content-type')
            boundary = "%x%x" % (int(time.time() * 1000000), os.getpid())
            response = http.Response(responsecode.PARTIAL_CONTENT,
                                     oldresponse.headers)

            response.headers.setHeader(
                'content-type',
                http_headers.MimeType('multipart', 'byteranges',
                                      [('boundary', boundary)]))
            response.stream = out = stream.CompoundStream()

            lastOffset = 0
            origStream = oldresponse.stream

            headerString = "\r\n--%s" % boundary
            if len(content_type) == 1:
                headerString += '\r\nContent-Type: %s' % content_type[0]
            headerString += "\r\nContent-Range: %s\r\n\r\n"

            for start, end in offsetList:
                out.addStream(headerString % http_headers.generateContentRange(
                    ('bytes', start, end, size)))

                content, origStream = makeSegment(origStream, lastOffset,
                                                  start, end)
                lastOffset = end + 1
                out.addStream(content)
            origStream.close()
            out.addStream("\r\n--%s--\r\n" % boundary)
            return response
    else:
        return oldresponse
Ejemplo n.º 16
0
 def sendResponse(self, response):
     if response.etag:
         self.e_tag = ETag(response.etag)
     response = http.Response(response.code, stream=response.data)
     return self.setHeaders(response)