コード例 #1
0
ファイル: url.py プロジェクト: mscherfling/circuits
 def escape(self):
     '''Make sure that the path is correctly escaped'''
     self._path = quote(unquote(self._path.decode("utf-8"))).encode("utf-8")
     return self
コード例 #2
0
ファイル: http.py プロジェクト: ke4roh/circuits
    def _on_read(self, sock, data):
        """Read Event Handler

        Process any incoming data appending it to an internal buffer.
        Split the buffer by the standard HTTP delimiter CRLF and create
        Raw Event per line. Any unfinished lines of text, leave in the buffer.
        """

        if sock in self._buffers:
            parser = self._buffers[sock]
        else:
            self._buffers[sock] = parser = HttpParser(0, True)

            # If we receive an SSL handshake at the start of a request
            # and we're not a secure server, then immediately close the
            # client connection since we can't respond to it anyway.

            if is_ssl_handshake(data) and not self._server.secure:
                if sock in self._buffers:
                    del self._buffers[sock]
                if sock in self._clients:
                    del self._clients[sock]
                return self.fire(close(sock))

        _scheme = "https" if self._server.secure else "http"
        parser.execute(data, len(data))
        if not parser.is_headers_complete():
            if parser.errno is not None:
                if parser.errno == BAD_FIRST_LINE:
                    req = wrappers.Request(sock, server=self._server)
                else:
                    req = wrappers.Request(
                        sock,
                        parser.get_method(),
                        parser.get_scheme() or _scheme,
                        parser.get_path(),
                        parser.get_version(),
                        parser.get_query_string(),
                        server=self._server
                    )
                req.server = self._server
                res = wrappers.Response(req, encoding=self._encoding)
                del self._buffers[sock]
                return self.fire(httperror(req, res, 400))
            return

        if sock in self._clients:
            req, res = self._clients[sock]
        else:
            method = parser.get_method()
            scheme = parser.get_scheme() or _scheme
            path = parser.get_path()
            version = parser.get_version()
            query_string = parser.get_query_string()

            req = wrappers.Request(
                sock, method, scheme, path, version, query_string,
                headers=parser.get_headers(), server=self._server
            )

            res = wrappers.Response(req, encoding=self._encoding)

            self._clients[sock] = (req, res)

            rp = req.protocol
            sp = self.protocol

            if rp[0] != sp[0]:
                # the major HTTP version differs
                return self.fire(httperror(req, res, 505))

            res.protocol = "HTTP/{0:d}.{1:d}".format(*min(rp, sp))
            res.close = not parser.should_keep_alive()

        clen = int(req.headers.get("Content-Length", "0"))
        if clen and not parser.is_message_complete():
            return

        if hasattr(sock, "getpeercert"):
            peer_cert = sock.getpeercert()
            if peer_cert:
                e = request(req, res, peer_cert)
            else:
                e = request(req, res)
        else:
            e = request(req, res)

        # Guard against unwanted request paths (SECURITY).
        path = req.path
        _path = req.uri._path
        if (path.encode(self._encoding) != _path) and (
                quote(path).encode(self._encoding) != _path):
            return self.fire(
                redirect(req, res, [req.uri.utf8()], 301)
            )

        req.body = BytesIO(parser.recv_body())
        del self._buffers[sock]

        self.fire(e)
コード例 #3
0
ファイル: static.py プロジェクト: yws/circuits
    def _on_request(self, event, request, response):
        if self.path is not None and not request.path.startswith(self.path):
            return

        path = request.path

        if self.path is not None:
            path = path[len(self.path):]

        path = unquote(path.strip("/"))

        if path:
            location = os.path.abspath(os.path.join(self.docroot, path))
        else:
            location = os.path.abspath(os.path.join(self.docroot, "."))

        if not os.path.exists(location):
            return

        if not location.startswith(os.path.dirname(self.docroot)):
            return  # hacking attemp e.g. /foo/../../../../../etc/shadow

        # Is it a file we can serve directly?
        if os.path.isfile(location):
            # Don't set cookies for static content
            response.cookie.clear()
            try:
                return serve_file(request, response, location)
            finally:
                event.stop()

        # Is it a directory?
        elif os.path.isdir(location):

            # Try to serve one of default files first..
            for default in self.defaults:
                location = os.path.abspath(
                    os.path.join(self.docroot, path, default))
                if os.path.exists(location):
                    # Don't set cookies for static content
                    response.cookie.clear()
                    try:
                        return serve_file(request, response, location)
                    finally:
                        event.stop()

            # .. serve a directory listing if allowed to.
            if self.dirlisting:
                directory = os.path.abspath(os.path.join(self.docroot, path))
                cur_dir = os.path.join(self.path, path) if self.path else ""

                if not path:
                    url_up = ""
                else:
                    if self.path is None:
                        url_up = os.path.join("/", os.path.split(path)[0])
                    else:
                        url_up = os.path.join(cur_dir, "..")
                    url_up = '<li><a href="%s">%s</a></li>' % (url_up, "..")

                listing = []
                for item in os.listdir(directory):
                    if not item.startswith("."):
                        url = os.path.join("/", path, cur_dir, item)
                        location = os.path.abspath(
                            os.path.join(self.docroot, path, item))
                        if os.path.isdir(location):
                            li = '<li><a href="%s/">%s/</a></li>' % (
                                quote(url), item)
                        else:
                            li = '<li><a href="%s">%s</a></li>' % (quote(url),
                                                                   item)
                        listing.append(li)

                ctx = {}
                ctx["directory"] = cur_dir or os.path.join("/", cur_dir, path)
                ctx["url_up"] = url_up
                ctx["listing"] = "\n".join(listing)
                try:
                    return _dirlisting_template.safe_substitute(ctx)
                finally:
                    event.stop()
