// TOSV - The Only Safe Vault, C++17 HTTP vault + WebDAV. Shared core in vault.inc. #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #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 formv(std::string b){std::map 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 SESS; static std::vector SESSQ; static void sess_add(std::string id){std::lock_guard L(M);SESS[id]=std::chrono::duration_cast(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 L(M);auto it=SESS.find(v);if(it==SESS.end())return false;long long sn=std::chrono::duration_cast(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 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(s0){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()TOSV
User
Pass
");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(f)),std::istreambuf_iterator());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 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="

TOSV wizard

two_way="+std::string(db.tw?"1":"0")+" layers="+std::to_string(db.layers)+" store="+db.su+" v"+std::string(TOSV_VERSION)+"

IPs
From To
Mode
Layers

logout

";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 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="TOSV grant

Grant created

Mode: "+mode+"

Copy now. Screenshots live forever; short windows bound the damage.

Retrieve

User: "+g.gu+"

Pass: "+g.gp+"

ID: "+g.gid+"

Store

User: "+db.su+"

Pass: "+g.gp+"

ID: "+g.gid+"

Store

User: "+db.su+"

Pass: "+db.sp+"

Back | Logout

";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()&&nsfrm){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 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 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=""+esc(href)+""+(dir?"":"")+""+esc(fs::path(fspath).filename().string())+"";if(!dir){try{xml+=""+std::to_string(dav_len(fspath))+"";}catch(...){}}xml+="application/octet-streamHTTP/1.1 200 OK";return xml;}; std::string xml="";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> st;st.emplace_back(fp,qpath); while(!st.empty()&&vis<10000){auto[cur,href0]=st.back();st.pop_back();std::vector> 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+="";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 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","opaquelocktoken:"+uuid4()+"");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 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=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 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 "< 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 "< 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<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: "<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