import socket,os
s=socket.socket(); s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(('0.0.0.0',8891)); s.listen(5)
while True:
    c,_=s.accept()
    try:
        f=c.makefile('rb')
        req=f.readline().decode(errors="replace").strip()
        parts=req.split()
        path=parts[1].lstrip('/') if len(parts)>1 else 'up.bin'
        hdrs={}
        while True:
            l=f.readline()
            if l in (b'\r\n',b'\n',b''): break
            k,_,v=l.decode(errors="replace").partition(':')
            hdrs[k.strip().lower()]=v.strip()
        try: c.sendall(b'HTTP/1.1 100 Continue\r\n\r\n')
        except Exception: pass
        n=int(hdrs.get('content-length','0') or 0)
        out='/tmp/up_'+os.path.basename(path)
        got=0
        with open(out,'wb') as o:
            while got<n:
                d=f.read(min(1<<18,n-got))
                if not d: break
                o.write(d); got+=len(d)
        try: c.sendall(b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok')
        except Exception: pass
        print('SAVED',out,got,flush=True)
    except Exception:
        pass
    finally:
        c.close()
