Exemplo n.º 1
0
    def render(self, request):
        """
        @param request: `twisted.web.Request`

        @return: empty `str` or `NOT_DONE_YET`
        """
        request_finished = [False]

        def _finish(ret):
            request_finished[0] = True

        request.notifyFinish().addBoth(_finish)

        self.preprocess(request)

        self.set_headers(request)

        if request.tid is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        if self.should_redirect_tor(request):
            self.redirect_tor(request)
            return b''

        if self.should_redirect_https(request):
            self.redirect_https(request)
            return b''

        request.path = request.path.decode('utf-8')

        if request.tid == 1:
            match = re.match(r'^/t/([0-9]+)(/.*)', request.path)
            if match is not None:
                groups = match.groups()
                request.tid, request.path = int(groups[0]), groups[1]

        match = None
        for regexp, handler, args in self._registry:
            try:
                match = regexp.match(request.path)
            except UnicodeDecodeError:
                match = None
            if match:
                break

        if match is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        method = request.method.lower().decode('utf-8')

        if method == 'head':
            # HEAD method is not really implemented
            # as trick we use the same approch of Twisted of
            # mapping the HEAD method on the GET method.
            method = 'get'

        if method not in self.method_map.keys() or not hasattr(handler, method):
            self.handle_exception(errors.MethodNotImplemented(), request)
            return b''

        f = getattr(handler, method)
        groups = [text_type(g) for g in match.groups()]

        self.handler = handler(State, request, **args)

        request.setResponseCode(self.method_map[method])

        if self.handler.root_tenant_only and request.tid != 1:
            self.handle_exception(errors.ForbiddenOperation(), request)
            return b''

        if self.handler.upload_handler and method == 'post':
            self.handler.process_file_upload()
            if self.handler.uploaded_file is None:
                return b''

        @defer.inlineCallbacks
        def concludeHandlerFailure(err):
            yield self.handler.execution_check()

            self.handle_exception(err, request)

            if not request_finished[0]:
                request.finish()

        @defer.inlineCallbacks
        def concludeHandlerSuccess(ret):
            """
            Concludes successful execution of a `BaseHandler` instance

            @param ret: A `dict`, `list`, `str`, `None` or something unexpected
            """
            yield self.handler.execution_check()

            if not request_finished[0]:
                if ret is not None:
                    if isinstance(ret, (dict, list)):
                        ret = json.dumps(ret, separators=(',', ':'))
                        request.setHeader(b'content-type', b'application/json')

                    if isinstance(ret, text_type):
                        ret = ret.encode()

                    request.write(ret)

                request.finish()

        defer.maybeDeferred(f, self.handler, *groups).addCallbacks(concludeHandlerSuccess, concludeHandlerFailure)

        return NOT_DONE_YET
Exemplo n.º 2
0
    def render(self, request):
        """
        :param request: `twisted.web.Request`

        :return: empty `str` or `NOT_DONE_YET`
        """
        request_finished = [False]

        def _finish(ret):
            request_finished[0] = True

        request.notifyFinish().addBoth(_finish)

        self.preprocess(request)

        if request.tid is None:
            # Tentative domain correction in relation to presence / absence of 'www.' prefix
            if not request.hostname.startswith(b'www.'):
                tentative_hostname = b'www.' + request.hostname
            else:
                tentative_hostname = request.hostname[4:]

            if tentative_hostname in State.tenant_hostname_id_map:
                request.tid = State.tenant_hostname_id_map[tentative_hostname]
                if State.tenant_cache[request.tid].https_enabled:
                    request.redirect(b'https://' + tentative_hostname + b'/')
                else:
                    request.redirect(b'http://' + tentative_hostname + b'/')
            else:
                # Fallback on root tenant with error 400
                request.tid = 1
                request.setResponseCode(400)

            self.set_headers(request)
            return b''

        self.set_headers(request)

        if self.should_redirect_tor(request):
            self.redirect_tor(request)
            return b''

        if self.should_redirect_https(request):
            self.redirect_https(request)
            return b''

        request_path = request.path.decode()

        if request_path in State.tenant_cache[request.tid]['redirects']:
            request.redirect(
                State.tenant_cache[request.tid]['redirects'][request_path])
            return b''

        match = None
        for regexp, handler, args in self._registry:
            try:
                match = regexp.match(request_path)
            except UnicodeDecodeError:
                match = None
            if match:
                break

        if match is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        method = request.method.lower().decode()

        if method == 'head':
            method = 'get'
        elif method == 'options':
            request.setResponseCode(200)
            return b''

        if method not in self.method_map.keys() or not hasattr(
                handler, method):
            self.handle_exception(errors.MethodNotImplemented(), request)
            return b''

        f = getattr(handler, method)
        groups = match.groups()

        self.handler = handler(State, request, **args)

        request.setResponseCode(self.method_map[method])

        if self.handler.root_tenant_only and request.tid != 1:
            self.handle_exception(errors.ForbiddenOperation(), request)
            return b''

        if self.handler.upload_handler and method == 'post':
            self.handler.process_file_upload()
            if self.handler.uploaded_file is None:
                return b''

        @defer.inlineCallbacks
        def concludeHandlerFailure(err):
            self.handle_exception(err, request)

            yield self.handler.execution_check()

            if not request_finished[0]:
                request.finish()

        @defer.inlineCallbacks
        def concludeHandlerSuccess(ret):
            """
            Concludes successful execution of a `BaseHandler` instance

            :param ret: A `dict`, `list`, `str`, `None` or something unexpected
            """
            yield self.handler.execution_check()

            if not request_finished[0]:
                if ret is not None:
                    if isinstance(ret, (dict, list)):
                        ret = json.dumps(ret,
                                         cls=JSONEncoder,
                                         separators=(',', ':'))
                        request.setHeader(b'content-type', b'application/json')

                    if isinstance(ret, str):
                        ret = ret.encode()

                    request.write(ret)

                request.finish()

        defer.maybeDeferred(f, self.handler,
                            *groups).addCallbacks(concludeHandlerSuccess,
                                                  concludeHandlerFailure)

        return NOT_DONE_YET
