def respond_404(request): respond_with_json( request, 404, cs_error("Not found %r" % (request.postpath,), code=Codes.NOT_FOUND), send_cors=True, )
def respond_404(request): respond_with_json( request, 404, cs_error("Not found %r" % (request.postpath, ), code=Codes.NOT_FOUND), send_cors=True, )
def render_GET(self, request): # no auth here on purpose, to allow anyone to view, even across home # servers. # TODO: A little crude here, we could do this better. filename = request.path.split('/')[-1] # be paranoid filename = re.sub("[^0-9A-z.-_]", "", filename) file_path = self.directory + "/" + filename logger.debug("Searching for %s", file_path) if os.path.isfile(file_path): # filename has the content type base64_contentype = filename.split(".")[1] content_type = base64.urlsafe_b64decode(base64_contentype) logger.info("Sending file %s", file_path) f = open(file_path, 'rb') request.setHeader('Content-Type', content_type) d = FileSender().beginFileTransfer(f, request) # after the file has been sent, clean up and finish the request def cbFinished(ignored): f.close() request.finish() d.addCallback(cbFinished) else: respond_with_json_bytes( request, 404, json.dumps(cs_error("Not found", code=Codes.NOT_FOUND)), send_cors=True) return server.NOT_DONE_YET
def trigger(self, http_method, path, content, mock_request): """ Fire an HTTP event. Args: http_method : The HTTP method path : The HTTP path content : The HTTP body mock_request : Mocked request to pass to the event so it can get content. Returns: A tuple of (code, response) Raises: KeyError If no event is found which will handle the path. """ path = self.prefix + path # annoyingly we return a twisted http request which has chained calls # to get at the http content, hence mock it here. mock_content = Mock() config = {'read.return_value': content} mock_content.configure_mock(**config) mock_request.content = mock_content mock_request.method = http_method mock_request.uri = path mock_request.requestHeaders.getRawHeaders.return_value = [ "X-Matrix origin=test,key=,sig=" ] # return the right path if the event requires it mock_request.path = path # add in query params to the right place try: mock_request.args = urlparse.parse_qs(path.split('?')[1]) mock_request.path = path.split('?')[0] path = mock_request.path except: pass for (method, pattern, func) in self.callbacks: if http_method != method: continue matcher = pattern.match(path) if matcher: try: args = [ urllib.unquote(u).decode("UTF-8") for u in matcher.groups() ] (code, response) = yield func(mock_request, *args) defer.returnValue((code, response)) except CodeMessageException as e: defer.returnValue((e.code, cs_error(e.msg))) raise KeyError("No event can handle %s" % path)
def trigger(self, http_method, path, content, mock_request): """ Fire an HTTP event. Args: http_method : The HTTP method path : The HTTP path content : The HTTP body mock_request : Mocked request to pass to the event so it can get content. Returns: A tuple of (code, response) Raises: KeyError If no event is found which will handle the path. """ path = self.prefix + path # annoyingly we return a twisted http request which has chained calls # to get at the http content, hence mock it here. mock_content = Mock() config = {'read.return_value': content} mock_content.configure_mock(**config) mock_request.content = mock_content mock_request.method = http_method mock_request.uri = path mock_request.requestHeaders.getRawHeaders.return_value=[ "X-Matrix origin=test,key=,sig=" ] # return the right path if the event requires it mock_request.path = path # add in query params to the right place try: mock_request.args = urlparse.parse_qs(path.split('?')[1]) mock_request.path = path.split('?')[0] path = mock_request.path except: pass for (method, pattern, func) in self.callbacks: if http_method != method: continue matcher = pattern.match(path) if matcher: try: (code, response) = yield func( mock_request, *matcher.groups() ) defer.returnValue((code, response)) except CodeMessageException as e: defer.returnValue((e.code, cs_error(e.msg))) raise KeyError("No event can handle %s" % path)
def render_GET(self, request): # no auth here on purpose, to allow anyone to view, even across home # servers. # TODO: A little crude here, we could do this better. filename = request.path.split('/')[-1] # be paranoid filename = re.sub("[^0-9A-z.-_]", "", filename) file_path = self.directory + "/" + filename logger.debug("Searching for %s", file_path) if os.path.isfile(file_path): # filename has the content type base64_contentype = filename.split(".")[1] content_type = base64.urlsafe_b64decode(base64_contentype) logger.info("Sending file %s", file_path) f = open(file_path, 'rb') request.setHeader('Content-Type', content_type) # cache for at least a day. # XXX: we might want to turn this off for data we don't want to # recommend caching as it's sensitive or private - or at least # select private. don't bother setting Expires as all our matrix # clients are smart enough to be happy with Cache-Control (right?) request.setHeader("Cache-Control", "public,max-age=86400,s-maxage=86400") d = FileSender().beginFileTransfer(f, request) # after the file has been sent, clean up and finish the request def cbFinished(ignored): f.close() request.finish() d.addCallback(cbFinished) else: respond_with_json_bytes(request, 404, json.dumps( cs_error("Not found", code=Codes.NOT_FOUND)), send_cors=True) return server.NOT_DONE_YET
def render_GET(self, request): # no auth here on purpose, to allow anyone to view, even across home # servers. # TODO: A little crude here, we could do this better. filename = request.path.split('/')[-1] # be paranoid filename = re.sub("[^0-9A-z.-_]", "", filename) file_path = self.directory + "/" + filename logger.debug("Searching for %s", file_path) if os.path.isfile(file_path): # filename has the content type base64_contentype = filename.split(".")[1] content_type = base64.urlsafe_b64decode(base64_contentype) logger.info("Sending file %s", file_path) f = open(file_path, 'rb') request.setHeader('Content-Type', content_type) # cache for at least a day. # XXX: we might want to turn this off for data we don't want to # recommend caching as it's sensitive or private - or at least # select private. don't bother setting Expires as all our matrix # clients are smart enough to be happy with Cache-Control (right?) request.setHeader( "Cache-Control", "public,max-age=86400,s-maxage=86400" ) d = FileSender().beginFileTransfer(f, request) # after the file has been sent, clean up and finish the request def cbFinished(ignored): f.close() finish_request(request) d.addCallback(cbFinished) else: respond_with_json_bytes( request, 404, json.dumps(cs_error("Not found", code=Codes.NOT_FOUND)), send_cors=True) return server.NOT_DONE_YET
def render_GET(self, request): # no auth here on purpose, to allow anyone to view, even across home # servers. # TODO: A little crude here, we could do this better. filename = request.path.split('/')[-1] # be paranoid filename = re.sub("[^0-9A-z.-_]", "", filename) file_path = self.directory + "/" + filename logger.debug("Searching for %s", file_path) if os.path.isfile(file_path): # filename has the content type base64_contentype = filename.split(".")[1] content_type = base64.urlsafe_b64decode(base64_contentype) logger.info("Sending file %s", file_path) f = open(file_path, 'rb') request.setHeader('Content-Type', content_type) d = FileSender().beginFileTransfer(f, request) # after the file has been sent, clean up and finish the request def cbFinished(ignored): f.close() request.finish() d.addCallback(cbFinished) else: respond_with_json_bytes(request, 404, json.dumps( cs_error("Not found", code=Codes.NOT_FOUND)), send_cors=True) return server.NOT_DONE_YET
def trigger(self, http_method, path, content, mock_request, federation_auth_origin=None): """ Fire an HTTP event. Args: http_method : The HTTP method path : The HTTP path content : The HTTP body mock_request : Mocked request to pass to the event so it can get content. federation_auth_origin (bytes|None): domain to authenticate as, for federation Returns: A tuple of (code, response) Raises: KeyError If no event is found which will handle the path. """ path = self.prefix + path # annoyingly we return a twisted http request which has chained calls # to get at the http content, hence mock it here. mock_content = Mock() config = {'read.return_value': content} mock_content.configure_mock(**config) mock_request.content = mock_content mock_request.method = http_method.encode('ascii') mock_request.uri = path.encode('ascii') mock_request.getClientIP.return_value = "-" headers = {} if federation_auth_origin is not None: headers[b"Authorization"] = [ b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin, ) ] mock_request.requestHeaders.getRawHeaders = mock_getRawHeaders(headers) # return the right path if the event requires it mock_request.path = path # add in query params to the right place try: mock_request.args = urlparse.parse_qs(path.split('?')[1]) mock_request.path = path.split('?')[0] path = mock_request.path except Exception: pass if isinstance(path, bytes): path = path.decode('utf8') for (method, pattern, func) in self.callbacks: if http_method != method: continue matcher = pattern.match(path) if matcher: try: args = [urlparse.unquote(u) for u in matcher.groups()] (code, response) = yield func(mock_request, *args) defer.returnValue((code, response)) except CodeMessageException as e: defer.returnValue((e.code, cs_error(e.msg, code=e.errcode))) raise KeyError("No event can handle %s" % path)
def trigger( self, http_method, path, content, mock_request, federation_auth_origin=None ): """ Fire an HTTP event. Args: http_method : The HTTP method path : The HTTP path content : The HTTP body mock_request : Mocked request to pass to the event so it can get content. federation_auth_origin (bytes|None): domain to authenticate as, for federation Returns: A tuple of (code, response) Raises: KeyError If no event is found which will handle the path. """ path = self.prefix + path # annoyingly we return a twisted http request which has chained calls # to get at the http content, hence mock it here. mock_content = Mock() config = {'read.return_value': content} mock_content.configure_mock(**config) mock_request.content = mock_content mock_request.method = http_method.encode('ascii') mock_request.uri = path.encode('ascii') mock_request.getClientIP.return_value = "-" headers = {} if federation_auth_origin is not None: headers[b"Authorization"] = [ b"X-Matrix origin=%s,key=,sig=" % (federation_auth_origin,) ] mock_request.requestHeaders.getRawHeaders = mock_getRawHeaders(headers) # return the right path if the event requires it mock_request.path = path # add in query params to the right place try: mock_request.args = urlparse.parse_qs(path.split('?')[1]) mock_request.path = path.split('?')[0] path = mock_request.path except Exception: pass if isinstance(path, bytes): path = path.decode('utf8') for (method, pattern, func) in self.callbacks: if http_method != method: continue matcher = pattern.match(path) if matcher: try: args = [urlparse.unquote(u) for u in matcher.groups()] (code, response) = yield func(mock_request, *args) defer.returnValue((code, response)) except CodeMessageException as e: defer.returnValue((e.code, cs_error(e.msg, code=e.errcode))) raise KeyError("No event can handle %s" % path)