def getChild(self, name, request): """ Returns send/receive/close resource for transport. .. seealso:: * :class:`twisted.web.resource.Resource` * :class:`zipfile.ZipFile` """ name = name.decode('utf8') if name not in self._transports: if not name: return self else: self.log.error("No WAMP transport '{name}'", name=name) return NoResource("no WAMP transport '{0}'".format(name)) if len(request.postpath) == 0 or (len(request.postpath) == 1 and request.postpath[0] in [b'send', b'receive', b'close']): return self._transports[name] else: return NoResource("invalid WAMP transport operation '{0}'".format( request.postpath))
def __init__(self, pathname, filter, childNotFound=None): Resource.__init__(self) FilePath.__init__(self, pathname) self.filter = filter if childNotFound: self.childNotFound = childNotFound else: self.childNotFound = NoResource("CGI directories do not support directory listing.")
def return_404(self, request): """Return a 404 HTTP response. :param request: The request to which we are responding. :returns: NoResource's rendering of the request. Performed if a request tries to access a nonexistent table. """ page = NoResource(message="Table %s could not be found" % self.table_name) return page.render(request)
def render_POST(self, request): request.responseHeaders.addRawHeader(b"content-type", b"application/json") response = {} try: token = request.args.get('token', None)[0] auth = request.args.get('auth', None)[0] setting = request.args.get('setting', None)[0] canarydrop = Canarydrop(**get_canarydrop(canarytoken=token)) if not canarydrop['auth'] or canarydrop['auth'] != auth: raise NoCanarytokenPresent() if setting not in [ 'clonedsite', 'email_enable', 'webhook_enable', 'sms_enable', 'browser_scanner_enable', 'web_image_enable' ]: raise NoCanarytokenPresent() except (IndexError, TypeError, NoCanarytokenPresent): return NoResource().render(request) if setting == 'clonedsite': try: clonedsite = request.args['clonedsite'][0] if not clonedsite: raise KeyError cloned_token = {'clonedsite': clonedsite, 'canarytoken': token} canarydrop.clonedsite_token = save_clonedsite_token( cloned_token) save_canarydrop(canarydrop) response[ 'clonedsite_js'] = canarydrop.get_cloned_site_javascript() response['clonedsite'] = clonedsite except (IndexError, KeyError): return NoResource().render(request) elif setting == "email_enable": canarydrop['alert_email_enabled'] = request.args['value'][ 0] == "on" elif setting == "webhook_enable": canarydrop['alert_webhook_enabled'] = request.args['value'][ 0] == "on" elif setting == "sms_enable": canarydrop['alert_sms_enabled'] = request.args['value'][0] == "on" elif setting == "browser_scanner_enable": canarydrop['browser_scanner_enabled'] = request.args['value'][ 0] == "on" elif setting == "web_image_enable": canarydrop['web_image_enabled'] = request.args['value'][0] == "on" save_canarydrop(canarydrop=canarydrop) response['result'] = 'success' return simplejson.dumps(response)
def getChild(self, name, request): try: stream = self.streams[name] if stream.finished: self.streams.pop(name, None) return NoResource() else: return Channel(name, stream) except KeyError: return NoResource() '''No longer appropriate with listen method
def getChild(self, id, request): if self.id: return NoResource() try: id = int(id) except ValueError: return NoResource() if id < 1 or id > (len(pastes[self.host])): return NoResource() return Paste(self.host, id)
def render_POST(self, request): if request.path != self._path: page = NoResource( message="API path %s is not supported" % request.URLPath()) return page.render(request) if request.getHeader(b"Content-Type") != b"application/json": page = NoResource( message="Unsupported Content-Type (must be \"application/json" "\")" % request.URLPath()) return page.render(request) request.setHeader(b"Content-Type", b"application/json") self._callback(request) return NOT_DONE_YET
def render(self, request: Request) -> bytes: try: action: bytes = request.postpath[0] action: Optional[str] = action.decode() except IndexError: action = None if action == 'channels': return self.channels(request).encode() else: res = NoResource(message="invalid command to server.") return res.render(request)
def delete_object(self, request, container_name, object_name): """ Delete an object in a container. """ if container_name in self.containers: container = self.containers[container_name] if object_name in container.objects: del container.objects[object_name] request.setResponseCode(204) return b"" else: return NoResource("No such object in container") else: return NoResource("No such container")
def getChild(self, child, request): cap, _, ext = child.partition('.') if len(cap) == 15 and cap in self.shortdb: cap, _, storedExt = self.shortdb[cap].partition('.') ext = ext or storedExt if not tahoeRegex.match(cap): try: cap = base64.urlsafe_b64decode(cap) except TypeError: # TypeError??? really??? return NoResource('Invalid base64') if not tahoeRegex.match(cap): return NoResource('Not a valid tahoe CAP URI') capURL = self.tahoeURL + urllib.quote(cap) return TahoeResource(self.agent, capURL, ext)
def getChild(self, name, request): log.msg( "ATDemoWebResource::getChild processing name=%s;uri=%s;clientIP=%s;" % (name, request.uri, request.getClientIP())) if name == 'test': if 'voice' in request.uri: return VoiceRequestWebPage(self.callerRegistry) elif 'ussd' in request.uri: return UssdRequestWebPage(self.callerRegistry) elif 'payment' in request.uri: return PaymentRequestWebPage() else: return NoResource() else: return NoResource()
def _listen_http(self, listener_config): port = listener_config["port"] bind_addresses = listener_config["bind_addresses"] site_tag = listener_config.get("tag", port) resources = {} for res in listener_config["resources"]: for name in res["names"]: if name == "metrics": resources[METRICS_PREFIX] = MetricsResource(self) elif name == "client": resource = JsonResource(self, canonical_json=False) sync.register_servlets(self, resource) events.register_servlets(self, resource) InitialSyncRestServlet(self).register(resource) RoomInitialSyncRestServlet(self).register(resource) resources.update({ "/_matrix/client/r0": resource, "/_matrix/client/unstable": resource, "/_matrix/client/v2_alpha": resource, "/_matrix/client/api/v1": resource, }) root_resource = create_resource_tree(resources, NoResource()) _base.listen_tcp( bind_addresses, port, SynapseSite( "synapse.access.http.%s" % (site_tag, ), site_tag, listener_config, root_resource, )) logger.info("Synapse synchrotron now listening on port %d", port)
def getChild(self, name, request): if name == 'log' and self.application.log_path is not None: return File(self.application.log_path.path, 'text/plain; charset=utf8') elif name == 'chartdata.json': return ApplicationHistogramResource(self.application) return NoResource()
def get_node(node): if node is not None: self.mserver.get_contract(node, unhexlify(request.args["id"][0]))\ .addCallback(parse_contract) else: request.write(NoResource().render(request)) request.finish()
def getChild(self, name, request): try: year = int(name) except ValueError: return NoResource() else: return YearPage(year)
def getChild(self, path, req): try: changeid = int(path) except ValueError: return NoResource("Expected a change number") return ChangeResource(changeid)
def render_GET(self, request): try: token = request.args.get('token', None)[0] auth = request.args.get('auth', None)[0] canarydrop = Canarydrop(**get_canarydrop(canarytoken=token)) if not canarydrop['auth'] or canarydrop['auth'] != auth: raise NoCanarytokenPresent() if canarydrop.get('triggered_list', None): for timestamp in canarydrop['triggered_list'].keys(): formatted_timestamp = datetime.datetime.fromtimestamp( float(timestamp)).strftime('%Y %b %d %H:%M:%S') canarydrop['triggered_list'][ formatted_timestamp] = canarydrop[ 'triggered_list'].pop(timestamp) if canarydrop.get('memo'): canarydrop['memo'] = unicode(canarydrop['memo'], "utf8") except (TypeError, NoCanarytokenPresent): return NoResource().render(request) g_api_key = get_canary_google_api_key() template = env.get_template('history.html') return template.render(canarydrop=canarydrop, API_KEY=g_api_key).encode('utf8')
def werewolves_update_requests(self, request, update): if not check_authenticated(request): return if not update in ('actions', 'phase-info', 'player-info', 'game-info', 'output', 'request-all'): return NoResource() avatar = get_avatar(request) avatar.request_update_from_app(update)
def _listen_http(self, listener_config): port = listener_config["port"] bind_addresses = listener_config["bind_addresses"] site_tag = listener_config.get("tag", port) resources = {} for res in listener_config["resources"]: for name in res["names"]: if name == "metrics": resources[METRICS_PREFIX] = MetricsResource(RegistryProxy) elif name == "media": media_repo = self.get_media_repository_resource() resources.update({ MEDIA_PREFIX: media_repo, LEGACY_MEDIA_PREFIX: media_repo, CONTENT_REPO_PREFIX: ContentRepoResource(self, self.config.uploads_path), }) root_resource = create_resource_tree(resources, NoResource()) _base.listen_tcp( bind_addresses, port, SynapseSite( "synapse.access.http.%s" % (site_tag, ), site_tag, listener_config, root_resource, self.version_string, )) logger.info("Synapse media repository now listening on port %d", port)
def _listen_http(self, listener_config): port = listener_config["port"] bind_addresses = listener_config["bind_addresses"] site_tag = listener_config.get("tag", port) resources = {} for res in listener_config["resources"]: for name in res["names"]: if name == "metrics": resources[METRICS_PREFIX] = MetricsResource(RegistryProxy) root_resource = create_resource_tree(resources, NoResource()) _base.listen_tcp( bind_addresses, port, SynapseSite( "synapse.access.http.%s" % (site_tag, ), site_tag, listener_config, root_resource, self.version_string, ), ) logger.info("Synapse federation_sender now listening on port %d", port)
def render_GET(self, request): try: token = request.args.get('token', None)[0] fmt = request.args.get('fmt', None)[0] canarydrop = Canarydrop(**get_canarydrop(canarytoken=token)) if not canarydrop: raise NoCanarytokenPresent() if fmt == 'zip': request.setHeader("Content-Type", "application/zip") request.setHeader("Content-Disposition", 'attachment; filename={token}.zip'\ .format(token=token)) return make_canary_zip(hostname= canarydrop.get_hostname(with_random=False)) elif fmt == 'msword': request.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument"+\ ".wordprocessingml.document") request.setHeader("Content-Disposition", 'attachment; filename={token}.docx'\ .format(token=token)) return make_canary_msword(url=canarydrop.get_url()) elif fmt == 'pdf': request.setHeader("Content-Type", "application/pdf") request.setHeader("Content-Disposition", 'attachment; filename={token}.pdf'\ .format(token=token)) return make_canary_pdf(hostname=canarydrop.get_hostname(nxdomain=True, with_random=False)) except Exception as e: log.err('Unexpected error in download: {err}'.format(err=e)) return NoResource().render(request)
def getChild(self, name, request): for obj in self._objects: if name == str(obj.id): return obj return NoResource(message="The resource %s was not found" % request.URLPath())
def getChild(self, name, request): """ Dispatch a specific incoming request to an appropriate resource """ # First try: static resource static = self.static.handle_static(request) if static: return static # If that doesn't serve the request, try the plugin dynamic path if request.path in self.path_map: print 'using plugin %s for %s' % (self.path_map[request.path], request.path) cfg = self.cfg.copy() cfg['tab_map'] = self.tab_map for arg in request.args: if arg not in cfg: cfg[arg] = request.args[arg][0] # Augment the request with our own session data request.sdata = session.get_data(request) return self.path_map[request.path](cfg) # Nothing else to try print 'Failed to match path', request.path, 'to any plugins', self.path_map return NoResource()
def getChild(self, name, request): if name == "": return self if name == READ_WEB_SERVICE: return SSReadWS() else: return NoResource()
def getChild(self, name, request): if name == '': return self if name.isdigit(): return YearPage(int(name)) else: return NoResource()
def getChild(self, name, request): """ This method get called when a request comes in from a browser This method then decides based on the requested URI which twisted.web.resource class to instantiate to process the GET/POST requests """ if name == '': # root URI requested "http://IP:port/" or "http://IP:port" return self if name == 'about': # about URI requested "http://IP:port/about" return AboutPage() if name == 'status': # about URI requested "http://IP:port/status" return StatusPage() if name == 'transmit': # about URI requested "http://IP:port/transmit" return TransmitPage() if name == 'config': # about URI requested "http://IP:port/config" return ConfigPage() if name.isdigit(): # about URI requested "http://IP:port/digit" return YearPage(int(name)) else: # invalid URI requested so return a error web resource with renders an HTML that displays a default 404 message return NoResource()
def _listen_http(self, listener_config): port = listener_config["port"] bind_addresses = listener_config["bind_addresses"] site_tag = listener_config.get("tag", port) resources = {} for res in listener_config["resources"]: for name in res["names"]: if name == "metrics": resources[METRICS_PREFIX] = MetricsResource(RegistryProxy) elif name == "client": resource = JsonResource(self, canonical_json=False) user_directory.register_servlets(self, resource) resources.update({ "/_matrix/client/r0": resource, "/_matrix/client/unstable": resource, "/_matrix/client/v2_alpha": resource, "/_matrix/client/api/v1": resource, }) root_resource = create_resource_tree(resources, NoResource()) _base.listen_tcp( bind_addresses, port, SynapseSite( "synapse.access.http.%s" % (site_tag, ), site_tag, listener_config, root_resource, self.version_string, ), ) logger.info("Synapse user_dir now listening on port %d", port)
class CgiDirectory(Resource, FilePath): cgiscript = CgiScript def __init__(self, pathname, filter, childNotFound=None): Resource.__init__(self) FilePath.__init__(self, pathname) self.filter = filter if childNotFound: self.childNotFound = childNotFound else: self.childNotFound = NoResource( "CGI directories do not support directory listing.") def getChild(self, path, request): fnp = self.child(path) if not fnp.exists(): return File.childNotFound elif fnp.isdir(): return CgiDirectory(fnp.path, self.filter, self.childNotFound) else: return self.cgiscript(fnp.path, self.filter) return NoResource() def render(self, request): return self.childNotFound.render(request)
def getChild(self, path, req): for log in self.step_status.getLogs(): if path == log.getName(): if log.old_hasContents(): return IHTMLLog(interfaces.IStatusLog(log)) return NoResource("Empty Log '%s'" % path) return HtmlResource.getChild(self, path, req)
def render(self, request): if self.type == self.types.REDIRECT: return "" elif self.type == self.types.QUEUE: return NOT_DONE_YET else: return NoResource.render(self, request)
class CgiDirectory(Resource, FilePath): cgiscript = CgiScript def __init__(self, pathname, filter, childNotFound=None): Resource.__init__(self) FilePath.__init__(self, pathname) self.filter = filter if childNotFound: self.childNotFound = childNotFound else: self.childNotFound = NoResource("CGI directories do not support directory listing.") def getChild(self, path, request): fnp = self.child(path) if not fnp.exists(): return File.childNotFound elif fnp.isdir(): return CgiDirectory(fnp.path, self.filter, self.childNotFound) else: return self.cgiscript(fnp.path, self.filter) return NoResource() def render(self, request): return self.childNotFound.render(request)
def getChild(self, name: bytes, request: Request) -> Resource: # sock: socket.socket = request.transport.socket if platform.system() == 'Darwin': sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) TCP_KEEPALIVE = 0x10 sock.setsockopt(socket.IPPROTO_TCP, TCP_KEEPALIVE, 1) else: sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5) # if name: name: str = name.decode() if name == '__status': return self.__status try: return self.__channels[name] except KeyError: self.__channels[name] = Channel(name) return self.__channels[name] return NoResource(message='invalid operation')
class Server(Resource): def __init__(self): Resource.__init__(self) self.isLeaf = True self.r404 = NoResource() fp = file(sys.argv[0]) self.src = fp.read() fp.close() from subprocess import PIPE, Popen try: self.src_syn = Popen(['pandoc', '-s'], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate("~~~~ {.python}\n" + self.src + "~~~~\n")[0] except OSError: sys.stderr.write("pandoc not found; /src/ will default to plain text rather than syntax highlighted code\n") self.src_syn = None def render_GET(self, request): host, path = request.client.host, request.path print_flush_log("R %s %s" % (host, path)) request.setHeader("content-type", "text/plain") if path == "/": return "%s %s\n%s\n/tcp/[port]\n/udp/[port]\n/src/\n/src/raw\n/src/get\n" % (NAME, VERSION, __doc__) try: type, port = path[1:].split('/', 2) if type == "src": if port == "raw": return self.src elif port == "get": request.setHeader("content-type", "text/x-python") request.setHeader("content-disposition", "attachment; filename=\"%s\"" % FNAME); return self.src elif self.src_syn is not None: request.setHeader("content-type", "text/html") return self.src_syn else: return self.src elif type not in PROTOCOL: raise KeyError port = int(port) except (ValueError, KeyError): return self.r404.render(request) else: start_connect(host, type, port, reactor.callLater) return "awaiting connection to %s %s %s" % (host, type, port)
def __init__(self): Resource.__init__(self) self.isLeaf = True self.r404 = NoResource() fp = file(sys.argv[0]) self.src = fp.read() fp.close() from subprocess import PIPE, Popen try: self.src_syn = Popen(['pandoc', '-s'], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate("~~~~ {.python}\n" + self.src + "~~~~\n")[0] except OSError: sys.stderr.write("pandoc not found; /src/ will default to plain text rather than syntax highlighted code\n") self.src_syn = None
def render_DELETE(self, request): # print "KeyResource.render_DELETE" if not self.isRemovable(): epage = NoResource( "deleting collection %s failed." % request.uri) return epage.render(request) if self.isdir(): depth = get_depth(request) if not depth: epage = BadRequestResource( "deleting collection %s failed." "because depth is not "infinity"" % request.uri) return epage.render(request) self.rmtree() else: self.remove() epage = NoContentResource("%s deleted" % request.uri) return epage.render(request)
def __init__(self): NoResource.__init__(self, b'Resource not found')
def getChild(self, path, request): """Find the appropriate child resource depending on request type Possible URLs: - /foo/bar/info/refs -> info refs (file / SmartHTTP hybrid) - /foo/bar/git-upload-pack -> SmartHTTP RPC - /foo/bar/git-receive-pack -> SmartHTTP RPC - /foo/bar/HEAD -> file (dumb http) - /foo/bar/objects/* -> file (dumb http) """ path = request.path # alternatively use path + request.postpath pathparts = path.split('/') writerequired = False script_name = '/' new_path = path resource = NoResource() # Path lookup / translation path_info = self.git_configuration.path_lookup(path, protocol_hint='http') if path_info is None: log.msg('User %s tried to access %s ' 'but the lookup failed' % (self.username, path)) return resource log.msg('Lookup of %s gave %r' % (path, path_info)) if (path_info['repository_fs_path'] is None and path_info['repository_base_fs_path'] is None): log.msg('Neither a repository base nor a repository were returned') return resource # split script_name / new_path according to path info if path_info['repository_base_url_path'] is not None: script_name = '/' script_name += path_info['repository_base_url_path'].strip('/') new_path = path[len(script_name.rstrip('/')):] # since pretty much everything needs read access, check for it now if not self.authnz.can_read(self.username, path_info): if self.username is None: return UnauthorizedResource(self.credentialFactories) else: return ForbiddenResource("You don't have read access") # Smart HTTP requests # /info/refs if (len(pathparts) >= 2 and pathparts[-2] == 'info' and pathparts[-1] == 'refs'): writerequired = ('service' in request.args and request.args['service'][0] == 'git-receive-pack') resource = InfoRefs(path_info['repository_fs_path']) # /git-upload-pack (client pull) elif len(pathparts) >= 1 and pathparts[-1] == 'git-upload-pack': cmd = 'git' args = [os.path.basename(cmd), 'upload-pack', '--stateless-rpc', path_info['repository_fs_path']] resource = GitCommand(cmd, args) request.setHeader('Content-Type', 'application/x-git-upload-pack-result') # /git-receive-pack (client push) elif len(pathparts) >= 1 and pathparts[-1] == 'git-receive-pack': writerequired = True cmd = 'git' args = [os.path.basename(cmd), 'receive-pack', '--stateless-rpc', path_info['repository_fs_path']] resource = GitCommand(cmd, args) request.setHeader('Content-Type', 'application/x-git-receive-pack-result') # static files as specified in file_headers or fallback webfrontend else: # determine the headers for this file filename, headers = None, None for matcher, get_headers in file_headers.items(): m = matcher.match(path) if m: filename = m.group(1) headers = get_headers() break if filename is not None: for key, val in headers.items(): request.setHeader(key, val) log.msg("Returning file %s" % os.path.join( path_info['repository_fs_path'], filename)) resource = File(os.path.join(path_info['repository_fs_path'], filename), headers['Content-Type']) resource.isLeaf = True # static file -> it is a leaf else: # No match -> fallback to git viewer if script_name is not None: # patch pre/post path of request according to # script_name and path request.prepath = script_name.strip('/').split('/') if request.prepath == ['']: request.prepath = [] request.postpath = new_path.lstrip('/').split('/') log.msg("pre and post: %r %r" % (request.prepath, request.postpath)) # If the resource has a withEnviron function, it's # probably our own flavour of WSGIResource that # supports passing further args for the environ if hasattr(self.git_viewer, "withEnviron"): # set wsgirouting args routing_args = { 'repository_path': path_info['repository_fs_path'], 'repository_base': path_info['repository_base_fs_path'] } if 'repository_clone_urls' in path_info: routing_args['repository_clone_urls'] = path_info['repository_clone_urls'] resource = self.git_viewer.withEnviron( {'wsgiorg.routing_args': ([], routing_args)}) else: resource = self.git_viewer # before returning the resource, check if write access is required # and enforce privileges accordingly # anonymous (username = None) will never be granted write access if writerequired and (self.username is None or not self.authnz.can_write(self.username, path_info)): if self.username is None: return UnauthorizedResource(self.credentialFactories) else: return ForbiddenResource("You don't have write access") return resource
def responseNotFound(self, request, failure): errorPage = NoResource(message=failure.getErrorMessage()) request.write(errorPage.render(request)) request.finish()
def render(self, request): notFound = NoResource("CGI directories do not support directory listing.") return notFound.render(request)
def __init__(self): NoResource.__init__(self, b"Resource not found")
def __init__(self): NoResource.__init__(self, "No pack number specified") self.brief = "No Such Pack" self.types = collections.namedtuple("Pack_Types", ["ERROR", "REDIRECT", "QUEUE"])._make(range(3)) self.type = self.types.ERROR