import sys
import base64
import socket
from http.server import HTTPServer, BaseHTTPRequestHandler

latest_result = ""

def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('8.8.8.8', 80))
        IP = s.getsockname()[0]
    except Exception:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP

class OOBHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        global latest_result
        if self.path == "/get":
            self.send_response(200)
            self.send_header('Content-type', 'text/plain; charset=utf-8')
            self.end_headers()
            # The result is already decoded when stored, but user wants base64 for fetch too?
            # Re-encoding for safety during fetch as requested
            result_b64 = base64.b64encode(latest_result.encode('utf-8')).decode('utf-8')
            self.wfile.write(result_b64.encode('utf-8'))
            latest_result = "" # Clear after read
        else:
            self.send_response(404)
            self.end_headers()

    def do_POST(self):
        global latest_result
        if self.path == "/data":
            try:
                content_length = int(self.headers['Content-Length'])
                post_data = self.rfile.read(content_length).decode('utf-8', errors='replace')
                
                # Add padding if needed
                padding = len(post_data) % 4
                if padding > 0:
                    post_data += "=" * (4 - padding)
                
                decoded = base64.b64decode(post_data).decode('utf-8', errors='replace')
                latest_result = decoded
                
                self.send_response(200)
                self.end_headers()
                self.wfile.write(b"OK")
                print(f"[+] Received data (base64 decoded): {decoded[:50]}...")
            except Exception as e:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(str(e).encode())
                print(f"[-] Error processing POST: {e}")
        else:
            self.send_response(404)
            self.end_headers()

def run_server(port):
    server = HTTPServer(('0.0.0.0', port), OOBHandler)
    ip = get_ip()
    print("="*60)
    print(f"OOB Server started successfully!")
    print(f"Local Fetch URL: http://127.0.0.1:{port}/get")
    print(f"Remote Data URL: http://{ip}:{port}/data")
    print("="*60)
    print("Waiting for data...")
    server.serve_forever()

if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
    run_server(port)
