use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use crate::state::{Engine, Status, Store};
pub fn runtime_dir() -> PathBuf {
if let Ok(v) = std::env::var("XGET_RUNTIME_DIR") {
if !v.trim().is_empty() {
return PathBuf::from(v);
}
}
if let Ok(v) = std::env::var("XDG_RUNTIME_DIR") {
if !v.trim().is_empty() {
return PathBuf::from(v);
}
}
std::env::temp_dir()
}
pub fn socket_path() -> PathBuf {
runtime_dir().join("xget.sock")
}
pub fn pid_path() -> PathBuf {
runtime_dir().join("xget.pid")
}
fn read_pid() -> Option<u32> {
std::fs::read_to_string(pid_path())
.ok()
.and_then(|s| s.trim().parse::<u32>().ok())
}
fn pid_alive(pid: u32) -> bool {
PathBuf::from(format!("/proc/{pid}")).exists()
}
pub fn rpc_block(method: &str, params: Value) -> Option<Value> {
let sock = socket_path();
if !sock.exists() {
return None;
}
let stream = std::os::unix::net::UnixStream::connect(&sock).ok()?;
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.ok()?;
stream
.set_write_timeout(Some(Duration::from_secs(5)))
.ok()?;
let mut reader = BufReader::new(stream.try_clone().ok()?);
let mut writer = stream;
let req = json!({"id": 1, "method": method, "params": params});
let mut line = serde_json::to_string(&req).ok()?;
line.push('\n');
writer.write_all(line.as_bytes()).ok()?;
writer.flush().ok()?;
let mut resp_line = String::new();
reader.read_line(&mut resp_line).ok()?;
if resp_line.trim().is_empty() {
return None;
}
serde_json::from_str(&resp_line).ok()
}
pub fn daemon_active() -> bool {
match rpc_block("ping", json!({})) {
Some(v) => v.get("result").and_then(|r| r.get("ok")).and_then(|o| o.as_bool()).unwrap_or(false),
None => false,
}
}
pub fn daemon_status_line() -> String {
let sock = socket_path();
match read_pid() {
Some(pid) if pid_alive(pid) && daemon_active() => {
let n = rpc_block("list", json!({}))
.and_then(|v| v.get("result").and_then(|r| r.get("records")).and_then(|r| r.as_array()).map(|a| a.len()))
.unwrap_or(0);
format!("daemon running (pid {pid}, socket {}, {n} record(s))", sock.display())
}
Some(pid) if pid_alive(pid) => format!("daemon pid file present (pid {pid}) but socket not responding at {}", sock.display()),
_ => {
if daemon_active() {
format!("daemon running (socket {})", sock.display())
} else {
format!("daemon not running (socket {})", sock.display())
}
}
}
}
pub async fn run_server() -> Result<()> {
let sock = socket_path();
if let Some(parent) = sock.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("cannot create {}", parent.display()))?;
}
if sock.exists() {
let _ = std::fs::remove_file(&sock);
}
let listener = tokio::net::UnixListener::bind(&sock)
.with_context(|| format!("cannot bind {}", sock.display()))?;
let pid = std::process::id();
let _ = std::fs::write(pid_path(), pid.to_string());
println!("xget daemon listening on {} (pid {pid})", sock.display());
loop {
let Ok((stream, _)) = listener.accept().await else {
continue;
};
let shutdown = handle_conn(stream).await;
if shutdown {
break;
}
}
let _ = std::fs::remove_file(&sock);
let _ = std::fs::remove_file(pid_path());
println!("xget daemon stopped");
Ok(())
}
async fn handle_conn(stream: tokio::net::UnixStream) -> bool {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
let (r, mut w) = stream.into_split();
let mut reader = tokio::io::BufReader::new(r);
let mut line = String::new();
let n = reader.read_line(&mut line).await.unwrap_or(0);
if n == 0 {
return false;
}
let req: Value = match serde_json::from_str(line.trim()) {
Ok(v) => v,
Err(_) => {
let _ = w.write_all(b"{\"id\":0,\"error\":\"bad request\"}\n").await;
return false;
}
};
let id = req.get("id").cloned().unwrap_or(json!(0));
let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("").to_string();
let params = req.get("params").cloned().unwrap_or(json!({}));
let (result, error, shutdown): (Value, Option<String>, bool) = dispatch(&method, params);
let resp = if let Some(e) = error {
json!({"id": id, "error": e})
} else {
json!({"id": id, "result": result})
};
let mut out = serde_json::to_string(&resp).unwrap_or_else(|_| "{\"error\":\"encode\"}".to_string());
out.push('\n');
let _ = w.write_all(out.as_bytes()).await;
shutdown
}
fn dispatch(method: &str, params: Value) -> (Value, Option<String>, bool) {
match method {
"ping" => (json!({"ok": true}), None, false),
"list" => match Store::load() {
Ok(s) => {
let records = serde_json::to_value(s.all()).unwrap_or(json!([]));
(json!({"records": records}), None, false)
}
Err(e) => (json!({}), Some(format!("{e:#}")), false),
},
"status" => {
let id = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32);
match Store::load() {
Ok(s) => {
let records: Vec<&crate::state::Record> = match id {
Some(i) => s.get(i).into_iter().collect(),
None => s.all().iter().collect(),
};
let v = serde_json::to_value(&records).unwrap_or(json!([]));
(json!({"records": v}), None, false)
}
Err(e) => (json!({}), Some(format!("{e:#}")), false),
}
}
"add" => {
let url = params.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string();
let output = params.get("output").and_then(|v| v.as_str()).unwrap_or("").to_string();
let connections = params.get("connections").and_then(|v| v.as_u64()).unwrap_or(16) as usize;
let kind = params.get("kind").and_then(|v| v.as_str()).unwrap_or("direct");
if url.is_empty() || output.is_empty() {
return (json!({}), Some("add needs url and output".to_string()), false);
}
match Store::update(|s| {
let engine = if kind == "torrent" { Engine::Torrent } else { Engine::Direct };
let id = s.add(
url.clone(),
PathBuf::from(output.clone()),
connections.clamp(1, 32),
engine,
Vec::new(),
0,
None,
None,
);
if let Some(r) = s.get_mut(id) {
r.status = Status::Downloading;
}
id
}) {
Ok(id) => (json!({"id": id}), None, false),
Err(e) => (json!({}), Some(format!("{e:#}")), false),
}
}
"pause" => {
let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
return (json!({}), Some("pause needs id".to_string()), false);
};
enum POut { Ok, NoSuch }
match Store::update(|s| {
let Some(r) = s.get_mut(id) else {
return POut::NoSuch;
};
r.status = Status::Paused;
r.error = None;
POut::Ok
}) {
Ok(POut::Ok) => (json!({"id": id, "status": "paused"}), None, false),
Ok(POut::NoSuch) => (json!({}), Some(format!("no such download with id {id}")), false),
Err(e) => (json!({}), Some(format!("{e:#}")), false),
}
}
"resume_state" => {
let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
return (json!({}), Some("resume_state needs id".to_string()), false);
};
enum ROut { Ok, NoSuch }
match Store::update(|s| {
let Some(r) = s.get_mut(id) else {
return ROut::NoSuch;
};
r.status = Status::Downloading;
r.error = None;
ROut::Ok
}) {
Ok(ROut::Ok) => (json!({"id": id, "status": "active"}), None, false),
Ok(ROut::NoSuch) => (json!({}), Some(format!("no such download with id {id}")), false),
Err(e) => (json!({}), Some(format!("{e:#}")), false),
}
}
"complete" => {
let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
return (json!({}), Some("complete needs id".to_string()), false);
};
let total = params.get("total").and_then(|v| v.as_u64());
enum COut { Ok, NoSuch }
match Store::update(|s| {
let Some(r) = s.get_mut(id) else {
return COut::NoSuch;
};
r.status = Status::Completed;
r.error = None;
if let Some(t) = total {
r.total_bytes = Some(t);
r.downloaded = t;
}
COut::Ok
}) {
Ok(COut::Ok) => (json!({"id": id, "status": "done"}), None, false),
Ok(COut::NoSuch) => (json!({}), Some(format!("no such download with id {id}")), false),
Err(e) => (json!({}), Some(format!("{e:#}")), false),
}
}
"fail" => {
let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
return (json!({}), Some("fail needs id".to_string()), false);
};
let err = params.get("error").and_then(|v| v.as_str()).unwrap_or("failed").to_string();
enum FOut { Ok, NoSuch }
match Store::update(|s| {
let Some(r) = s.get_mut(id) else {
return FOut::NoSuch;
};
r.status = Status::Failed;
r.error = Some(err.clone());
FOut::Ok
}) {
Ok(FOut::Ok) => (json!({"id": id, "status": "failed"}), None, false),
Ok(FOut::NoSuch) => (json!({}), Some(format!("no such download with id {id}")), false),
Err(e) => (json!({}), Some(format!("{e:#}")), false),
}
}
"remove" => {
let Some(id) = params.get("id").and_then(|v| v.as_u64()).map(|v| v as u32) else {
return (json!({}), Some("remove needs id".to_string()), false);
};
match Store::update(|s| s.remove(id).is_some()) {
Ok(true) => (json!({"id": id, "removed": true}), None, false),
Ok(false) => (json!({}), Some(format!("no such download with id {id}")), false),
Err(e) => (json!({}), Some(format!("{e:#}")), false),
}
}
"shutdown" => (json!({"ok": true}), None, true),
_ => (json!({}), Some(format!("unknown method: {method}")), false),
}
}
pub fn cmd_start() -> Result<()> {
if daemon_active() {
println!("daemon already running: {}", socket_path().display());
return Ok(());
}
let exe = std::env::current_exe().context("cannot find xget binary")?;
let mut cmd = std::process::Command::new(exe);
cmd.arg("__daemon-run");
cmd.stdin(std::process::Stdio::null());
cmd.stdout(std::process::Stdio::null());
cmd.stderr(std::process::Stdio::null());
let child = cmd.spawn().context("cannot start daemon process")?;
let pid = child.id();
drop(child);
for _ in 0..50 {
std::thread::sleep(Duration::from_millis(100));
if daemon_active() {
println!("daemon started (pid {pid}, socket {})", socket_path().display());
return Ok(());
}
}
bail!("daemon did not respond on {}", socket_path().display());
}
pub fn cmd_stop() -> Result<()> {
if !daemon_active() {
let _ = std::fs::remove_file(socket_path());
let _ = std::fs::remove_file(pid_path());
println!("daemon not running");
return Ok(());
}
let _ = rpc_block("shutdown", json!({}));
std::thread::sleep(Duration::from_millis(300));
let _ = std::fs::remove_file(socket_path());
let _ = std::fs::remove_file(pid_path());
println!("daemon stopped");
Ok(())
}
pub fn cmd_status() -> Result<()> {
println!("{}", daemon_status_line());
Ok(())
}
pub fn daemon_create_record(url: &str, output: &str, connections: usize, kind: &str) -> Option<u32> {
let resp = rpc_block(
"add",
json!({"url": url, "output": output, "connections": connections, "kind": kind}),
)?;
if let Some(e) = resp.get("error") {
let _ = e;
return None;
}
resp.get("result")
.and_then(|r| r.get("id"))
.and_then(|v| v.as_u64())
.map(|v| v as u32)
}
pub fn daemon_complete(id: u32, total: u64) -> bool {
rpc_block("complete", json!({"id": id, "total": total})).is_some()
}
pub fn daemon_fail(id: u32, error: &str) -> bool {
rpc_block("fail", json!({"id": id, "error": error})).is_some()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn socket_paths_are_sane() {
let s = socket_path();
assert!(s.to_string_lossy().contains("xget.sock"));
let p = pid_path();
assert!(p.to_string_lossy().contains("xget.pid"));
}
#[test]
fn dispatch_ping_and_unknown() {
let (r, e, sd) = dispatch("ping", json!({}));
assert!(e.is_none() && !sd);
assert_eq!(r.get("ok").and_then(|v| v.as_bool()), Some(true));
let (_, e, _) = dispatch("nope", json!({}));
assert!(e.is_some());
}
#[test]
fn dispatch_validates_add_and_pause() {
let (_, e, _) = dispatch("add", json!({}));
assert!(e.is_some());
let (_, e, _) = dispatch("pause", json!({}));
assert!(e.is_some());
let (_, e, _) = dispatch("remove", json!({"id": 999999}));
assert!(e.is_some() || e.is_none());
}
#[test]
fn rpc_returns_none_without_socket() {
let dir = std::env::temp_dir().join(format!("xget-daemon-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let prev = std::env::var("XGET_RUNTIME_DIR").ok();
unsafe { std::env::set_var("XGET_RUNTIME_DIR", &dir) };
assert!(rpc_block("ping", json!({})).is_none());
assert!(!daemon_active());
if let Some(v) = prev {
unsafe { std::env::set_var("XGET_RUNTIME_DIR", v) };
} else {
unsafe { std::env::remove_var("XGET_RUNTIME_DIR") };
}
let _ = std::fs::remove_dir_all(&dir);
}
}