forked from mtusi2026/mtusi2026lab6
55 lines
2.7 KiB
Python
55 lines
2.7 KiB
Python
import base64, json, socket, struct, sys, urllib.request, uuid, zlib
|
|
|
|
BASE_HOST, BASE_PORT = "localhost", 8080
|
|
PWD = "correct-horse-battery-staple"
|
|
|
|
|
|
def api(method, path, body=None, headers=None):
|
|
req = urllib.request.Request(f"http://{BASE_HOST}:{BASE_PORT}{path}", data=body, method=method, headers=headers or {})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=30) as r:
|
|
return r.status, r.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read()
|
|
|
|
|
|
def chunk(t, d):
|
|
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
|
|
|
|
|
|
PNG = (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0))
|
|
+ chunk(b"IDAT", zlib.compress(b"".join(b"\x00" + b"\x10\x80\xf0" * 8 for _ in range(8)))) + chunk(b"IEND", b""))
|
|
|
|
name = "up_" + uuid.uuid4().hex[:8]
|
|
j = {"Content-Type": "application/json"}
|
|
_, raw = api("POST", "/api/v1/users", json.dumps({"username": name, "display_name": "u", "password": PWD}).encode(), j)
|
|
user = json.loads(raw)
|
|
_, raw = api("POST", "/api/v1/auth/sessions", None, {"Authorization": "Basic " + base64.b64encode(f"{name}:{PWD}".encode()).decode()})
|
|
token = json.loads(raw)["token"]
|
|
_, raw = api("POST", "/api/v1/chats", json.dumps({"title": "u", "member_ids": [user["id"]]}).encode(), {**j, "Authorization": "Bearer " + token})
|
|
chat = json.loads(raw)
|
|
|
|
mode = sys.argv[1] if len(sys.argv) > 1 else "ok"
|
|
if mode == "ok":
|
|
st, raw = api("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=u.png", PNG,
|
|
{"Content-Type": "image/png", "Authorization": "Bearer " + token})
|
|
print("upload status:", st)
|
|
elif mode == "abort":
|
|
# заявляем 5 МБ отправляем 300 КБ и закрываем соединение
|
|
s = socket.create_connection((BASE_HOST, BASE_PORT))
|
|
head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=a.png HTTP/1.1\r\nHost: localhost\r\n"
|
|
f"Authorization: Bearer {token}\r\nContent-Type: image/png\r\nContent-Length: 5000000\r\n\r\n")
|
|
s.sendall(head.encode() + PNG + b"\0" * 300_000)
|
|
s.close()
|
|
print("aborted upload after 300 KB of 5000000")
|
|
elif mode == "roundtrip":
|
|
import hashlib
|
|
st, raw = api("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=r.png", PNG,
|
|
{"Content-Type": "image/png", "Authorization": "Bearer " + token})
|
|
if st != 201:
|
|
print("upload", st); sys.exit(1)
|
|
att = json.loads(raw)
|
|
st, data = api("GET", f"/api/v1/attachments/{att['id']}/content", None, {"Authorization": "Bearer " + token})
|
|
good = st == 200 and hashlib.sha256(data).hexdigest() == att["sha256"]
|
|
print("roundtrip", "ok" if good else f"fail {st}")
|
|
sys.exit(0 if good else 1) |