#!/usr/bin/env python3 """TCP Brutal v2 speed test server. Each connection starts with a 20-byte header from the client: group ID (u64), rate in bytes/s (u64), duration in seconds (u32). The server puts the connection into that Brutal group and sends random data for the duration. All connections sharing a group ID share the rate. """ import argparse import errno import os import socket import struct import sys import threading import time TCP_CONGESTION = 13 TCP_BRUTAL_PARAMS = 23301 TCP_BRUTAL_VERSION = 23302 CWND_GAIN = 15 HEADER = struct.Struct("!QQI") CHUNK_SIZE = 65536 def brutal_version(conn): conn.setsockopt(socket.IPPROTO_TCP, TCP_CONGESTION, b"brutal") raw = conn.getsockopt(socket.IPPROTO_TCP, TCP_BRUTAL_VERSION, 4) return struct.unpack("> 16}.{(version >> 8) & 0xFF}.{version & 0xFF}") def recv_exact(conn, n): buf = b"" while len(buf) < n: chunk = conn.recv(n - len(buf)) if not chunk: return None buf += chunk return buf def handle(conn, addr): peer = f"{addr[0]}:{addr[1]}" try: header = recv_exact(conn, HEADER.size) if header is None: return group_id, rate, duration = HEADER.unpack(header) try: conn.setsockopt(socket.IPPROTO_TCP, TCP_CONGESTION, b"brutal") except PermissionError: # A "congctl lock" route pinned the algorithm; fine if it is brutal cc = conn.getsockopt(socket.IPPROTO_TCP, TCP_CONGESTION, 16).rstrip(b"\0") if cc != b"brutal": raise try: conn.setsockopt( socket.IPPROTO_TCP, TCP_BRUTAL_PARAMS, struct.pack("