use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::Semaphore;
use zeroize::Zeroizing;
use crate::client::Client;
use crate::config::Config;
use crate::error::{Error, Result};
use crate::torrent::{parse_magnet, TorrentFile};
pub const MAX_RPC_LINE: usize = 16 * 1024;
const MAX_RPC_CONNECTIONS: usize = 8;
const RPC_READ_TIMEOUT: Duration = Duration::from_secs(30);
const RPC_MAX_REQ_PER_SEC: u32 = 30;
const RPC_READ_CHUNK: usize = 512;
pub fn validate_rpc_config(cfg: &Config) -> Result<()> {
if !cfg.rpc_enabled {
return Ok(());
}
let listen = cfg.rpc_listen.as_deref().ok_or_else(|| {
Error::Config("rpc-enabled requires rpc-listen (e.g. \"127.0.0.1:7600\")".into())
})?;
let token = rpc_token(cfg).ok_or_else(|| {
Error::Config(
"rpc-enabled requires rpc-auth-token or env TORRENTDHT_RPC_TOKEN".into(),
)
})?;
if token.len() < 32 {
return Err(Error::Config(
"rpc auth token must be at least 32 characters for commercial use".into(),
));
}
let addr: SocketAddr = listen
.parse()
.map_err(|err| Error::Config(format!("invalid rpc-listen {listen}: {err}")))?;
if !cfg.rpc_allow_non_loopback && !addr.ip().is_loopback() {
return Err(Error::Config(format!(
"rpc-listen {listen} is not loopback; set rpc-allow-non-loopback #true to permit"
)));
}
Ok(())
}
fn rpc_token(cfg: &Config) -> Option<Zeroizing<String>> {
cfg.rpc_auth_token
.clone()
.or_else(|| std::env::var("TORRENTDHT_RPC_TOKEN").ok().map(Zeroizing::new))
}
fn torrent_jail(cfg: &Config) -> PathBuf {
cfg.rpc_torrent_root
.clone()
.unwrap_or_else(|| cfg.download_dir.clone())
}
pub async fn serve(client: Arc<Client>) -> Result<()> {
validate_rpc_config(client.config())?;
let listen = client
.config()
.rpc_listen
.as_deref()
.expect("validated");
let expected_token = rpc_token(client.config()).expect("validated");
let allow_non_loopback = client.config().rpc_allow_non_loopback;
let jail = torrent_jail(client.config());
let listener = TcpListener::bind(listen)
.await
.map_err(|err| Error::Session(format!("rpc bind {listen}: {err}")))?;
tracing::info!(listen, "rpc server listening (auth required)");
let sessions = Arc::new(Semaphore::new(MAX_RPC_CONNECTIONS));
loop {
let (stream, peer) = listener.accept().await.map_err(Error::from)?;
if !allow_non_loopback && !is_loopback_peer(peer.ip()) {
tracing::warn!(%peer, "rpc rejected non-loopback peer");
continue;
}
let Ok(permit) = sessions.clone().try_acquire_owned() else {
tracing::warn!(%peer, "rpc connection limit reached");
continue;
};
let client = Arc::clone(&client);
let expected_token = expected_token.clone();
let jail = jail.clone();
tokio::spawn(async move {
let _permit = permit;
if let Err(err) = handle_connection(client, stream, &expected_token, &jail).await {
tracing::debug!(%err, "rpc connection ended");
}
});
}
}
fn is_loopback_peer(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => v4.is_loopback(),
IpAddr::V6(v6) => v6.is_loopback() || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback()),
}
}
struct ConnRateLimit {
window_start: Instant,
count: u32,
}
impl ConnRateLimit {
fn new() -> Self {
Self {
window_start: Instant::now(),
count: 0,
}
}
fn allow(&mut self) -> bool {
let now = Instant::now();
if now.duration_since(self.window_start) >= Duration::from_secs(1) {
self.window_start = now;
self.count = 0;
}
if self.count >= RPC_MAX_REQ_PER_SEC {
return false;
}
self.count = self.count.saturating_add(1);
true
}
}
async fn handle_connection(
client: Arc<Client>,
stream: TcpStream,
expected_token: &str,
jail: &Path,
) -> Result<()> {
let (mut reader, mut writer) = stream.into_split();
let mut authed = false;
let mut line_buf = Vec::with_capacity(256);
let mut carry = Vec::new();
let rate = Arc::new(Mutex::new(ConnRateLimit::new()));
loop {
line_buf.clear();
let line = match read_rpc_line(&mut reader, &mut line_buf, &mut carry).await {
Ok(Some(line)) => line,
Ok(None) => return Ok(()),
Err(err) => {
let body = json_error(&err.to_string());
let _ = writer.write_all(body.as_bytes()).await;
let _ = writer.write_all(b"\n").await;
return Ok(());
}
};
let line = line.trim();
if line.is_empty() {
continue;
}
let response = if !authed {
match auth_line(line, expected_token) {
Ok(()) => {
authed = true;
json_ok_auth()
}
Err(msg) => {
let body = json_error(&msg);
writer.write_all(body.as_bytes()).await?;
writer.write_all(b"\n").await?;
return Ok(());
}
}
} else {
let allowed = rate
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.allow();
if !allowed {
json_error("rate limited")
} else {
dispatch(&client, line, jail).await
}
};
writer.write_all(response.as_bytes()).await?;
writer.write_all(b"\n").await?;
}
}
async fn read_rpc_line<R: AsyncReadExt + Unpin>(
reader: &mut R,
buf: &mut Vec<u8>,
carry: &mut Vec<u8>,
) -> Result<Option<String>> {
let read = tokio::time::timeout(RPC_READ_TIMEOUT, async {
loop {
if let Some(pos) = carry.iter().position(|&b| b == b'\n') {
let line_bytes = &carry[..pos];
for &b in line_bytes {
if b == b'\r' {
continue;
}
if buf.len() >= MAX_RPC_LINE {
return Err(Error::Session(format!(
"rpc line exceeds {MAX_RPC_LINE} bytes"
)));
}
buf.push(b);
}
let rest = carry[pos + 1..].to_vec();
*carry = rest;
break;
}
if buf.len().saturating_add(carry.len()) > MAX_RPC_LINE {
return Err(Error::Session(format!(
"rpc line exceeds {MAX_RPC_LINE} bytes"
)));
}
let mut chunk = [0u8; RPC_READ_CHUNK];
let n = reader.read(&mut chunk).await?;
if n == 0 {
if carry.is_empty() && buf.is_empty() {
return Ok::<Option<String>, Error>(None);
}
for &b in carry.iter() {
if b == b'\r' {
continue;
}
if buf.len() >= MAX_RPC_LINE {
return Err(Error::Session(format!(
"rpc line exceeds {MAX_RPC_LINE} bytes"
)));
}
buf.push(b);
}
carry.clear();
break;
}
carry.extend_from_slice(&chunk[..n]);
}
let line = std::str::from_utf8(buf)
.map_err(|_| Error::Session("rpc line is not valid utf-8".into()))?
.to_string();
Ok(Some(line))
})
.await
.map_err(|_| Error::Session("rpc read timed out".into()))??;
Ok(read)
}
fn auth_line(line: &str, expected: &str) -> std::result::Result<(), String> {
let mut parts = line.split_whitespace();
let method = parts.next().unwrap_or("");
if !method.eq_ignore_ascii_case("auth") {
return Err("authenticate first with: auth <token>".into());
}
let Some(token) = parts.next() else {
return Err("auth requires a token".into());
};
if !token_eq_constant_time(token.as_bytes(), expected.as_bytes()) {
return Err("auth failed".into());
}
if parts.next().is_some() {
return Err("auth takes a single token".into());
}
Ok(())
}
fn token_eq_constant_time(provided: &[u8], expected: &[u8]) -> bool {
use sha2::{Digest, Sha256};
let a = Sha256::digest(provided);
let b = Sha256::digest(expected);
let mut diff = 0u8;
for (x, y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
diff == 0
}
async fn dispatch(client: &Arc<Client>, line: &str, jail: &Path) -> String {
let mut parts = line.split_whitespace();
let Some(method) = parts.next() else {
return json_error("empty request");
};
match method {
"status" | "list_sessions" => json_status(client).await,
"progress" => {
let Some(hex) = parts.next() else {
return json_error("progress requires an info-hash hex");
};
json_progress(client, hex).await
}
"add_torrent" => {
let Some(path) = parts.next() else {
return json_error("add_torrent requires a path");
};
json_add_torrent(client, path, jail).await
}
"add_magnet" => {
let Some(uri) = parts.next() else {
return json_error("add_magnet requires a magnet URI");
};
let rest = if parts.clone().next().is_some() {
let start = line.find(uri).unwrap_or(0);
line[start..].to_string()
} else {
uri.to_string()
};
if rest.len() > MAX_RPC_LINE {
return json_error("magnet URI too long");
}
json_add_magnet(client, &rest).await
}
"stop" => {
let Some(hex) = parts.next() else {
return json_error("stop requires an info-hash hex");
};
json_stop(client, hex).await
}
"remove" => {
let Some(hex) = parts.next() else {
return json_error("remove requires an info-hash hex");
};
json_remove(client, hex).await
}
"ping" => "{\"ok\":true,\"pong\":true}".into(),
other => json_error(&format!("unknown method: {other}")),
}
}
async fn json_status(client: &Arc<Client>) -> String {
let sessions = client.sessions().await;
let mut rows = String::new();
for (idx, session) in sessions.iter().enumerate() {
if idx > 0 {
rows.push(',');
}
let progress = session.current_progress().await;
let scrape = session
.scrape_stats()
.map(|s| {
format!(
"{{\"complete\":{},\"incomplete\":{},\"downloaded\":{}}}",
s.complete, s.incomplete, s.downloaded
)
})
.unwrap_or_else(|| "null".into());
let layout = session.layout();
rows.push_str(&format!(
"{{\"name\":{},\"info_hash\":{},\"pieces_complete\":{},\"piece_count\":{},\
\"bytes_downloaded\":{},\"content_path\":{},\"state_path\":{},\"checkpoint_path\":{},\"scrape\":{}}}",
json_str(&session.info().name),
json_str(&session.info_hash().to_hex()),
progress.pieces_complete,
progress.piece_count,
progress.bytes_downloaded,
json_str(&layout.content_root.display().to_string()),
json_str(&layout.state_root.display().to_string()),
json_str(&session.checkpoint_path().display().to_string()),
scrape,
));
}
let on_disk = match crate::ops::scan_download_dir(client.config()).await {
Ok(disk_rows) => {
let mut out = String::new();
for (idx, row) in disk_rows.iter().enumerate() {
if idx > 0 {
out.push(',');
}
out.push_str(&format!(
"{{\"info_hash\":{},\"pieces_complete\":{},\"bytes_downloaded\":{},\
\"has_checkpoint\":{},\"content_path\":{},\"state_path\":{}}}",
json_str(&row.info_hash_hex),
row.pieces_complete,
row.bytes_downloaded,
if row.has_checkpoint { "true" } else { "false" },
json_str(&row.path.display().to_string()),
json_str(&row.state_path.display().to_string()),
));
}
out
}
Err(err) => {
tracing::debug!(%err, "rpc status on-disk scan skipped");
String::new()
}
};
let cfg = client.config();
let state_dir = cfg
.state_dir
.as_ref()
.map(|p| json_str(&p.display().to_string()))
.unwrap_or_else(|| "null".into());
format!(
"{{\"ok\":true,\"listen_port\":{},\"download_dir\":{},\"state_dir\":{},\
\"sessions\":[{}],\"on_disk\":[{}]}}",
cfg.listen_port,
json_str(&cfg.download_dir.display().to_string()),
state_dir,
rows,
on_disk,
)
}
async fn json_progress(client: &Arc<Client>, info_hash_hex: &str) -> String {
let Ok(hash) = crate::torrent::InfoHash::from_hex(info_hash_hex) else {
return json_error("invalid info-hash hex");
};
let Some(session) = client.session(hash).await else {
return json_error("session not found");
};
let progress = session.current_progress().await;
format!(
"{{\"ok\":true,\"info_hash\":{},\"pieces_complete\":{},\"piece_count\":{},\"bytes_downloaded\":{}}}",
json_str(&session.info_hash().to_hex()),
progress.pieces_complete,
progress.piece_count,
progress.bytes_downloaded,
)
}
async fn json_add_torrent(client: &Arc<Client>, path: &str, jail: &Path) -> String {
let relative = match jail_relative_path(jail, path) {
Ok(p) => p,
Err(err) => return json_error(&err),
};
let jail = jail.to_path_buf();
let relative_clone = relative.clone();
let max = crate::security::MAX_TORRENT_FILE_BYTES;
let data = match tokio::task::spawn_blocking(move || {
crate::security::read_bytes_under_root_capped(&jail, &relative_clone, max)
})
.await
{
Ok(Ok(data)) => data,
Ok(Err(err)) => return json_error(&format!("read {}: {err}", relative.display())),
Err(err) => return json_error(&format!("read join: {err}")),
};
match TorrentFile::parse(&data) {
Ok(torrent) => match client.add_torrent(torrent).await {
Ok(session) => format!(
"{{\"ok\":true,\"info_hash\":{},\"name\":{}}}",
json_str(&session.info_hash().to_hex()),
json_str(&session.info().name),
),
Err(err) => json_error(&err.to_string()),
},
Err(err) => json_error(&err.to_string()),
}
}
fn jail_relative_path(jail: &Path, requested: &str) -> std::result::Result<PathBuf, String> {
if !jail.is_dir() {
return Err(format!(
"rpc torrent root is missing or not a directory: {}",
jail.display()
));
}
let candidate = Path::new(requested);
let relative = if candidate.is_absolute() {
candidate.strip_prefix(jail).map_err(|_| {
format!(
"path {} is outside rpc torrent root {}",
candidate.display(),
jail.display()
)
})?
} else {
candidate
};
crate::security::sanitize_torrent_relative_path(relative).map_err(|err| err.to_string())
}
async fn json_add_magnet(client: &Arc<Client>, uri: &str) -> String {
match parse_magnet(uri) {
Ok(magnet) => match client.add_magnet(magnet).await {
Ok(session) => format!(
"{{\"ok\":true,\"info_hash\":{},\"name\":{}}}",
json_str(&session.info_hash().to_hex()),
json_str(&session.info().name),
),
Err(err) => json_error(&err.to_string()),
},
Err(err) => json_error(&err.to_string()),
}
}
async fn json_stop(client: &Arc<Client>, info_hash_hex: &str) -> String {
let Ok(hash) = crate::torrent::InfoHash::from_hex(info_hash_hex) else {
return json_error("invalid info-hash hex");
};
if client.stop_torrent(hash).await {
format!(
"{{\"ok\":true,\"stopped\":true,\"info_hash\":{}}}",
json_str(&hash.to_hex())
)
} else {
json_error("session not found")
}
}
async fn json_remove(client: &Arc<Client>, info_hash_hex: &str) -> String {
let Ok(hash) = crate::torrent::InfoHash::from_hex(info_hash_hex) else {
return json_error("invalid info-hash hex");
};
if client.session(hash).await.is_none() {
return json_error("session not found");
}
client.remove_torrent(hash).await;
format!(
"{{\"ok\":true,\"removed\":true,\"info_hash\":{}}}",
json_str(&hash.to_hex())
)
}
fn json_ok_auth() -> String {
"{\"ok\":true,\"authenticated\":true}".into()
}
fn json_str(value: &str) -> String {
let mut escaped = String::with_capacity(value.len() + 2);
escaped.push('"');
for ch in value.chars() {
match ch {
'\\' => escaped.push_str("\\\\"),
'"' => escaped.push_str("\\\""),
'\n' => escaped.push_str("\\n"),
'\r' => escaped.push_str("\\r"),
'\t' => escaped.push_str("\\t"),
c if c.is_control() => {
use std::fmt::Write;
let _ = write!(escaped, "\\u{:04x}", u32::from(c));
}
c => escaped.push(c),
}
}
escaped.push('"');
escaped
}
fn json_error(message: &str) -> String {
format!("{{\"ok\":false,\"error\":{}}}", json_str(message))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_rpc_without_token_or_listen() {
let cfg = Config {
rpc_enabled: true,
..Config::default()
};
assert!(validate_rpc_config(&cfg).is_err());
let cfg = Config {
rpc_enabled: true,
rpc_listen: Some("127.0.0.1:7600".into()),
..Config::default()
};
assert!(validate_rpc_config(&cfg).is_err());
let cfg = Config {
rpc_enabled: true,
rpc_listen: Some("127.0.0.1:7600".into()),
rpc_auth_token: Some(Zeroizing::new("secret".into())),
..Config::default()
};
assert!(validate_rpc_config(&cfg).is_err());
let cfg = Config {
rpc_enabled: true,
rpc_listen: Some("127.0.0.1:7600".into()),
rpc_auth_token: Some(Zeroizing::new("a-commercial-grade-rpc-token-32b".into())),
..Config::default()
};
assert!(validate_rpc_config(&cfg).is_ok());
}
#[test]
fn rejects_non_loopback_unless_allowed() {
let cfg = Config {
rpc_enabled: true,
rpc_listen: Some("0.0.0.0:7600".into()),
rpc_auth_token: Some(Zeroizing::new("a-commercial-grade-rpc-token-32b".into())),
..Config::default()
};
assert!(validate_rpc_config(&cfg).is_err());
let cfg = Config {
rpc_enabled: true,
rpc_listen: Some("0.0.0.0:7600".into()),
rpc_auth_token: Some(Zeroizing::new("a-commercial-grade-rpc-token-32b".into())),
rpc_allow_non_loopback: true,
..Config::default()
};
assert!(validate_rpc_config(&cfg).is_ok());
}
#[test]
fn auth_constant_time_rejects_mismatch() {
assert!(auth_line("auth secret", "secret").is_ok());
assert!(auth_line("auth wrong", "secret").is_err());
assert!(auth_line("auth secre", "secret").is_err());
assert!(auth_line("auth secrett", "secret").is_err());
assert!(auth_line("status", "secret").is_err());
}
#[tokio::test]
async fn rejects_oversized_rpc_line() {
let mut data = vec![b'a'; MAX_RPC_LINE + 1];
data.push(b'\n');
let mut cursor = std::io::Cursor::new(data);
let mut buf = Vec::new();
let mut carry = Vec::new();
let err = read_rpc_line(&mut cursor, &mut buf, &mut carry)
.await
.expect_err("cap");
assert!(err.to_string().contains("exceeds"));
}
#[tokio::test]
async fn reads_line_in_chunks() {
let data = b"ping\nstatus\n";
let mut cursor = std::io::Cursor::new(data.as_slice());
let mut buf = Vec::new();
let mut carry = Vec::new();
let line = read_rpc_line(&mut cursor, &mut buf, &mut carry)
.await
.expect("read")
.expect("line");
assert_eq!(line, "ping");
buf.clear();
let line = read_rpc_line(&mut cursor, &mut buf, &mut carry)
.await
.expect("read")
.expect("line");
assert_eq!(line, "status");
}
}