def _handle_client(self, client, address): try: r = SocketReader(client) p = HttpStream(r) headers = p.headers() body = "" if "CONTENT-LENGTH" in headers and int( headers["CONTENT-LENGTH"]) > 0: body = p.body_string(binary=False) # System requests if p.path() == "/alive": self._respond(client, "ok") return # User requests req = IpcServer.Request(self._respond, client, p.path(), p.method(), headers, body) if p.path() == "/message": req.respond() self.requests.put(req) except Exception as e: client.close() raise e
def handle(self, sock, addr): p = HttpStream(SocketReader(sock)) path = p.path() data = "welcome wold" sock.send("".join(["HTTP/1.1 200 OK\r\n", "Content-Type: text/html\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data]))
def handle(self, sock, addr): p = HttpStream(SocketReader(sock)) path = p.path() data = "hello world" sock.send("".join([ "HTTP/1.1 200 OK\r\n", "Content-Type: text/html\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data ]))
def handle(self): self.logger = logging.getLogger("proxy") self.session = Session() try: request = HttpStream(SocketReader(self.request)) _ = request.status() except http_parser.http.BadStatusLine: return self.logger.warning(request.path()) if 'CONNECT' == request.method(): self.https_proxy(request) else: self.http_proxy(request) self.session.close()
def https_proxy(self, connectreq: HttpStream): self.request.sendall(CON_ESTABLISH) host, port = connectreq.path().split(':') cert_path = self.generate_cert(host) # request to localhost as server try: sock_client = ssl.wrap_socket(self.request, keyfile="cert.key", certfile=cert_path, ssl_version=ssl.PROTOCOL_TLS, server_side=True) sock_server = socket.create_connection((host, port)) sock_server = ssl.create_default_context().wrap_socket(sock_server, server_hostname=host) except OSError: return client_reader = SocketReader(sock_client) server_reader = SocketReader(sock_server) while True: # request to mail.ru as client clientreq = HttpStream(client_reader, decompress=True) try: clientreq_tosend = join_data(clientreq, 'Request') except (http_parser.http.ParserError, http_parser.http.BadStatusLine, ConnectionResetError): return sock_server.sendall(clientreq_tosend) # request from mail.ru to localhost as client server_resp = HttpStream(server_reader, decompress=True) try: server_resp_tosend = join_data(server_resp, 'Response') except (http_parser.http.ParserError, http_parser.http.BadStatusLine, ConnectionResetError): return try: sock_client.sendall(server_resp_tosend) except BrokenPipeError: return req = Request(clientreq.method(), server_resp.status_code(), clientreq_tosend, host) self.add_date_base(clientreq, req)
def rewrite_request(self, req, extra): try: while True: if extra.get('rewrite_location', True): parser = HttpStream(req) prefix = extra.get('prefix', '') location = parser.url() if prefix: try: location = location.split(prefix, 1)[1] or '/' except IndexError: pass headers = rewrite_headers(parser, location, [('host', extra.get('host'))]) if headers is None: break extra['path'] = parser.path() req.writeall(headers) body = parser.body_file() while True: data = body.read(8192) if not data: break req.writeall(data) else: while True: data = req.read(io.DEFAULT_BUFFER_SIZE) if not data: break req.writeall(data) except (socket.error, NoMoreData): pass
def handle(self, sock, addr): p = HttpStream(SocketReader(sock)) path = p.path() if not path or path == "/": path = "index.html" if path.startswith("/"): path = path[1:] real_path = os.path.join(CURDIR, "static", path) if os.path.isdir(real_path): lines = ["<ul>"] for d in os.listdir(real_path): fpath = os.path.join(real_path, d) lines.append("<li><a href=" + d + ">" + d + "</a>") data = "".join(lines) resp = "".join(["HTTP/1.1 200 OK\r\n", "Content-Type: text/html\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data]) sock.sendall(resp) elif not os.path.exists(real_path): util.write_error(sock, 404, "Not found", real_path + " not found") else: ctype = mimetypes.guess_type(real_path)[0] if ctype.startswith('text') or 'html' in ctype: try: f = open(real_path, 'rb') data = f.read() resp = "".join(["HTTP/1.1 200 OK\r\n", "Content-Type: " + ctype + "\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data]) sock.sendall(resp) finally: f.close() else: try: f = open(real_path, 'r') clen = int(os.fstat(f.fileno())[6]) # send headers sock.send("".join(["HTTP/1.1 200 OK\r\n", "Content-Type: " + ctype + "\r\n", "Content-Length:" + str(clen) + "\r\n", "Connection: close\r\n\r\n"])) if not sendfile: while True: data = f.read(4096) if not data: break sock.send(data) else: fileno = f.fileno() sockno = sock.fileno() sent = 0 offset = 0 nbytes = clen sent += sendfile(sockno, fileno, offset+sent, nbytes-sent) while sent != nbytes: sent += sendfile(sock.fileno(), fileno, offset+sent, nbytes-sent) finally: f.close()
def handle(self, sock, addr): p = HttpStream(SocketReader(sock)) path = p.path() if not path or path == "/": path = "index.html" if path.startswith("/"): path = path[1:] real_path = os.path.join(CURDIR, "static", path) if os.path.isdir(real_path): lines = ["<ul>"] for d in os.listdir(real_path): fpath = os.path.join(real_path, d) lines.append("<li><a href=" + d + ">" + d + "</a>") data = "".join(lines) resp = "".join([ "HTTP/1.1 200 OK\r\n", "Content-Type: text/html\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data ]) sock.sendall(resp) elif not os.path.exists(real_path): util.write_error(sock, 404, "Not found", real_path + " not found") else: ctype = mimetypes.guess_type(real_path)[0] if ctype.startswith('text') or 'html' in ctype: try: f = open(real_path, 'rb') data = f.read() resp = "".join([ "HTTP/1.1 200 OK\r\n", "Content-Type: " + ctype + "\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data ]) sock.sendall(resp) finally: f.close() else: try: f = open(real_path, 'r') clen = int(os.fstat(f.fileno())[6]) # send headers sock.send("".join([ "HTTP/1.1 200 OK\r\n", "Content-Type: " + ctype + "\r\n", "Content-Length:" + str(clen) + "\r\n", "Connection: close\r\n\r\n" ])) if not sendfile: while True: data = f.read(4096) if not data: break sock.send(data) else: fileno = f.fileno() sockno = sock.fileno() sent = 0 offset = 0 nbytes = clen sent += sendfile(sockno, fileno, offset + sent, nbytes - sent) while sent != nbytes: sent += sendfile(sock.fileno(), fileno, offset + sent, nbytes - sent) finally: f.close()
def handle(self, sock, addr): sock.setblocking(1) try: p = HttpStream(SocketReader(sock)) path = p.path() if not path or path == "/": path = "index.html" if path.startswith("/"): path = path[1:] real_path = os.path.join(self.conf['path'], path) if os.path.isdir(real_path): lines = ["<ul>"] for d in os.listdir(real_path): fpath = os.path.join(real_path, d) lines.append("<li><a href=" + d + ">" + d + "</a>") data = "".join(lines) resp = "".join(["HTTP/1.1 200 OK\r\n", "Content-Type: text/html\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data]) sock.sendall(resp) elif not os.path.exists(real_path): util.write_error(sock, 404, "Not found", real_path + " not found") else: ctype = mimetypes.guess_type(real_path)[0] fno = None try: fno = os.open(real_path, os.O_RDONLY|os.O_NONBLOCK) clen = int(os.fstat(fno)[6]) # send headers sock.send("".join(["HTTP/1.1 200 OK\r\n", "Content-Type: " + ctype + "\r\n", "Content-Length:" + str(clen) + "\r\n", "Connection: close\r\n\r\n"])) if not sendfile: while True: data = os.read(fno, 4096) if not data: break sock.send(data) else: offset = 0 nbytes = clen if nbytes > BLKSIZE: # Send file in at most 1GB blocks as some operating # systems can have problems with sending files in blocks # over 2GB. for m in range(0, nbytes, BLKSIZE): sendfile_all(fno, sock.fileno(), offset, min(nbytes, BLKSIZE)) offset += BLKSIZE nbytes -= BLKSIZE else: sendfile_all(fno, sock.fileno(), offset, nbytes) finally: if fno is not None: os.close(fno) finally: # make sure we close the socket try: sock.close() except: pass