// TOSV - The Only Safe Vault, C++17 HTTP vault + WebDAV. Shared core in vault.inc.
#include <algorithm>
#include <poll.h>
#include <chrono>
#include <fcntl.h>
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <sstream>
#include <iostream>
#include <list>
#include <random>
#include <chrono>
#include <iomanip>
#include <filesystem>
#include <thread>
#include <mutex>
#include <cstring>
#include <cstdint>
#include <atomic>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <sys/mman.h>
#include <sodium.h>
#include "vault.inc"
#include "mlkem_native.h"
extern "C" int tosv_mlkem_rng(uint8_t*o,size_t n){randombytes_buf(o,n);return 0;}
#include "tls13.inc"
#ifndef TOSV_VERSION
#define TOSV_VERSION "dev"
#endif
// ---- minimal HTTP server ----
static std::string urldec(std::string s){std::string o;for(size_t i=0;i<s.size();i++){if(s[i]=='+')o+=' ';else if(s[i]=='%'&&i+2<s.size()){o+=(char)strtol(s.substr(i+1,2).c_str(),0,16);i+=2;}else o+=s[i];}return o;}
static std::map<std::string,std::string> formv(std::string b){std::map<std::string,std::string> m;std::stringstream ss(b);std::string kv;while(std::getline(ss,kv,'&')){auto p=kv.find('=');if(p==std::string::npos)continue;m[urldec(kv.substr(0,p))]=urldec(kv.substr(p+1));}return m;}
static std::string b64d(std::string s){static int T[256];static bool I=false;if(!I){memset(T,-1,sizeof T);const char*A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(int i=0;A[i];i++)T[(unsigned char)A[i]]=i;I=true;}std::string o;int v=0,nb=0;for(char c:s){if(c=='=')break;int x=T[(unsigned char)c];if(x<0)continue;v=(v<<6)|x;nb+=6;if(nb>=8){nb-=8;o+=(char)((v>>nb)&255);}}std::string r=o;wipe_mem(o.data(),o.size());return r;}
static void send_all(int fd,const std::string&h,const char*body,size_t n){send(fd,h.c_str(),h.size(),0);size_t s=0;while(s<n){ssize_t w=send(fd,body+s,n-s,0);if(w<=0)break;s+=w;}}
static void resp(int fd,int code,const std::string&ct,const std::string&body,const std::string&extra=""){std::string h="HTTP/1.1 "+std::to_string(code)+" OK\r\nContent-Type: "+ct+"\r\nContent-Length: "+std::to_string(body.size())+"\r\nConnection: close\r\nCache-Control: no-store\r\n"+extra+"\r\n";send_all(fd,h,body.data(),body.size());}
static void resp_wipe(int fd,int code,const std::string&ct,std::string&body){resp(fd,code,ct,body);wipe_mem(body.data(),body.size());}
static void resp_early(int fd,int code,const std::string&ct,const std::string&body){resp(fd,code,ct,body);shutdown(fd,SHUT_WR);close(fd);}
// sessions live in SESS, added via sess_add with 1000-cap oldest-drop
static std::map<std::string,long long> SESS;
static std::vector<std::string> SESSQ;
static void sess_add(std::string id){std::lock_guard<std::mutex> L(M);SESS[id]=std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();SESSQ.push_back(id);while(SESSQ.size()>1000){SESS.erase(SESSQ.front());SESSQ.erase(SESSQ.begin());}}
static bool sess_ok(std::string hd){auto p=hd.find("Cookie:");if(p==std::string::npos)return false;auto q=hd.find("tosv=",p);if(q==std::string::npos)return false;q+=5;auto e=hd.find_first_of(";\r\n",q);std::string v=hd.substr(q,e==std::string::npos?std::string::npos:e-q);std::lock_guard<std::mutex> L(M);auto it=SESS.find(v);if(it==SESS.end())return false;long long sn=std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();if(sn-it->second>86400){SESS.erase(it);return false;}it->second=sn;return true;}
static void handle_inner(int fd,std::string peer);
static std::atomic<int> CONN{0};
struct ConnGuard{~ConnGuard(){CONN--;}};
static void handle(int fd,std::string peer){if(CONN.fetch_add(1)>=64){CONN--;resp(fd,503,"text/plain","busy");close(fd);return;}ConnGuard g;(void)g;try{handle_inner(fd,peer);}catch(...){try{resp(fd,500,"text/plain","error");}catch(...){}close(fd);}}
static KeyCache KC;
// returns 0 after sending 200+stream, else 1 tag mismatch, 2 crypto fail, 3 bad size/header (nothing sent)
static int fetch_v2(int fd,std::string p,std::string auth){ParamWipe _pw(auth);size_t plain=0;int c=v2_check(p,auth,KC,plain);if(c!=0)return c;std::string hout="HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: "+std::to_string(plain)+"\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n";send(fd,hout.c_str(),hout.size(),0);fetch_v2_stream(p,auth,KC,[fd](unsigned char*m,size_t n){size_t s=0;while(s<n){ssize_t w=send(fd,(char*)m+s,n-s,0);if(w<=0)break;s+=w;}});return 0;}
static void handle_inner(int fd,std::string peer){
char buf[8192];std::string req;ssize_t r;while((r=recv(fd,buf,sizeof buf,0))>0){req.append(buf,r);if(req.find("\r\n\r\n")!=std::string::npos)break;if(req.size()>65536)break;}if(req.empty()){close(fd);return;}
std::istringstream rl(req);std::string method,path,ver;rl>>method>>path>>ver;
size_t hh=req.find("\r\n\r\n");std::string hd=req.substr(0,hh==std::string::npos?req.size():hh);
{auto te=hd.find("Transfer-Encoding:");if(te!=std::string::npos){auto ee=hd.find("\r\n",te);std::string tv=hd.substr(te,ee==std::string::npos?std::string::npos:ee-te);if(tv.find("chunked")!=std::string::npos||tv.find("Chunked")!=std::string::npos){resp(fd,501,"text/plain","no chunked");close(fd);return;}}}
size_t cl=0;{auto p=hd.find("Content-Length:");if(p!=std::string::npos)cl=strtoull(hd.substr(p+15).c_str(),0,10);}if(cl>536870912){resp_early(fd,413,"text/plain","too large");return;}
std::string qpath=path;auto qp=qpath.find('?');if(qp!=std::string::npos)qpath=qpath.substr(0,qp);
if((qpath=="/login"||qpath=="/grant")&&method=="POST"&&cl>65536){resp_early(fd,413,"text/plain","form too large");return;}
std::string body=hh==std::string::npos?"":req.substr(hh+4);
while(body.size()<cl){char b2[8192];r=recv(fd,b2,sizeof b2,0);if(r<=0)break;body.append(b2,r);}
DB db=load_db();DBGuard _dbg(db);
if(wiped()){resp(fd,403,"text/plain","wiped");close(fd);return;}
if(qpath=="/login"&&method=="GET"){resp(fd,200,"text/html","<h1>TOSV</h1><form method=post>User <input name=u><br>Pass <input type=password name=p><br><input type=submit value=Login></form>");close(fd);return;}
if(qpath=="/login"&&method=="POST"){
auto fm=formv(body);WipeStr u(fm["u"]),p(fm["p"]);wipe_mem(fm["u"].data(),fm["u"].size());wipe_mem(fm["p"].data(),fm["p"].size());
if(!db.duress.empty()&&cred_match(db.duress,u.str(),p.str())){audit("duress",peer);mark_wiped();wipe_store(KC);resp(fd,403,"text/plain","wiped");close(fd);return;}if(is_blocked(peer)){resp(fd,403,"text/plain","blocked");close(fd);return;}if(!rate_ok("login:"+peer,5,300)){strike(peer);if(is_blocked(peer))audit("blocked",peer);resp(fd,429,"text/plain","blocked");close(fd);return;}
WipeStr eu,ep;{std::ifstream f(ENVF());std::string s((std::istreambuf_iterator<char>(f)),std::istreambuf_iterator<char>());auto pu=s.find("\"user\""),pp=s.find("\"pass\"");if(pu!=std::string::npos){auto q1=s.find('"',pu+7),q2=s.find('"',q1+1);eu.ref()=s.substr(q1+1,q2-q1-1);}if(pp!=std::string::npos){auto q1=s.find('"',pp+7),q2=s.find('"',q1+1);ep.ref()=s.substr(q1+1,q2-q1-1);wipe_mem(s.data(),s.size());}}
if(!eu.str().empty()&&!db.used&&u.str()==eu.str()&&p.str()==ep.str()){{std::lock_guard<std::mutex> L(DBM);db=load_db();if(eu.str().empty()||db.used||u.str()!=eu.str()||p.str()!=ep.str()){resp(fd,403,"text/plain","denied");close(fd);return;}db.used=true;db.su="store_"+hexr(8);{std::random_device rd;std::string t;const char*A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";for(int i=0;i<22;i++)t+=A[rd()%64];db.sp=t;wipe_mem(t.data(),t.size());}db.duress="duress:"+hexr(8);if(!save_db(db)){resp(fd,500,"text/plain","store failed");close(fd);return;}}std::string sid="s_"+hexr(16);sess_add(sid);audit("bootstrap",peer);resp(fd,302,"text/plain","","Location: /\r\nSet-Cookie: tosv="+sid+"; Path=/; HttpOnly; SameSite=Lax\r\n");close(fd);return;}
if(db.used&&u.str()==db.su&&p.str()==db.sp){std::string sid2="s_"+hexr(16);sess_add(sid2);audit("login",peer);resp(fd,302,"text/plain","","Location: /\r\nSet-Cookie: tosv="+sid2+"; Path=/; HttpOnly; SameSite=Lax\r\n");close(fd);return;}
strike(peer);if(is_blocked(peer))audit("blocked",peer);resp(fd,403,"text/plain","denied");close(fd);return;}
if(!sess_ok(hd)&&qpath!="/login"&&qpath!="/store"&&qpath.rfind("/fetch/",0)!=0&&qpath!="/dav"&&qpath.rfind("/dav/",0)!=0){resp(fd,302,"text/plain","","Location: /login\r\n");close(fd);return;}
if(qpath=="/"&&method=="GET"){std::string h="<h1>TOSV wizard</h1><p>two_way="+std::string(db.tw?"1":"0")+" layers="+std::to_string(db.layers)+" store="+db.su+" v"+std::string(TOSV_VERSION)+"</p><form method=post action=/grant>IPs <input name=ips><br>From <input name=frm type=datetime-local> To <input name=to type=datetime-local><br>Mode <label><input type=radio name=tw value=0 checked> append-only</label> <label><input type=radio name=tw value=1> two-way</label><br>Layers <input name=layers value=3><br><input type=submit value=Maak></form><p><a href=/logout>logout</a></p>";resp(fd,200,"text/html",h);close(fd);return;}
if(qpath=="/grant"&&method=="POST"){auto fm=formv(body);Grant g;GrantGuard _gg(g);g.gu="get_"+hexr(8);{std::random_device rd;std::string t;const char*A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";for(int i=0;i<22;i++)t+=A[rd()%64];g.gp=t;wipe_mem(t.data(),t.size());}g.gid=uuid4();g.ips=fm["ips"];g.frm=fm["frm"];g.to=fm["to"];{std::lock_guard<std::mutex> L(DBM);db=load_db();if(fm.count("tw"))db.tw=(fm["tw"]=="1");try{db.layers=fm.count("layers")?std::max(1,std::min(8,atoi(fm["layers"].c_str()))):db.layers;}catch(...){}if((!fm["frm"].empty()&&!valid_ts(fm["frm"]))||(!fm["to"].empty()&&!valid_ts(fm["to"]))){resp(fd,400,"text/plain","bad window");close(fd);return;}if(db.grants.size()>=10000){resp(fd,507,"text/plain","grants full");close(fd);return;}db.grants.push_back(g);if(!save_db(db)){resp(fd,500,"text/plain","store failed");close(fd);return;}}audit("grant "+g.gid,peer);std::string mode=(db.tw?"two-way drive":"append-only");std::string j="{\"retrieve\":{\"user\":\""+g.gu+"\",\"pass\":\""+g.gp+"\",\"id\":\""+g.gid+"\"},\"store\":{\"user\":\""+db.su+"\",\"pass\":\""+db.sp+"\"},\"two_way\":"+(db.tw?"true":"false")+",\"mode\":\""+mode+"\"}";bool wantJson=false;{auto ap=hd.find("Accept:");if(ap!=std::string::npos){auto ae=hd.find("\r\n",ap);if(hd.substr(ap,ae==std::string::npos?std::string::npos:ae-ap).find("application/json")!=std::string::npos)wantJson=true;}}if(wantJson){resp_wipe(fd,200,"application/json",j);close(fd);return;}std::string h="<!doctype html><html><head><meta charset=utf-8><meta name=viewport content=\"width=device-width,initial-scale=1\"><title>TOSV grant</title><style>body{font-family:system-ui,sans-serif;max-width:640px;margin:40px auto;padding:0 16px}code{background:#f2f2f2;padding:2px 6px;border-radius:4px;word-break:break-all}.card{border:1px solid #ddd;border-radius:8px;padding:16px;margin:12px 0}</style></head><body><h1>Grant created</h1><p>Mode: <b>"+mode+"</b></p><p><b>Copy now.</b> Screenshots live forever; short windows bound the damage.</p><div class=card><h3>Retrieve</h3><p>User: <code>"+g.gu+"</code></p><p>Pass: <code>"+g.gp+"</code></p><p>ID: <code>"+g.gid+"</code></p></div><div class=card><h3>Store</h3><p>User: <code>"+db.su+"</code></p><p>Pass: <code>"+g.gp+"</code></p><p>ID: <code>"+g.gid+"</code></p></div><div class=card><h3>Store</h3><p>User: <code>"+db.su+"</code></p><p>Pass: <code>"+db.sp+"</code></p></div><p><a href=/>Back</a> | <a href=/logout>Logout</a></p></body></html>";wipe_mem(j.data(),j.size());resp_wipe(fd,200,"text/html; charset=utf-8",h);close(fd);return;}
if(qpath=="/store"&&method=="POST"){WipeStr au;{auto p=hd.find("Authorization: Basic ");if(p!=std::string::npos){auto e=hd.find("\r\n",p);au.ref()=b64d(hd.substr(p+21,e-p-21));}}if(db.su.empty()||!cred_match(au.str(),db.su,db.sp)){resp(fd,403,"text/plain","denied");close(fd);return;}if(!rate_ok("store:"+peer,20,300)){resp(fd,429,"text/plain","blocked");close(fd);return;}if(store_full()){resp(fd,507,"text/plain","store full");close(fd);return;}std::string fid=uuid4();fs::create_directories(STORED());std::string tmp=STORED()+"/"+fid+".bin";if(!store_v2(tmp,(unsigned char*)body.data(),body.size(),db.su+":"+db.sp)){std::error_code ec;fs::remove(tmp,ec);fs::remove(tmp+".tag",ec);resp(fd,500,"text/plain","store failed");close(fd);return;}audit("store "+fid,peer);resp(fd,200,"application/json","{\"id\":\""+fid+"\"}");close(fd);return;}
if(qpath.rfind("/fetch/",0)==0&&method=="GET"){std::string fid=qpath.substr(7);if(!fid_ok(fid)){resp(fd,404,"text/plain","missing");close(fd);return;}WipeStr au;{auto p=hd.find("Authorization: Basic ");if(p!=std::string::npos){auto e=hd.find("\r\n",p);au.ref()=b64d(hd.substr(p+21,e-p-21));}}Grant*g=nullptr;for(auto&x:db.grants)if(cred_match(au.str(),x.gu,x.gp)){g=&x;break;}if(!g){resp(fd,403,"text/plain","denied");close(fd);return;}if(!g->ips.empty()&&!ip_ok(g->ips,peer)){resp(fd,403,"text/plain","denied ip");close(fd);return;}std::string ns=window_now();if(!g->frm.empty()&&ns<g->frm){resp(fd,403,"text/plain","too early");close(fd);return;}if(!g->to.empty()&&ns>g->to){resp(fd,403,"text/plain","expired");close(fd);return;}std::string p=STORED()+"/"+fid+".bin";std::ifstream f(p,std::ios::binary);if(!f){resp(fd,404,"text/plain","missing");close(fd);return;}size_t fl=0;try{fl=fs::file_size(p);}catch(...){resp(fd,404,"text/plain","missing");close(fd);return;}{int bv=blob_ver(p);if(bv!=1&&bv!=2){audit("integrity-fail "+fid,peer);resp(fd,500,"text/plain","unsupported version");close(fd);return;}if(bv==2){int fr=fetch_v2(fd,p,db.su+":"+db.sp);if(fr!=0){audit((fr==2?"aead-fail ":"integrity-fail ")+fid,peer);resp(fd,500,"text/plain","integrity fail");close(fd);return;}audit("fetch "+fid,peer);close(fd);return;}}{int tc=tag_check(p,db.layers);if(tc==2){audit("integrity-fail "+fid,peer);resp(fd,500,"text/plain","integrity fail");close(fd);return;}}auto ks2=derive(db.su+":"+db.sp,"00",tag_layers(p,db.layers));{std::string h="HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: "+std::to_string(fl)+"\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n";send(fd,h.c_str(),h.size(),0);}std::vector<unsigned char> ch2(65536);long long off=0;while(f){f.read((char*)ch2.data(),65536);std::streamsize n=f.gcount();if(n<=0)break;crypt_buf(ch2.data(),(size_t)n,ks2.v,off);size_t s=0;while(s<(size_t)n){ssize_t w=send(fd,(char*)ch2.data()+s,(size_t)n-s,0);if(w<=0)break;s+=(size_t)w;}off+=n;}audit("fetch "+fid,peer);close(fd);return;}
if(qpath=="/logout"){auto q2=hd.find("tosv=");if(q2!=std::string::npos){q2+=5;auto ee=hd.find_first_of(";\r\n",q2);std::lock_guard<std::mutex> L(M);SESS.erase(hd.substr(q2,ee==std::string::npos?std::string::npos:ee-q2));}resp(fd,302,"text/plain","","Location: /login\r\nSet-Cookie: tosv=; Path=/\r\n");close(fd);return;}
// ---- WebDAV in-binary (RFC4918 Class 1, same port, Basic grant auth) ----
auto dav_auth=[&]()->Grant*{WipeStr au;{auto p=hd.find("Authorization: Basic ");if(p!=std::string::npos){auto e=hd.find("\r\n",p);au.ref()=b64d(hd.substr(p+21,e-p-21));}}for(auto&x:db.grants)if(cred_match(au.str(),x.gu,x.gp))return &x;if(!db.su.empty()&&cred_match(au.str(),db.su,db.sp)){thread_local static Grant s;DB d2=load_db();DBGuard _d2g(d2);wipe_mem(s.gu.data(),s.gu.size());wipe_mem(s.gp.data(),s.gp.size());s.gu=d2.su;s.gp=d2.sp;return &s;}return nullptr;};
auto dav_path=[&](std::string qp2)->std::string{std::string r=urldec(qp2);if(r.rfind("/dav",0)==0)r=r.substr(4);if(r.empty())r="/";while(r.find("..")!=std::string::npos)r.replace(r.find(".."),2,"");return STORED()+r;};
if((qpath=="/dav"||qpath.rfind("/dav/",0)==0)){
if(method=="OPTIONS"){std::string h="HTTP/1.1 200 OK\r\nDAV: 1\r\nAllow: OPTIONS,GET,HEAD,PUT,DELETE,PROPFIND,PROPPATCH,MKCOL,COPY,MOVE,LOCK,UNLOCK\r\nContent-Length: 0\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n";send(fd,h.c_str(),h.size(),0);close(fd);return;}
Grant*g=dav_auth();if(!g){std::string h="HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"tosv-dav\"\r\nContent-Length: 0\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n";send(fd,h.c_str(),h.size(),0);close(fd);return;}
if(!g->ips.empty()&&!ip_ok(g->ips,peer)){resp(fd,403,"text/plain","denied ip");close(fd);return;}
std::string fp=dav_path(qpath);
if(method=="PROPFIND"){if(!fs::exists(fp)){resp(fd,404,"text/plain","missing");close(fd);return;}audit("dav-list "+qpath,peer);std::string depth="1";{auto p=hd.find("Depth:");if(p!=std::string::npos){auto e=hd.find("\r\n",p);depth=hd.substr(p+6,e-p-6);while(!depth.empty()&&(depth[0]==' '))depth.erase(depth.begin());}}auto esc=[](std::string s){std::string o;for(char c:s){if(c=='&')o+="&";else if(c=='<')o+="<";else if(c=='>')o+=">";else if(c=='"')o+=""";else o+=c;}return o;};
auto entry=[&](std::string fspath,std::string href){bool dir=fs::is_directory(fspath);std::string xml="<d:response><d:href>"+esc(href)+"</d:href><d:propstat><d:prop><d:resourcetype>"+(dir?"<d:collection/>":"")+"</d:resourcetype><d:displayname>"+esc(fs::path(fspath).filename().string())+"</d:displayname>";if(!dir){try{xml+="<d:getcontentlength>"+std::to_string(dav_len(fspath))+"</d:getcontentlength>";}catch(...){}}xml+="<d:getcontenttype>application/octet-stream</d:getcontenttype></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>";return xml;};
std::string xml="<?xml version=\"1.0\"?><d:multistatus xmlns:d=\"DAV:\">";try{xml+=entry(fp,qpath);}catch(...){resp(fd,404,"text/plain","missing");close(fd);return;}
bool fpdir=false;try{fpdir=fs::is_directory(fp);}catch(...){}
if((depth=="1"||depth=="infinity")&&fpdir){size_t scan=0,vis=0;std::vector<std::pair<std::string,std::string>> st;st.emplace_back(fp,qpath);
while(!st.empty()&&vis<10000){auto[cur,href0]=st.back();st.pop_back();std::vector<std::pair<std::string,std::string>> kids;try{for(auto&p:fs::directory_iterator(cur)){if(++scan>20000)break;std::string pn=p.path().filename().string();if(pn.size()>4&&pn.substr(pn.size()-4)==".tag")continue;std::string href=href0;if(href.back()!='/')href+="/";href+=pn;try{xml+=entry(p.path().string(),href);}catch(...){continue;}if(++vis>=10000)break;if(depth=="infinity"){try{if(fs::is_directory(p.path()))kids.emplace_back(p.path().string(),href);}catch(...){}}}}catch(...){}for(auto it=kids.rbegin();it!=kids.rend();++it)st.push_back(*it);}}
xml+="</d:multistatus>";resp(fd,207,"application/xml; charset=utf-8",xml);close(fd);return;}
if(method=="MKCOL"){std::error_code mec;fs::create_directories(fp,mec);if(mec||!fs::exists(fp)){resp(fd,500,"text/plain","mkdir failed");close(fd);return;}audit("dav-mkcol "+qpath,peer);resp(fd,201,"text/plain","");close(fd);return;}
if(method=="PUT"){if(!db.tw&&fs::exists(fp)){resp(fd,403,"text/plain","append-only");close(fd);return;}if(store_full()){resp(fd,507,"text/plain","store full");close(fd);return;}fs::create_directories(fs::path(fp).parent_path());if(!store_v2(fp,(unsigned char*)body.data(),body.size(),db.su+":"+db.sp)){std::error_code ec;fs::remove(fp,ec);fs::remove(fp+".tag",ec);resp(fd,500,"text/plain","store failed");close(fd);return;}audit("dav-put "+qpath,peer);resp(fd,201,"text/plain","");close(fd);return;}
if(method=="GET"||method=="HEAD"){if(!fs::exists(fp)){resp(fd,404,"text/plain","missing");close(fd);return;}audit("dav-get "+qpath,peer);if(fs::is_directory(fp)){if(method=="HEAD")resp(fd,200,"application/octet-stream","");else resp(fd,404,"text/plain","missing");close(fd);return;}if(method=="HEAD"){size_t hl=0;try{hl=dav_len(fp);}catch(...){}std::string hh2="HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: "+std::to_string(hl)+"\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n";send(fd,hh2.c_str(),hh2.size(),0);close(fd);return;}size_t dl=0;try{dl=fs::file_size(fp);}catch(...){resp(fd,404,"text/plain","missing");close(fd);return;}{int bv2=blob_ver(fp);if(bv2!=1&&bv2!=2){audit("integrity-fail "+qpath,peer);resp(fd,500,"text/plain","unsupported version");close(fd);return;}if(bv2==2){int fr2=fetch_v2(fd,fp,db.su+":"+db.sp);if(fr2!=0){audit((fr2==2?"aead-fail ":"integrity-fail ")+qpath,peer);resp(fd,500,"text/plain","integrity fail");close(fd);return;}close(fd);return;}{int tc=tag_check(fp,db.layers);if(tc==2){audit("integrity-fail "+qpath,peer);resp(fd,500,"text/plain","integrity fail");close(fd);return;}}}auto gks=derive(db.su+":"+db.sp,"00",tag_layers(fp,db.layers));{std::string h="HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: "+std::to_string(dl)+"\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n";send(fd,h.c_str(),h.size(),0);}std::ifstream df(fp,std::ios::binary);std::vector<unsigned char> dch(65536);long long doff=0;while(df){df.read((char*)dch.data(),65536);std::streamsize dn=df.gcount();if(dn<=0)break;crypt_buf(dch.data(),(size_t)dn,gks.v,doff);size_t ds=0;while(ds<(size_t)dn){ssize_t dw=send(fd,(char*)dch.data()+ds,(size_t)dn-ds,0);if(dw<=0)break;ds+=(size_t)dw;}doff+=dn;}close(fd);return;}
if(method=="DELETE"){if(!db.tw){resp(fd,403,"text/plain","append-only");close(fd);return;}{std::error_code ec;fs::remove_all(fp,ec);fs::remove(fp+".tag",ec);}audit("dav-del "+qpath,peer);resp(fd,204,"text/plain","");close(fd);return;}
if(method=="COPY"||method=="MOVE"){auto p=hd.find("Destination:");if(p==std::string::npos){resp(fd,400,"text/plain","no dest");close(fd);return;}auto e=hd.find("\r\n",p);std::string dest=hd.substr(p+12,e-p-12);while(!dest.empty()&&dest[0]==' ')dest.erase(dest.begin());auto dp=dest.find("/dav");if(dp==std::string::npos){resp(fd,400,"text/plain","bad destination");close(fd);return;}std::string dfp=dav_path(dest.substr(dp+4));if(!db.tw&&(method=="MOVE"||fs::exists(dfp))){resp(fd,403,"text/plain","append-only");close(fd);return;}fs::create_directories(fs::path(dfp).parent_path());if(method=="COPY"){fs::copy(fp,dfp,fs::copy_options::recursive|fs::copy_options::overwrite_existing);{try{fs::copy(fp+".tag",dfp+".tag",fs::copy_options::overwrite_existing);}catch(...){}}}else{if(rename(fp.c_str(),dfp.c_str())!=0){resp(fd,500,"text/plain","move failed");close(fd);return;}rename((fp+".tag").c_str(),(dfp+".tag").c_str());}audit(std::string("dav-")+(method=="COPY"?"copy":"move")+" "+qpath,peer);resp(fd,201,"text/plain","");close(fd);return;}
if(method=="LOCK"){resp(fd,200,"application/xml","<?xml version=\"1.0\"?><d:prop xmlns:d=\"DAV:\"><d:lockdiscovery><d:activelock><d:locktoken><d:href>opaquelocktoken:"+uuid4()+"</d:href></d:locktoken></d:activelock></d:lockdiscovery></d:prop>");close(fd);return;}
if(method=="UNLOCK"||method=="PROPPATCH"){resp(fd,200,"text/plain","");close(fd);return;}
resp(fd,405,"text/plain","dav?");close(fd);return;}
resp(fd,404,"text/plain","missing");close(fd);}
// ---- SEC-11: in-tree TLS 1.3 (tls13.inc, ADR 0011). Pump thread terminates TLS and relays to a socketpair. ----
static TlsId TLSID;static bool TLSON=false,TLS_CLASSICAL=false;
static std::atomic<int> TLSC{0};
static const int TLS_MAX=128;
static bool tls_init(std::string&err){const char*c=getenv("TOSV_TLS_CERT");const char*k=getenv("TOSV_TLS_KEY");if(!(c&&*c)&&!(k&&*k))return true;if(!(c&&*c&&k&&*k)){err="TOSV_TLS_CERT and TOSV_TLS_KEY must both be set";return false;}
const char*cl=getenv("TOSV_TLS_ALLOW_CLASSICAL");TLS_CLASSICAL=cl&&cl[0]=='1'&&cl[1]==0;if(!tls_load_id(c,k,TLSID,err))return false;TLSON=true;return true;}
static bool wr_all(int fd,const char*b,size_t n){size_t o=0;while(o<n){ssize_t w=send(fd,b+o,n-o,MSG_NOSIGNAL);if(w<=0)return false;o+=(size_t)w;}return true;}
static void tls_serve(int fd,std::string peer){if(TLSC.fetch_add(1)>=TLS_MAX){TLSC--;close(fd);return;}
timeval tv{30,0};setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&tv,sizeof tv);Tls13 t(fd,!TLS_CLASSICAL,&TLSID);
if(!t.handshake()){audit("tls-fail",peer);close(fd);TLSC--;return;}
int sp[2];if(socketpair(AF_UNIX,SOCK_STREAM,0,sp)!=0){close(fd);TLSC--;return;}setsockopt(sp[1],SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof tv);
try{std::thread(handle,sp[1],peer).detach();}catch(...){close(sp[0]);close(sp[1]);close(fd);TLSC--;return;}
std::vector<char> buf(16000);bool cin=true;
while(true){pollfd pf[2]={{cin?fd:-1,POLLIN,0},{sp[0],POLLIN,0}};int r=poll(pf,2,60000);if(r<=0)break;
if(cin&&(pf[0].revents&(POLLIN|POLLHUP|POLLERR))){TBytes d;int g=t.read_app(d);if(g==1){if(!wr_all(sp[0],(const char*)d.data(),d.size()))break;wipe_mem(d.data(),d.size());}else{cin=false;shutdown(sp[0],SHUT_WR);if(g<0)break;}}
if(pf[1].revents&(POLLIN|POLLHUP|POLLERR)){ssize_t n=read(sp[0],buf.data(),buf.size());if(n<=0)break;if(!t.send_rec(23,TBytes(buf.begin(),buf.begin()+n)))break;}}
if(cin||true){TBytes a={1,0};t.send_rec(21,a);}wipe_mem(buf.data(),buf.size());close(fd);close(sp[0]);TLSC--;}
// ---- FR-17 / R-20: offline v1 -> v2 re-store. Dry-run by default; --apply converts. Originals move to tosv_v1_bak/. ----
static int restore_v2(bool apply){auto d=load_db();std::string auth=d.su+":"+d.sp;int nv1=0,done=0,skip=0;std::string bak=BASE+"/tosv_v1_bak";if(apply){try{fs::create_directories(bak);}catch(...){std::cerr<<"cannot create "<<bak<<"\n";return 1;}}
std::vector<std::string> files;try{for(auto&e:fs::directory_iterator(STORED())){if(!e.is_regular_file())continue;std::string n=e.path().filename().string();if(n.size()<5||n.substr(n.size()-4)!=".bin"||n.find(".part.")!=std::string::npos)continue;files.push_back(e.path().string());}}catch(...){std::cerr<<"cannot list store\n";return 1;}
std::sort(files.begin(),files.end());
for(auto&p:files){if(blob_ver(p)!=1)continue;nv1++;if(!apply){std::cout<<"would-convert "<<p<<"\n";continue;}
if(tag_check(p,d.layers)==2){std::cerr<<"SKIP integrity-fail "<<p<<"\n";audit("restore-v2 skip integrity "+p);skip++;continue;}
std::string tmp=p+".v2tmp";bool ok=false;unsigned char h1[32];{auto ks=derive(auth,"00",tag_layers(p,d.layers));crypto_hash_sha256_state hs;crypto_hash_sha256_init(&hs);V2Push w;std::ifstream f(p,std::ios::binary);if(f&&w.open(tmp,auth)){std::vector<unsigned char> b(65536);long long off=0;ok=true;while(ok){f.read((char*)b.data(),65536);std::streamsize n=f.gcount();if(n<=0)break;crypt_buf(b.data(),(size_t)n,ks.v,off);off+=n;crypto_hash_sha256_update(&hs,b.data(),(size_t)n);ok=w.push(b.data(),(size_t)n);wipe_mem(b.data(),b.size());}if(ok)ok=w.finish();}crypto_hash_sha256_final(&hs,h1);}
if(ok){KeyCache kc;V2Pull r;crypto_hash_sha256_state hs;crypto_hash_sha256_init(&hs);unsigned char h2[32];ok=false;std::ofstream tt(tmp+".tag");tt<<real_fhash(tmp)<<" 0 2";tt.close();if(r.open(tmp,auth,kc)){bool last=false;bool good=true;while(!last&&good)good=r.next([&](unsigned char*m,size_t n){crypto_hash_sha256_update(&hs,m,n);wipe_mem(m,n);},last);crypto_hash_sha256_final(&hs,h2);ok=good&&sodium_memcmp(h1,h2,32)==0;}}
if(!ok){std::cerr<<"SKIP verify-fail "<<p<<"\n";audit("restore-v2 skip verify "+p);skip++;std::error_code ec;fs::remove(tmp,ec);fs::remove(tmp+".tag",ec);continue;}
try{std::string base=fs::path(p).filename().string();fs::rename(p,bak+"/"+base);if(fs::exists(p+".tag"))fs::rename(p+".tag",bak+"/"+base+".tag");fs::rename(tmp,p);fs::rename(tmp+".tag",p+".tag");}catch(...){std::cerr<<"FAIL move "<<p<<" (originals in "<<bak<<")\n";audit("restore-v2 fail move "+p);return 1;}
audit("restore-v2 converted "+p);done++;std::cout<<"converted "<<p<<"\n";}
std::cout<<"v1="<<nv1<<" converted="<<done<<" skipped="<<skip<<(apply?"":" (dry-run, pass --apply)")<<"\n";if(apply&&done)std::cout<<"originals in "<<bak<<": verify, then delete them (v1 copies stay malleable)\n";return skip?2:0;}
int main(int argc,char**argv){if(sodium_init()<0){std::cerr<<"sodium init failed\n";return 1;}if(argc>1&&std::string(argv[1])=="--tls-selfsign"){if(argc!=5){std::cerr<<"usage: tosv --tls-selfsign NAME CERT.pem KEY.pem\n";return 2;}std::string e;if(!tls_selfsign(argv[2],argv[3],argv[4],e)){std::cerr<<"selfsign: "<<e<<"\n";return 1;}std::cout<<"wrote "<<argv[3]<<" and "<<argv[4]<<" (Ed25519, 365 days)\n";return 0;}if(argc>1&&std::string(argv[1])=="--restore-v2"){bool ap=argc>2&&std::string(argv[2])=="--apply";if(argc>2&&!ap){std::cerr<<"usage: tosv --restore-v2 [--apply]\n";return 1;}return restore_v2(ap);}signal(SIGTERM,on_sig);signal(SIGINT,on_sig);signal(SIGHUP,on_sig);signal(SIGPIPE,SIG_IGN);int port=argc>1?atoi(argv[1]):8765;if(port<1||port>65535){std::cerr<<"bad port\n";return 1;}try{fs::create_directories(STORED());}catch(...){std::cerr<<"cannot create store\n";return 1;}
try{if(!fs::exists(ENVF())){std::random_device rd;std::string t;const char*A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";for(int i=0;i<16;i++)t+=A[rd()%64];std::string ej="{\"user\":\"admin\",\"pass\":\""+t+"\"}";wipe_mem(t.data(),t.size());int efd=open(ENVF().c_str(),O_WRONLY|O_CREAT|O_TRUNC,0600);if(efd<0){std::cerr<<"cannot create .env.json\n";return 1;}fchmod(efd,0600);size_t eo=0;while(eo<ej.size()){ssize_t w=write(efd,ej.data()+eo,ej.size()-eo);if(w<=0)break;eo+=(size_t)w;}close(efd);wipe_mem(ej.data(),ej.size());if(eo!=ej.size()){std::cerr<<"cannot create .env.json\n";return 1;}}if(!fs::exists(ENVF())){std::cerr<<"cannot create .env.json\n";return 1;}}catch(...){std::cerr<<"cannot access .env.json\n";return 1;}
{char mpr[4096];int mlr=mlock(mpr,sizeof mpr),mdr=madvise(mpr,sizeof mpr,MADV_DONTDUMP);munlock(mpr,sizeof mpr);std::cout<<"memlock="<<(mlr==0?"ok":"no")<<" dontdump="<<(mdr==0?"ok":"no")<<"\n"<<std::flush;}{std::string te;if(!tls_init(te)){std::cerr<<"tls: "<<te<<"\n";return 1;}}const char*bh=getenv("TOSV_BIND");std::string bind_ip=(bh&&*bh)?bh:"127.0.0.1";if(bind_ip!="127.0.0.1"&&!TLSON){std::cerr<<"TOSV_BIND other than 127.0.0.1 requires TLS (TOSV_TLS_CERT and TOSV_TLS_KEY)\n";return 1;}int ls=socket(AF_INET,SOCK_STREAM,0);int one=1;setsockopt(ls,SOL_SOCKET,SO_REUSEADDR,&one,sizeof one);sockaddr_in a{};a.sin_family=AF_INET;if(inet_pton(AF_INET,bind_ip.c_str(),&a.sin_addr)!=1){std::cerr<<"bad TOSV_BIND\n";return 1;}a.sin_port=htons(port);if(bind(ls,(sockaddr*)&a,sizeof a)!=0){perror("bind");_exit(1);}listen(ls,64);std::cout<<"TOSV "<<TOSV_VERSION<<" on "<<bind_ip<<":"<<port<<"\n"<<std::flush;if(TLSON)std::cout<<"tls=1.3 groups="<<(TLS_CLASSICAL?"X25519MLKEM768:X25519":"X25519MLKEM768")<<"\n"<<std::flush;{const char*ns=getenv("TOSV_NTP");if(ns&&*ns)std::thread(ntp_loop,std::string(ns)).detach();}
while(true){sockaddr_in c{};socklen_t n=sizeof c;int fd=accept(ls,(sockaddr*)&c,&n);if(fd<0)continue;timeval rtv{30,0};setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&rtv,sizeof rtv);char ip[64];inet_ntop(AF_INET,&c.sin_addr,ip,64);try{if(TLSON)std::thread(tls_serve,fd,std::string(ip)).detach();else std::thread(handle,fd,std::string(ip)).detach();}catch(...){close(fd);}}}