Exemplo n.º 3
0
 def delete_file(store):
     raise errors.MethodNotImplemented()
Exemplo n.º 4
0
 def db_serialize(store):
     """
     :rtype: A `dict` to be converted into JSON for delivery to a client
     """
     raise errors.MethodNotImplemented()
Exemplo n.º 5
0
 def perform_file_action():
     raise errors.MethodNotImplemented()
Exemplo n.º 6
0
 def get_file(store):
     """
     :rtype: A `unicode` string
     """
     raise errors.MethodNotImplemented()
Exemplo n.º 7
0
 def create_file(store, content):
     raise errors.MethodNotImplemented()
Exemplo n.º 8
0
    def get_file_res_or_raise(self, name):
        if name not in self.mapped_file_resources:
            raise errors.MethodNotImplemented()

        return self.mapped_file_resources[name]
Exemplo n.º 9
0
    def render(self, request):
        """
        @param request: `twisted.web.Request`

        @return: empty `str` or `NOT_DONE_YET`
        """
        request_finished = [False]

        def _finish(ret):
            request_finished[0] = True

        request.notifyFinish().addBoth(_finish)

        self.preprocess(request)

        if self.should_redirect_tor(request):
            self.redirect_tor(request)
            return b''

        if self.should_redirect_https(request):
            self.redirect_https(request)
            return b''

        match = None
        for regexp, handler, args in self._registry:
            match = regexp.match(request.path)
            if match:
                break

        if match is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        method = request.method.lower()
        if not method in self.method_map or not hasattr(handler, method):
            self.handle_exception(errors.MethodNotImplemented(), request)
            return b''
        else:
            request.setResponseCode(self.method_map[method])

        f = getattr(handler, method)

        groups = [unicode(g) for g in match.groups()]
        h = handler(State, request, **args)

        d = defer.maybeDeferred(f, h, *groups)

        @defer.inlineCallbacks
        def concludeHandlerFailure(err):
            yield h.execution_check()

            self.handle_exception(err, request)

            if not request_finished[0]:
                request.finish()

        @defer.inlineCallbacks
        def concludeHandlerSuccess(ret):
            """
            Concludes successful execution of a `BaseHandler` instance

            @param ret: A `dict`, `list`, `str`, `None` or something unexpected
            """
            yield h.execution_check()

            if not request_finished[0]:
                if ret is not None:
                    if isinstance(ret, (types.DictType, types.ListType)):
                        ret = json.dumps(ret, separators=(',', ':'))
                        request.setHeader(b'content-type', b'application/json')

                    request.write(bytes(ret))

                request.finish()

        d.addErrback(concludeHandlerFailure)
        d.addCallback(concludeHandlerSuccess)

        return NOT_DONE_YET
Exemplo n.º 10
0
 def delete_file(session, tid):
     raise errors.MethodNotImplemented()
Exemplo n.º 11
0
 def create_file(session, cls, tid, content):
     raise errors.MethodNotImplemented()
Exemplo n.º 12
0
 def db_serialize(session, tid):
     raise errors.MethodNotImplemented()
Exemplo n.º 13
0
    def render(self, request):
        """
        @param request: `twisted.web.Request`

        @return: empty `str` or `NOT_DONE_YET`
        """

        self.set_default_headers(request)

        request_finished = [False]

        def _finish(_):
            request_finished[0] = True

        request.notifyFinish().addBoth(_finish)

        match = None
        for regexp, handler, args in self._registry:
            match = regexp.match(request.path)
            if match:
                break

        if match is None:
            self.handle_exception(errors.ResourceNotFound(), request)
            return b''

        method = request.method.lower()
        if not method in ['get', 'post', 'put', 'delete'] or not hasattr(
                handler, method):
            self.handle_exception(errors.MethodNotImplemented(), request)
            return b''

        f = getattr(handler, method)

        groups = [unicode(g) for g in match.groups()]
        h = handler(request, **args)
        d = defer.maybeDeferred(f, h, *groups)

        @defer.inlineCallbacks
        def concludeHandlerFailure(err):
            yield h.execution_check()

            self.handle_exception(err, request)

            if not request_finished[0]:
                request.finish()

        @defer.inlineCallbacks
        def concludeHandlerSuccess(ret):
            """Concludes successful execution of a `BaseHandler` instance

            @param ret: A `dict`, `str`, `None` or something unexpected
            """
            yield h.execution_check()

            if not ret is None:
                h.write(ret)

            if not request_finished[0]:
                request.finish()

        d.addErrback(concludeHandlerFailure)
        d.addCallback(concludeHandlerSuccess)
        return NOT_DONE_YET