#![allow(clippy::collapsible_if)]
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tracing::{info, Level};
use tracing_subscriber::EnvFilter;
use torrentdht::{
build_integrity_image_async, format_status_table, load_signing_key, scan_download_dir,
sidecar_root_for_config, torrent_to_magnet, validate_integrity_image, Client, Config,
ContentLayout, IntegrityConfig, PeerDiscoveryMode, Session, TorrentBuilder, TorrentFile,
};
struct SessionOptions {
config_path: PathBuf,
dht_only: bool,
tracker_only: bool,
static_peers: Vec<SocketAddr>,
download_files: Vec<String>,
}
impl SessionOptions {
fn parse(args: &[String], require_target: bool, target_label: &str) -> torrentdht::Result<(Self, Option<String>)> {
let mut config_path = PathBuf::from("config/default.kdl");
let mut target = None;
let mut dht_only = false;
let mut tracker_only = false;
let mut static_peers = Vec::new();
let mut download_files = Vec::new();
let mut idx = 0;
while idx < args.len() {
match args[idx].as_str() {
"-c" | "--config" => {
idx += 1;
config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
}
"--dht-only" => dht_only = true,
"--tracker-only" => tracker_only = true,
"--peer" => {
idx += 1;
let addr = args
.get(idx)
.ok_or_else(missing("peer address"))?
.parse::<SocketAddr>()
.map_err(|_| {
torrentdht::Error::Session(
"peer address must be host:port".into(),
)
})?;
static_peers.push(addr);
}
"--files" => {
idx += 1;
download_files.push(
args.get(idx)
.ok_or_else(missing("file pattern"))?
.to_string(),
);
}
value if value.starts_with('-') => {
return Err(torrentdht::Error::Session(format!(
"unknown flag: {value}"
)));
}
value => {
if target.is_some() {
return Err(torrentdht::Error::Session(format!(
"{target_label} accepts a single target"
)));
}
target = Some(value.to_string());
}
}
idx += 1;
}
if require_target && target.is_none() {
return Err(torrentdht::Error::Session(format!(
"{target_label} requires a target"
)));
}
Ok((
Self {
config_path,
dht_only,
tracker_only,
static_peers,
download_files,
},
target,
))
}
fn apply_to_config(&self, cfg: &mut Config) -> torrentdht::Result<()> {
if self.dht_only && self.tracker_only {
return Err(torrentdht::Error::Config(
"cannot use --dht-only and --tracker-only together".into(),
));
}
if self.dht_only {
cfg.peer_discovery = PeerDiscoveryMode::Dht;
cfg.dht_enabled = true;
} else if self.tracker_only {
cfg.peer_discovery = PeerDiscoveryMode::Tracker;
cfg.dht_enabled = false;
}
Ok(())
}
}
async fn load_torrent_file(data: &[u8], cfg: &Config) -> torrentdht::Result<TorrentFile> {
let torrent = TorrentFile::parse(data)?;
torrentdht::ensure_torrent_trusted(cfg, &torrent)?;
Ok(torrent)
}
async fn cmd_daemon(args: &[String]) -> torrentdht::Result<()> {
let mut config_path = PathBuf::from("config/default.kdl");
let mut idx = 0;
while idx < args.len() {
match args[idx].as_str() {
"-c" | "--config" => {
idx += 1;
config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
}
value if value.starts_with('-') => {
return Err(torrentdht::Error::Session(format!(
"unknown flag: {value}"
)));
}
_ => {
return Err(torrentdht::Error::Session(
"daemon accepts only -c/--config".into(),
));
}
}
idx += 1;
}
let cfg = Config::from_kdl_file(&config_path)?;
let client = Client::open(cfg).await?;
if client.config().rpc_enabled {
info!(
listen = client.config().rpc_listen.as_deref().unwrap_or(""),
"daemon running with RPC (auth <token> then status|progress|add_torrent|add_magnet|stop|remove|ping)"
);
} else {
info!("daemon running (secure client held open until ctrl-c; RPC off)");
}
tokio::signal::ctrl_c().await.map_err(|err| {
torrentdht::Error::Session(format!("ctrl-c handler failed: {err}"))
})?;
client.persist_dht().await?;
info!("daemon stopped");
Ok(())
}
async fn cmd_run(args: &[String]) -> torrentdht::Result<()> {
let mut config_path = PathBuf::from("config/default.kdl");
let mut dht_only = false;
let mut tracker_only = false;
let mut targets = Vec::new();
let mut idx = 0;
while idx < args.len() {
match args[idx].as_str() {
"-c" | "--config" => {
idx += 1;
config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
}
"--dht-only" => dht_only = true,
"--tracker-only" => tracker_only = true,
value if value.starts_with('-') => {
return Err(torrentdht::Error::Session(format!(
"unknown flag: {value}"
)));
}
value => targets.push(value.to_string()),
}
idx += 1;
}
if targets.is_empty() {
return Err(torrentdht::Error::Session(
"run requires one or more torrent files or magnet URIs".into(),
));
}
let mut cfg = Config::from_kdl_file(&config_path)?;
let opts = SessionOptions {
config_path,
dht_only,
tracker_only,
static_peers: Vec::new(),
download_files: Vec::new(),
};
opts.apply_to_config(&mut cfg)?;
let client = Client::open(cfg).await?;
let progress_client = Arc::clone(&client);
let progress_task = tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(15));
interval.tick().await;
loop {
interval.tick().await;
let sessions = progress_client.sessions().await;
if sessions.is_empty() {
continue;
}
let mut all_done = true;
for session in &sessions {
let complete = session.picker().read().await.complete_count() as u32;
let total = session.info().piece_count();
info!(
name = %session.info().name,
hash = %session.info_hash().to_hex(),
complete,
total,
"run progress"
);
if complete < total {
all_done = false;
}
}
if all_done {
break;
}
}
});
let mut handles = Vec::new();
for target in targets {
let session = if target.starts_with("magnet:?") {
let magnet = torrentdht::parse_magnet(&target)?;
info!(hash = %magnet.info_hash.to_hex(), "loaded magnet");
client.add_magnet(magnet).await?
} else {
let torrent_data = tokio::fs::read(&target).await?;
let torrent = load_torrent_file(&torrent_data, client.config()).await?;
info!(name = %torrent.info.name, hash = %torrent.info.info_hash.to_hex(), "loaded torrent");
client.add_torrent(torrent).await?
};
let worker = Arc::clone(&session);
handles.push(tokio::spawn(async move {
let name = worker.info().name.clone();
match worker.run().await {
Ok(progress) => info!(
name,
pieces = progress.pieces_complete,
total = progress.piece_count,
"download complete"
),
Err(err) => tracing::error!(%err, name, "download failed"),
}
}));
}
for handle in handles {
let _ = handle.await;
}
progress_task.abort();
Ok(())
}
async fn cmd_status(args: &[String]) -> torrentdht::Result<()> {
let mut config_path = PathBuf::from("config/default.kdl");
let mut idx = 0;
while idx < args.len() {
match args[idx].as_str() {
"-c" | "--config" => {
idx += 1;
config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
}
value if value.starts_with('-') => {
return Err(torrentdht::Error::Session(format!(
"unknown flag: {value}"
)));
}
_ => {
return Err(torrentdht::Error::Session(
"status accepts only -c/--config".into(),
));
}
}
idx += 1;
}
let cfg = Config::from_kdl_file(&config_path)?;
let rows = scan_download_dir(&cfg).await?;
println!("{}", format_status_table(&rows));
Ok(())
}
#[tokio::main]
async fn main() -> torrentdht::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env().add_directive(Level::INFO.into()))
.init();
let args: Vec<String> = std::env::args().skip(1).collect();
if args.is_empty() {
print_usage();
return Ok(());
}
match args[0].as_str() {
"create" => cmd_create(&args[1..]).await,
"verify" => cmd_verify(&args[1..]).await,
"download" => cmd_download(&args[1..]).await,
"run" => cmd_run(&args[1..]).await,
"daemon" => cmd_daemon(&args[1..]).await,
"status" => cmd_status(&args[1..]).await,
"seed" => cmd_seed(&args[1..]).await,
"magnet" => cmd_magnet(&args[1..]).await,
"env-check" => cmd_env_check(),
"help" | "--help" | "-h" => {
print_usage();
Ok(())
}
_ => {
print_usage();
Err(torrentdht::Error::Session(
"unknown command; use `torrentdht download --config <file.kdl> <torrent|magnet>` (legacy `torrentdht <config.kdl> <torrent>` is removed)"
.into(),
))
}
}
}
async fn cmd_create(args: &[String]) -> torrentdht::Result<()> {
let mut config_path = PathBuf::from("config/default.kdl");
let mut output = None;
let mut announce = None;
let mut piece_length = None;
let mut name = None;
let mut sign_key = None;
let mut no_integrity_image = false;
let mut v2_hybrid = false;
let mut v2_only = false;
let mut input = None;
let mut idx = 0;
while idx < args.len() {
match args[idx].as_str() {
"-c" | "--config" => {
idx += 1;
config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
}
"-o" | "--output" => {
idx += 1;
output = Some(PathBuf::from(args.get(idx).ok_or_else(missing("output path"))?));
}
"--announce" => {
idx += 1;
announce = Some(args.get(idx).ok_or_else(missing("announce url"))?.clone());
}
"--piece-length" => {
idx += 1;
piece_length = Some(
args.get(idx)
.ok_or_else(missing("piece length"))?
.parse::<u32>()
.map_err(|_| torrentdht::Error::Torrent("invalid piece length".into()))?,
);
}
"--name" => {
idx += 1;
name = Some(args.get(idx).ok_or_else(missing("name"))?.clone());
}
"--sign-key" => {
idx += 1;
sign_key = Some(PathBuf::from(
args.get(idx).ok_or_else(missing("signing key path"))?,
));
}
"--no-integrity-image" => no_integrity_image = true,
"--v2" => v2_hybrid = true,
"--v2-only" => v2_only = true,
value if value.starts_with('-') => {
return Err(torrentdht::Error::Session(format!(
"unknown flag: {value}"
)));
}
value => {
if input.is_some() {
return Err(torrentdht::Error::Session(
"create accepts a single input path".into(),
));
}
input = Some(PathBuf::from(value));
}
}
idx += 1;
}
if v2_hybrid && v2_only {
return Err(torrentdht::Error::Session(
"create: use only one of --v2 (hybrid) or --v2-only".into(),
));
}
let input = input.ok_or_else(|| torrentdht::Error::Session("create requires input path".into()))?;
let cfg = Config::from_kdl_file(&config_path)?;
let mut builder = TorrentBuilder::new(&input);
if let Some(url) = announce {
builder = builder.announce(url);
}
if let Some(len) = piece_length {
builder = builder.piece_length(len);
}
if let Some(display) = name {
builder = builder.name(display);
}
if let Some(path) = sign_key {
builder = builder.signing_key(load_signing_key(&path)?);
} else if cfg.integrity_sign_torrents {
if let Some(path) = &cfg.integrity_signing_key_file {
builder = builder.signing_key(load_signing_key(path)?);
}
}
if v2_hybrid {
builder = builder.v2_hybrid(true);
}
if v2_only {
builder = builder.v2_only(true);
}
let torrent = builder.build().await?;
let output = output.unwrap_or_else(|| {
PathBuf::from(format!("{}.torrent", torrent.info.name.replace('/', "_")))
});
torrent.write_to(&output).await?;
if cfg.integrity_create_image && !no_integrity_image {
let layout =
ContentLayout::from_path(&input, Some(torrent.info.name.clone()))?;
let integrity =
IntegrityConfig::from_app_config(&cfg, torrent.info.info_hash.as_bytes())?;
let sidecar_root = sidecar_root_for_config(&cfg, &torrent.info);
let report = build_integrity_image_async(
&layout,
&torrent.info,
&sidecar_root,
cfg.block_size,
&integrity,
)
.await?;
info!(
sidecar = %sidecar_root.display(),
pieces = report.pieces_sha1_ok,
blocks = report.blocks_crc_ok,
parity = report.parity_ok,
valid = report.is_valid(),
"created integrity image"
);
if !report.is_valid() {
return Err(torrentdht::Error::Integrity(
"integrity image build reported errors".into(),
));
}
}
info!(
path = %output.display(),
hash = %torrent.info.info_hash.to_hex(),
signed = torrent.signature.is_some(),
magnet = %torrent_to_magnet(&torrent),
"created torrent"
);
Ok(())
}
async fn cmd_verify(args: &[String]) -> torrentdht::Result<()> {
let mut config_path = PathBuf::from("config/default.kdl");
let mut torrent_path = None;
let mut content_path = None;
let mut sidecar_root = None;
let mut idx = 0;
while idx < args.len() {
match args[idx].as_str() {
"-c" | "--config" => {
idx += 1;
config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
}
"--content" => {
idx += 1;
content_path = Some(PathBuf::from(
args.get(idx).ok_or_else(missing("content path"))?,
));
}
"--sidecar-root" => {
idx += 1;
sidecar_root = Some(PathBuf::from(
args.get(idx).ok_or_else(missing("sidecar root"))?,
));
}
value if value.starts_with('-') => {
return Err(torrentdht::Error::Session(format!(
"unknown flag: {value}"
)));
}
value => {
if torrent_path.is_some() {
return Err(torrentdht::Error::Session(
"verify accepts a single torrent file".into(),
));
}
torrent_path = Some(PathBuf::from(value));
}
}
idx += 1;
}
let torrent_path = torrent_path
.ok_or_else(|| torrentdht::Error::Session("verify requires a .torrent file".into()))?;
let cfg = Config::from_kdl_file(&config_path)?;
let torrent_data = tokio::fs::read(&torrent_path).await?;
let torrent = load_torrent_file(&torrent_data, &cfg).await?;
let layout_paths = cfg.torrent_layout(&torrent.info.info_hash.to_hex());
let sidecar_root = sidecar_root.unwrap_or_else(|| layout_paths.state_root.clone());
let layout = if let Some(content) = content_path {
ContentLayout::from_path(content, Some(torrent.info.name.clone()))?
} else {
ContentLayout::from_torrent_at(&layout_paths.content_root, &torrent.info)?
};
let integrity = IntegrityConfig::from_app_config(&cfg, torrent.info.info_hash.as_bytes())?;
let report = validate_integrity_image(
&layout,
&torrent.info,
&sidecar_root,
cfg.block_size,
&integrity,
)
.await?;
info!(
hash = %torrent.info.info_hash.to_hex(),
pieces = report.pieces_sha1_ok,
piece_total = report.piece_count,
blocks = report.blocks_crc_ok,
block_total = report.block_count,
parity = report.parity_ok,
parity_total = report.parity_count,
valid = report.is_valid(),
errors = report.errors.len(),
"integrity verification"
);
if !report.is_valid() {
for err in &report.errors {
tracing::error!(%err, "integrity error");
}
return Err(torrentdht::Error::Integrity(
"content failed integrity verification".into(),
));
}
Ok(())
}
async fn cmd_download(args: &[String]) -> torrentdht::Result<()> {
let (opts, target) = SessionOptions::parse(
args,
true,
"download requires torrent file or magnet URI",
)?;
cmd_download_target(&opts, &target.expect("target checked")).await
}
async fn cmd_seed(args: &[String]) -> torrentdht::Result<()> {
let (opts, target) = SessionOptions::parse(args, true, "seed requires a .torrent file")?;
let target = target.expect("target checked");
let mut cfg = Config::from_kdl_file(&opts.config_path)?;
opts.apply_to_config(&mut cfg)?;
let torrent_data = tokio::fs::read(&target).await?;
let torrent = load_torrent_file(&torrent_data, &cfg).await?;
info!(name = %torrent.info.name, hash = %torrent.info.info_hash.to_hex(), "loaded torrent for seeding");
let session = Session::from_torrent(cfg, torrent).await?;
session.add_static_peers(opts.static_peers).await;
session.seed().await
}
async fn cmd_download_target(opts: &SessionOptions, target: &str) -> torrentdht::Result<()> {
let mut cfg = Config::from_kdl_file(&opts.config_path)?;
opts.apply_to_config(&mut cfg)?;
cfg.download_files = opts.download_files.clone();
let session = if target.starts_with("magnet:?") {
let magnet = torrentdht::parse_magnet(target)?;
info!(hash = %magnet.info_hash.to_hex(), "loaded magnet link");
let session = Session::from_magnet(cfg, magnet).await?;
session.add_static_peers(opts.static_peers.clone()).await;
session
} else {
let torrent_data = tokio::fs::read(target).await?;
let torrent = load_torrent_file(&torrent_data, &cfg).await?;
info!(name = %torrent.info.name, hash = %torrent.info.info_hash.to_hex(), "loaded torrent");
let session = Session::from_torrent(cfg, torrent).await?;
session.add_static_peers(opts.static_peers.clone()).await;
session.bootstrap_dht().await?;
session
};
let progress = session.download().await?;
info!(
pieces = progress.pieces_complete,
total = progress.piece_count,
bytes = progress.bytes_downloaded,
"download complete"
);
Ok(())
}
async fn cmd_magnet(args: &[String]) -> torrentdht::Result<()> {
let mut config_path = PathBuf::from("config/default.kdl");
let mut torrent_path = None;
let mut idx = 0;
while idx < args.len() {
match args[idx].as_str() {
"-c" | "--config" => {
idx += 1;
config_path = PathBuf::from(args.get(idx).ok_or_else(missing("config path"))?);
}
value if value.starts_with('-') => {
return Err(torrentdht::Error::Session(format!(
"unknown flag: {value}"
)));
}
value => {
if torrent_path.is_some() {
return Err(torrentdht::Error::Session(
"magnet accepts a single torrent file".into(),
));
}
torrent_path = Some(PathBuf::from(value));
}
}
idx += 1;
}
let torrent_path = torrent_path
.ok_or_else(|| torrentdht::Error::Session("magnet requires a .torrent file".into()))?;
let cfg = Config::from_kdl_file(&config_path)?;
let torrent_data = tokio::fs::read(&torrent_path).await?;
let torrent = load_torrent_file(&torrent_data, &cfg).await?;
println!("{}", torrent_to_magnet(&torrent));
Ok(())
}
fn cmd_env_check() -> torrentdht::Result<()> {
torrentdht::SecureEnv::check_required()?;
println!("secure-session environment OK");
println!(
"network id present; remember NETWORK_ID is capability-bearing (SHA-1 announced on public DHT)"
);
Ok(())
}
fn print_usage() {
eprintln!(
"torrentdht — pure Rust BitTorrent client\n\
\n\
Usage:\n\
torrentdht create [options] <input-path>\n\
torrentdht verify [options] <file.torrent>\n\
torrentdht download [options] <file.torrent|magnet:?...>\n\
torrentdht run [options] <torrent...> Download multiple torrents in one client\n\
torrentdht daemon [options] Long-running secure client (optional RPC)\n\
torrentdht status [options] List download-dir resume state\n\
torrentdht seed [options] <file.torrent>\n\
torrentdht magnet <file.torrent>\n\
torrentdht env-check Validate TORRENTDHT_* TLS/network env\n\
\n\
Secure session (required for download/seed/run/daemon):\n\
TORRENTDHT_CA_CERT=/path/to/ca.pem\n\
TORRENTDHT_CERT=/path/to/node.pem\n\
TORRENTDHT_KEY=/path/to/node-key.pem\n\
TORRENTDHT_NETWORK_ID=<high-entropy private network name>\n\
TORRENTDHT_HANDSHAKE_KEY=<shared secret for this network>\n\
Optional: TORRENTDHT_PEER_STORE, TORRENTDHT_LISTEN_ADDR\n\
Note: NETWORK_ID is capability-bearing (SHA-1 announced on public DHT).\n\
Membership is network-wide across torrents on this Client.\n\
\n\
Create options:\n\
-c, --config <kdl> Config file (default: config/default.kdl)\n\
-o, --output <path> Output .torrent path\n\
--announce <url> Tracker announce URL\n\
--piece-length <bytes> Piece size (default: 262144)\n\
--name <name> Torrent display name override\n\
--sign-key <path> Ed25519 signing key (32-byte seed file)\n\
--no-integrity-image Skip ECC manifest + parity sidecar generation\n\
--v2 Create hybrid BEP 52 torrent (v1 SHA1 + v2 file tree)\n\
--v2-only Create pure BEP 52 v2 torrent (btmh magnets; no v1 pieces)\n\
\n\
Verify options:\n\
-c, --config <kdl> Config file (default: config/default.kdl)\n\
--content <path> Content root (default: download-dir/info-hash)\n\
--sidecar-root <path> Sidecar root (default: state-dir/torrents/hash or download-dir/hash)\n\
\n\
Download/seed options:\n\
-c, --config <kdl> Config file (default: config/default.kdl)\n\
--dht-only Discover peers via DHT only\n\
--tracker-only Discover peers via tracker(s) only\n\
--peer <host:port> Static peer (repeatable)\n\
--files <pattern> Selective download file pattern (repeatable)\n"
);
}
fn missing(label: &'static str) -> impl FnOnce() -> torrentdht::Error {
move || torrentdht::Error::Session(format!("missing {label}"))
}