#include "settings/proxy_settings.h" #include "platform/platform.h" #include "transport/http_transport.h" #include "engine/torrent_backend.h" #include "engine/download_link.h" #include "settings/tracker_settings.h" #include "settings/tracker_import.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace lt=libtorrent; void Check(bool ok,const char* text) { if(!ok) throw std::runtime_error(text); } std::string Drain(http::ResponseStream& stream) { std::string result; char buffer[7919]; for(;;) { auto read=stream.Read(buffer); if(read.state==http::ReadState::kEnd) return result; Check(read.state==http::ReadState::kData,"FTP stream read"); result.append(buffer,read.size); } } void Certificate(const std::filesystem::path& root) { std::filesystem::create_directories(root); auto* context=EVP_PKEY_CTX_new_id(EVP_PKEY_RSA,nullptr); Check(context!=nullptr,"create test key"); EVP_PKEY* key=nullptr; Check(EVP_PKEY_keygen_init(context)>0 && EVP_PKEY_CTX_set_rsa_keygen_bits(context,2048)>0 && EVP_PKEY_keygen(context,&key)>0,"generate local test key"); auto* certificate=X509_new(); X509_set_version(certificate,2); ASN1_INTEGER_set(X509_get_serialNumber(certificate),1); X509_gmtime_adj(X509_getm_notBefore(certificate),-60); X509_gmtime_adj(X509_getm_notAfter(certificate),86400); X509_set_pubkey(certificate,key); auto* name=X509_get_subject_name(certificate); X509_NAME_add_entry_by_txt(name,"CN",MBSTRING_ASC,reinterpret_cast("localhost"),-1,-1,0); X509_set_issuer_name(certificate,name); X509V3_CTX extension{}; X509V3_set_ctx(&extension,certificate,certificate,nullptr,nullptr,0); auto* san=X509V3_EXT_conf_nid(nullptr,&extension,NID_subject_alt_name,const_cast("DNS:localhost,IP:127.0.0.1")); X509_add_ext(certificate,san,-1); X509_EXTENSION_free(san); Check(X509_sign(certificate,key,EVP_sha256())>0,"sign untrusted test certificate"); FILE* file=nullptr; _wfopen_s(&file,(root/L"cert.pem").c_str(),L"wb"); Check(file && PEM_write_X509(file,certificate),"write test certificate"); fclose(file); _wfopen_s(&file,(root/L"key.pem").c_str(),L"wb"); Check(file && PEM_write_PrivateKey(file,key,nullptr,nullptr,0,nullptr,nullptr),"write test key"); fclose(file); X509_free(certificate); EVP_PKEY_free(key); EVP_PKEY_CTX_free(context); } int wmain(int argc,wchar_t** argv) { try { SetCurrentProxy({}); if(argc==3 && std::wstring(argv[1])==L"--tls-fixture") { Certificate(argv[2]); return 0; } const bool import_only=argc==3 && std::wstring(argv[1])==L"--tracker-import-tests"; Check(argc==6 || import_only,"loopback fixture URL required"); const std::wstring base=argv[1]; auto imported=ParseTrackerImport("\xef\xbb\xbfudp://127.0.0.1:1234/announce\r\nhttp://127.0.0.1:8080/announce\nhttps://unsupported.test/a\n",L"udp://127.0.0.1:1234/announce"); Check(imported.error.empty() && imported.added==2 && imported.duplicates==1 && imported.skipped==0,"TXT import merges, deduplicates and reports unsupported entries"); auto https_only=ParseTrackerImport("https://tracker.example/announce\n",L""); Check(https_only.added==1 && https_only.skipped==0 && https_only.error.empty(),"HTTPS tracker TXT import is supported"); std::wstring full_list; for(int i=0;i<2000;++i) full_list+=L"http://tracker.example/"+std::to_wstring(i)+L"\n"; auto appended=ParseTrackerImport("https://tracker.example/announce\ninvalid\n",full_list); Check(appended.added==1 && appended.invalid==1 && appended.skipped==1,"append beyond former 128 tracker and 32767 character caps"); std::vector many; std::wstring parse_error; Check(ParseTrackers(appended.text,many,parse_error) && many.size()==2001,"large tracker list remains complete after normalization"); auto long_url=ParseTrackerImport("https://tracker.example/"+std::string(3000,'a')+"\n",L""); Check(long_url.added==1 && long_url.error.empty(),"do not impose an arbitrary tracker URL length cap"); Check(!ParseTrackerImport("bad gateway",L"").error.empty(),"reject HTML as tracker list"); std::string large_text; for(int i=0;i<6000;++i) large_text+="https://tracker.example/"+std::to_string(i)+"/"+std::string(180,'a')+"\n"; auto large=ParseTrackerImport(large_text,L""); Check(large_text.size()>1024*1024 && large.added==6000 && large.error.empty(),"import valid TXT above former 1 MiB limit without truncation"); std::atomic canceled=false; auto txt_base=std::wstring(argv[2]); for(auto route:{L"/trackers.txt",L"/redirect.txt"}) { auto remote=ImportTrackerText(txt_base+route,true,L"",canceled); Check(remote.error.empty() && remote.added==3 && remote.duplicates==1 && remote.skipped==0,"online TXT import and redirect use loopback only"); } Check(!ImportTrackerText(txt_base+L"/missing.txt",true,L"",canceled).error.empty(),"online TXT 404 must not replace current list"); auto remote_large=ImportTrackerText(txt_base+L"/large.txt",true,L"",canceled); Check(remote_large.added==6000 && remote_large.error.empty(),"online TXT above 1 MiB is imported in full"); auto txt_path=std::filesystem::temp_directory_path()/(L"TTDownloader_tracker_import_"+std::to_wstring(GetCurrentProcessId())+L".txt"); const std::wstring wide_txt=L"udp://127.0.0.1:1234/announce\r\n"; { std::ofstream out(txt_path,std::ios::binary); out.put(char(255)); out.put(char(254)); out.write(reinterpret_cast(wide_txt.data()),wide_txt.size()*2); } auto local=ImportTrackerText(txt_path.wstring(),false,L"",canceled); Check(local.error.empty() && local.added==1,"local UTF-16 TXT import"); { std::ofstream out(txt_path,std::ios::binary|std::ios::trunc); out.write(large_text.data(),large_text.size()); } auto local_large=ImportTrackerText(txt_path.wstring(),false,L"",canceled); Check(local_large.added==6000 && local_large.error.empty(),"local TXT above 1 MiB is imported in full"); std::filesystem::remove(txt_path); canceled=true; Check(!ImportTrackerText(txt_base+L"/trackers.txt",true,L"",canceled).error.empty(),"canceled import does not make a request"); std::vector trackers; std::wstring tracker_error; Check(ParseTrackers(L"# comment\r\nudp://127.0.0.1:1234/announce\r\nhttp://127.0.0.1:5678/announce\r\nudp://127.0.0.1:1234/announce",trackers,tracker_error) && trackers.size()==2,"parse, deduplicate trackers"); for(const auto& bad:{L"ftp://example.test/announce",L"file:///secret",L"udp://host:99999/announce",L"http://user:password@host/a",L"udp://host/announce",L"http://bad host/a"}) Check(!ParseTrackers(bad,trackers,tracker_error),"reject unsupported or invalid trackers"); if(import_only) { std::cout<<"PASS: uncapped tracker parsing, local/online TXT above 1 MiB, normalization and validation\n"; return 0; } auto transport=http::CreateDefaultTransport(); const std::string data(256*1024,'X'); for(const auto& route:{L"/file.bin",L"/no-rest.bin"}) for(int offset:{0,711,262144}) { http::Request request; request.url=base+route; request.range_offset=offset; auto opened=transport->Open(request); Check(!!opened.stream,"open FTP stream"); auto expected=opened.stream->Headers().status==200?data:data.substr(offset); Check(Drain(*opened.stream)==expected,"FTP payload, restart fallback and resumed payload"); } http::Request authenticated; authenticated.url=base+L"/file.bin"; authenticated.url.insert(6,L"user:pass@"); auto login=transport->Open(authenticated); Check(login.stream && Drain(*login.stream)==data,"FTP URL authentication"); http::Request missing; missing.url=base+L"/missing.bin"; Check(!transport->Open(missing).stream,"FTP missing file reports failure"); ProxySettings proxy; proxy.type=1; proxy.host=L"127.0.0.1"; proxy.port=argv[3]; proxy.user=L"test"; proxy.password=L"pw"; std::wstring proxy_error; Check(ValidateProxy(proxy,proxy_error),"validate HTTP proxy"); auto broken=proxy; broken.type=-1; SetCurrentProxy(broken); http::Request fail_closed; fail_closed.url=L"http://127.0.0.1:1/"; Check(transport->Open(fail_closed).kind==http::OpenError::kInvalidRequest,"invalid saved proxy fails closed"); SetCurrentProxy(proxy); http::Request proxied; proxied.url=L"http://proxy-only.invalid/file"; auto through=transport->Open(proxied); Check(through.stream && Drain(*through.stream)=="proxied-payload","HTTP authenticated proxy without local target DNS"); http::Request ftp_proxy; ftp_proxy.url=base+L"/file.bin"; auto ftp_through=transport->Open(ftp_proxy); Check(ftp_through.stream && Drain(*ftp_through.stream)==data,"FTP control and data through authenticated HTTP CONNECT proxy"); auto wrong_password=proxy; wrong_password.password=L"wrong"; SetCurrentProxy(wrong_password); auto refused=transport->Open(proxied); Check(refused.stream && refused.stream->Headers().status==407,"HTTP proxy authentication failure is not bypassed"); SetCurrentProxy(proxy); proxied.range_offset=4; through=transport->Open(proxied); Check(through.stream && through.stream->Headers().status==206 && Drain(*through.stream)=="ied-payload","proxy HTTP resume"); proxied.range_offset=0; proxied.url=std::wstring(argv[5])+L"/trackers.txt"; Check(!transport->Open(proxied).stream,"HTTPS via CONNECT rejects untrusted certificate"); proxy.type=2; proxy.port=argv[4]; SetCurrentProxy(proxy); http::Request socks_request; socks_request.url=std::wstring(argv[2])+L"/trackers.txt"; socks_request.url.replace(7,9,L"proxy-only.invalid"); wrong_password=proxy; wrong_password.password=L"wrong"; SetCurrentProxy(wrong_password); Check(!transport->Open(socks_request).stream,"SOCKS5 authentication failure is not bypassed"); SetCurrentProxy(proxy); auto socks_response=transport->Open(socks_request); Check(socks_response.stream && !Drain(*socks_response.stream).empty(),"SOCKS5 authentication and remote DNS"); ftp_through=transport->Open(ftp_proxy); Check(ftp_through.stream && Drain(*ftp_through.stream)==data,"FTP through authenticated SOCKS5 proxy"); SetCurrentProxy({}); std::wstring name,identity; Check(!ParseMagnet(L"magnet:?xt=urn:btih:invalid",name,identity),"reject malformed info hash"); Check(IsLocalDownloadLink(L"ftp://127.0.0.1/file") && IsLocalDownloadLink(L"magnet:?xt=urn:btih:0123456789012345678901234567890123456789"),"local startup accepts FTP and magnet schemes"); auto root=std::filesystem::temp_directory_path()/(L"TTDownloader_protocol_test_"+std::to_wstring(GetCurrentProcessId())); std::filesystem::create_directories(root/L"seed"); std::filesystem::create_directories(root/L"download"); const std::string payload(2*1024*1024,'T'); { std::ofstream out(root/L"seed"/L"payload.bin",std::ios::binary); out.write(payload.data(),payload.size()); } lt::file_storage files; files.add_file("payload.bin",payload.size()); lt::create_torrent creator(files,16*1024); lt::error_code ec; lt::set_piece_hashes(creator,platform::ToUtf8((root/L"seed").wstring()),ec); Check(!ec,"hash local seed"); auto metadata=std::make_shared(creator.generate()); lt::settings_pack settings; settings.set_bool(lt::settings_pack::enable_dht,false); settings.set_bool(lt::settings_pack::enable_lsd,false); settings.set_bool(lt::settings_pack::enable_upnp,false); settings.set_bool(lt::settings_pack::enable_natpmp,false); settings.set_str(lt::settings_pack::listen_interfaces,"127.0.0.1:0"); settings.set_int(lt::settings_pack::upload_rate_limit,512*1024); { lt::session seeder(settings); lt::add_torrent_params params; params.ti=metadata; params.save_path=platform::ToUtf8((root/L"seed").wstring()); params.flags|=lt::torrent_flags::seed_mode; params.flags&=~lt::torrent_flags::auto_managed; params.flags&=~lt::torrent_flags::paused; auto handle=seeder.add_torrent(params,ec); Check(!ec,"start local seed"); auto deadline=GetTickCount64()+10000; while(!seeder.listen_port() && GetTickCount64()Open(register_seed); Check(registered.stream && Drain(*registered.stream)=="OK","register local tracker peer"); auto magnet=platform::FromUtf8(lt::make_magnet_uri(*metadata)); Check(ParseMagnet(magnet,name,identity),"parse valid magnet"); { TorrentTransfer tls(magnet,(root/L"tls").wstring(),(root/L"tls.resume").wstring(),true,{std::wstring(argv[5])+L"/announce"}); bool rejected=false; std::wstring tls_diagnostic; auto until=GetTickCount64()+20000; while(GetTickCount64()0) { Check(transfer.Save(false),"checkpoint active torrent without pausing"); checkpoint=true; proxy.type=2; proxy.port=argv[4]; SetCurrentProxy(proxy); transfer.RefreshProxy(); } if(state.complete) { finished=true; break; } Sleep(100); } if(!finished) throw std::runtime_error("metadata stalled: "+platform::ToUtf8(last_diagnostic)); Check(checkpoint,"periodic metadata checkpoint was exercised"); Check(finished,"magnet retrieves metadata and downloads from loopback peer"); Check(transfer.Save(),"save torrent resume metadata"); transfer.SetTrackers({}); Check(transfer.Poll().trackers==0,"remove global trackers from live transfer"); } TorrentTransfer resumed(magnet,(root/L"download").wstring(),(root/L"state.resume").wstring(),true); Check(resumed.Poll().trackers==0,"old global trackers do not return from resume data"); bool complete=false; deadline=GetTickCount64()+15000; while(GetTickCount64()(input)),{}); Check(received==payload,"torrent bytes match verified local seed"); input.close(); std::filesystem::remove_all(root); std::cout<<"PASS: local FTP full/resume/restart and real magnet metadata, payload verification and recovery\n"; return 0; } catch(const std::exception& error) { std::cerr<<"FAIL: "<