コード例 #4
0
ファイル: static.py プロジェクト: ke4roh/circuits
    def _on_request(self, event, request, response):
        if self.path is not None and not request.path.startswith(self.path):
            return

        path = request.path

        if self.path is not None:
            path = path[len(self.path):]

        path = unquote(path.strip("/"))

        if path:
            location = os.path.abspath(os.path.join(self.docroot, path))
        else:
            location = os.path.abspath(os.path.join(self.docroot, "."))

        if not os.path.exists(location):
            return

        if not location.startswith(os.path.dirname(self.docroot)):
            return  # hacking attemp e.g. /foo/../../../../../etc/shadow

        # Is it a file we can serve directly?
        if os.path.isfile(location):
            # Don't set cookies for static content
            response.cookie.clear()
            try:
                return serve_file(request, response, location)
            finally:
                event.stop()

        # Is it a directory?
        elif os.path.isdir(location):

            # Try to serve one of default files first..
            for default in self.defaults:
                location = os.path.abspath(
                    os.path.join(self.docroot, path, default)
                )
                if os.path.exists(location):
                    # Don't set cookies for static content
                    response.cookie.clear()
                    try:
                        return serve_file(request, response, location)
                    finally:
                        event.stop()

            # .. serve a directory listing if allowed to.
            if self.dirlisting:
                directory = os.path.abspath(os.path.join(self.docroot, path))
                cur_dir = os.path.join(self.path, path) if self.path else ""

                if not path:
                    url_up = ""
                else:
                    if self.path is None:
                        url_up = os.path.join("/", os.path.split(path)[0])
                    else:
                        url_up = os.path.join(cur_dir, "..")
                    url_up = '<li><a href="%s">%s</a></li>' % (url_up, "..")

                listing = []
                for item in os.listdir(directory):
                    if not item.startswith("."):
                        url = os.path.join("/", path, cur_dir, item)
                        location = os.path.abspath(
                            os.path.join(self.docroot, path, item)
                        )
                        if os.path.isdir(location):
                            li = '<li><a href="%s/">%s/</a></li>' % (
                                quote(url), item
                            )
                        else:
                            li = '<li><a href="%s">%s</a></li>' % (
                                quote(url), item
                            )
                        listing.append(li)

                ctx = {}
                ctx["directory"] = cur_dir or os.path.join("/", cur_dir, path)
                ctx["url_up"] = url_up
                ctx["listing"] = "\n".join(listing)
                try:
                    return _dirlisting_template.safe_substitute(ctx)
                finally:
                    event.stop()
コード例 #5
0
    def _on_read(self, sock, data):
        """Read Event Handler

        Process any incoming data appending it to an internal buffer.
        Split the buffer by the standard HTTP delimiter CRLF and create
        Raw Event per line. Any unfinished lines of text, leave in the buffer.
        """

        if sock in self._buffers:
            parser = self._buffers[sock]
        else:
            self._buffers[sock] = parser = HttpParser(0, True)

            # If we receive an SSL handshake at the start of a request
            # and we're not a secure server, then immediately close the
            # client connection since we can't respond to it anyway.

            if is_ssl_handshake(data) and not self._server.secure:
                if sock in self._buffers:
                    del self._buffers[sock]
                if sock in self._clients:
                    del self._clients[sock]
                return self.fire(close(sock))

        _scheme = "https" if self._server.secure else "http"
        parser.execute(data, len(data))
        if not parser.is_headers_complete():
            if parser.errno is not None:
                if parser.errno == BAD_FIRST_LINE:
                    req = wrappers.Request(sock, server=self._server)
                else:
                    req = wrappers.Request(sock,
                                           parser.get_method(),
                                           parser.get_scheme() or _scheme,
                                           parser.get_path(),
                                           parser.get_version(),
                                           parser.get_query_string(),
                                           server=self._server)
                req.server = self._server
                res = wrappers.Response(req, encoding=self._encoding)
                del self._buffers[sock]
                return self.fire(httperror(req, res, 400))
            return

        if sock in self._clients:
            req, res = self._clients[sock]
        else:
            method = parser.get_method()
            scheme = parser.get_scheme() or _scheme
            path = parser.get_path()
            version = parser.get_version()
            query_string = parser.get_query_string()

            req = wrappers.Request(sock,
                                   method,
                                   scheme,
                                   path,
                                   version,
                                   query_string,
                                   headers=parser.get_headers(),
                                   server=self._server)

            res = wrappers.Response(req, encoding=self._encoding)

            self._clients[sock] = (req, res)

            rp = req.protocol
            sp = self.protocol

            if rp[0] != sp[0]:
                # the major HTTP version differs
                return self.fire(httperror(req, res, 505))

            res.protocol = "HTTP/{0:d}.{1:d}".format(*min(rp, sp))
            res.close = not parser.should_keep_alive()

        clen = int(req.headers.get("Content-Length", "0"))
        if clen and not parser.is_message_complete():
            return

        if hasattr(sock, "getpeercert"):
            peer_cert = sock.getpeercert()
            if peer_cert:
                e = request(req, res, peer_cert)
            else:
                e = request(req, res)
        else:
            e = request(req, res)

        # Guard against unwanted request paths (SECURITY).
        path = req.path
        _path = req.uri._path
        if (path.encode(self._encoding) != _path) and (quote(path).encode(
                self._encoding) != _path):
            return self.fire(redirect(req, res, [req.uri.utf8()], 301))

        req.body = BytesIO(parser.recv_body())
        del self._buffers[sock]

        self.fire(e)