use std::collections::VecDeque;
use std::env;
use std::fs::{self, File};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use winit::event_loop::EventLoopProxy;
use super::join_remote_path;
use super::session::SshSession;
use super::sftp::{
EntryKind, LiveConnection, SSH_FXF_CREAT, SSH_FXF_READ, SSH_FXF_TRUNC, SSH_FXF_WRITE,
SftpClient,
};
use crate::desktop::{Event, PaneId};
const CHUNK_SIZE: usize = 32 * 1024;
const PIPELINE_DEPTH: usize = 8;
const MAX_RECURSIVE_DEPTH: usize = 32;
const MAX_RECURSIVE_FILES: usize = 4_096;
const PROGRESS_INTERVAL: Duration = Duration::from_millis(60);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::desktop) enum TransferDirection {
Upload,
Download,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(in crate::desktop) enum TransferState {
Queued,
Running,
Finished(String),
Failed(String),
Cancelled,
}
#[derive(Clone, Debug)]
pub(in crate::desktop) struct TransferItem {
pub(in crate::desktop) id: u64,
pub(in crate::desktop) pane_id: PaneId,
pub(in crate::desktop) session_key: String,
pub(in crate::desktop) direction: TransferDirection,
pub(in crate::desktop) name: String,
pub(in crate::desktop) remote_dir: String,
pub(in crate::desktop) done_bytes: u64,
pub(in crate::desktop) total_bytes: u64,
pub(in crate::desktop) state: TransferState,
pub(in crate::desktop) cancel: Arc<AtomicBool>,
}
#[derive(Clone, Debug)]
pub(in crate::desktop) struct TransferUpdate {
pub(in crate::desktop) id: u64,
pub(in crate::desktop) done_bytes: u64,
pub(in crate::desktop) total_bytes: u64,
pub(in crate::desktop) state: TransferState,
}
enum TransferCommand {
Upload {
id: u64,
session: SshSession,
local_path: PathBuf,
remote_dir: String,
cancel: Arc<AtomicBool>,
},
Download {
id: u64,
session: SshSession,
remote_path: String,
is_dir: bool,
cancel: Arc<AtomicBool>,
},
Shutdown,
}
pub(in crate::desktop) struct TransferWorker {
tx: mpsc::Sender<TransferCommand>,
thread: Option<JoinHandle<()>>,
}
impl TransferWorker {
pub(in crate::desktop) fn spawn(proxy: EventLoopProxy<Event>) -> io::Result<Self> {
let (tx, rx) = mpsc::channel::<TransferCommand>();
let thread = thread::Builder::new()
.name("lune-sftp-xfer".into())
.spawn(move || run_transfer_worker(rx, proxy))?;
Ok(Self {
tx,
thread: Some(thread),
})
}
pub(in crate::desktop) fn upload(
&self,
id: u64,
session: SshSession,
local_path: PathBuf,
remote_dir: String,
cancel: Arc<AtomicBool>,
) {
let _ = self.tx.send(TransferCommand::Upload {
id,
session,
local_path,
remote_dir,
cancel,
});
}
pub(in crate::desktop) fn download(
&self,
id: u64,
session: SshSession,
remote_path: String,
is_dir: bool,
cancel: Arc<AtomicBool>,
) {
let _ = self.tx.send(TransferCommand::Download {
id,
session,
remote_path,
is_dir,
cancel,
});
}
}
impl Drop for TransferWorker {
fn drop(&mut self) {
let _ = self.tx.send(TransferCommand::Shutdown);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
fn run_transfer_worker(rx: mpsc::Receiver<TransferCommand>, proxy: EventLoopProxy<Event>) {
while let Ok(command) = rx.recv() {
match command {
TransferCommand::Shutdown => break,
TransferCommand::Upload {
id,
session,
local_path,
remote_dir,
cancel,
} => {
if cancel.load(Ordering::Acquire) {
send_update(&proxy, id, 0, 0, TransferState::Cancelled);
continue;
}
send_update(&proxy, id, 0, 0, TransferState::Running);
let result = run_upload(
&session,
&local_path,
&remote_dir,
&cancel,
|done, total| {
send_update(&proxy, id, done, total, TransferState::Running);
},
);
match result {
Ok((done, total, summary)) => {
send_update(&proxy, id, done, total, TransferState::Finished(summary));
}
Err(TransferError::Cancelled) => {
send_update(&proxy, id, 0, 0, TransferState::Cancelled);
}
Err(TransferError::Io(err)) => {
send_update(&proxy, id, 0, 0, TransferState::Failed(err.to_string()));
}
}
}
TransferCommand::Download {
id,
session,
remote_path,
is_dir,
cancel,
} => {
if cancel.load(Ordering::Acquire) {
send_update(&proxy, id, 0, 0, TransferState::Cancelled);
continue;
}
send_update(&proxy, id, 0, 0, TransferState::Running);
let result =
run_download(&session, &remote_path, is_dir, &cancel, |done, total| {
send_update(&proxy, id, done, total, TransferState::Running);
});
match result {
Ok((done, total, dest)) => {
send_update(
&proxy,
id,
done,
total,
TransferState::Finished(dest.display().to_string()),
);
}
Err(TransferError::Cancelled) => {
send_update(&proxy, id, 0, 0, TransferState::Cancelled);
}
Err(TransferError::Io(err)) => {
send_update(&proxy, id, 0, 0, TransferState::Failed(err.to_string()));
}
}
}
}
}
}
fn send_update(
proxy: &EventLoopProxy<Event>,
id: u64,
done_bytes: u64,
total_bytes: u64,
state: TransferState,
) {
let _ = proxy.send_event(Event::SshTransferUpdate(TransferUpdate {
id,
done_bytes,
total_bytes,
state,
}));
}
enum TransferError {
Cancelled,
Io(io::Error),
}
impl From<io::Error> for TransferError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
struct ProgressTracker<F> {
done: u64,
total: u64,
last_emit: Instant,
emit: F,
}
impl<F: FnMut(u64, u64)> ProgressTracker<F> {
fn new(total: u64, mut emit: F) -> Self {
emit(0, total);
Self {
done: 0,
total,
last_emit: Instant::now(),
emit,
}
}
fn advance(&mut self, bytes: u64) {
self.done = self.done.saturating_add(bytes);
let now = Instant::now();
if now.duration_since(self.last_emit) >= PROGRESS_INTERVAL {
self.last_emit = now;
(self.emit)(self.done, self.total);
}
}
}
fn run_upload(
session: &SshSession,
local_path: &Path,
remote_dir: &str,
cancel: &AtomicBool,
emit: impl FnMut(u64, u64),
) -> Result<(u64, u64, String), TransferError> {
let file_name = local_path
.file_name()
.and_then(|n| n.to_str())
.filter(|n| is_safe_entry_name(n))
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Invalid local filename"))?;
let meta = fs::metadata(local_path)?;
let remote_root = join_remote_path(remote_dir, file_name);
let mut dirs = Vec::new();
let mut files = Vec::new();
let mut total_bytes = 0u64;
if meta.is_dir() {
dirs.push(remote_root.clone());
collect_local_tree(
local_path,
&remote_root,
0,
&mut dirs,
&mut files,
&mut total_bytes,
)?;
} else if meta.is_file() {
total_bytes = meta.len();
files.push((local_path.to_path_buf(), remote_root.clone()));
} else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Only regular files and directories can be uploaded",
)
.into());
}
if cancel.load(Ordering::Acquire) {
return Err(TransferError::Cancelled);
}
let mut conn = LiveConnection::open(session)?;
let result = (|| -> Result<(u64, u64, String), TransferError> {
let mut tracker = ProgressTracker::new(total_bytes, emit);
for dir in &dirs {
if cancel.load(Ordering::Acquire) {
return Err(TransferError::Cancelled);
}
ensure_remote_dir(&mut conn.client, dir)?;
}
for (src, dst) in &files {
upload_single_file(&mut conn.client, src, dst, cancel, &mut tracker)?;
}
Ok((tracker.done, tracker.total, remote_root))
})();
conn.close();
result
}
fn collect_local_tree(
local_dir: &Path,
remote_dir: &str,
depth: usize,
dirs: &mut Vec<String>,
files: &mut Vec<(PathBuf, String)>,
total_bytes: &mut u64,
) -> io::Result<()> {
if depth >= MAX_RECURSIVE_DEPTH {
return Err(io::Error::other("Directory nesting exceeds safety limit"));
}
for entry in fs::read_dir(local_dir)? {
let entry = entry?;
let file_type = entry.file_type()?;
if file_type.is_symlink() {
continue;
}
let name = entry.file_name();
let Some(name_str) = name.to_str().filter(|n| is_safe_entry_name(n)) else {
continue;
};
let child_local = entry.path();
let child_remote = join_remote_path(remote_dir, name_str);
if file_type.is_dir() {
dirs.push(child_remote.clone());
collect_local_tree(
&child_local,
&child_remote,
depth + 1,
dirs,
files,
total_bytes,
)?;
} else if file_type.is_file() {
if files.len() >= MAX_RECURSIVE_FILES {
return Err(io::Error::other("Too many files in recursive upload"));
}
*total_bytes = total_bytes.saturating_add(entry.metadata()?.len());
files.push((child_local, child_remote));
}
}
Ok(())
}
fn ensure_remote_dir<R: Read, W: Write>(
client: &mut SftpClient<R, W>,
path: &str,
) -> io::Result<()> {
match client.mkdir(path) {
Ok(()) => Ok(()),
Err(mkdir_err) => {
if let Ok(attrs) = client.stat(path, true)
&& attrs.entry_kind() == EntryKind::Directory
{
return Ok(());
}
Err(mkdir_err)
}
}
}
fn upload_single_file<R: Read, W: Write>(
client: &mut SftpClient<R, W>,
local_path: &Path,
remote_path: &str,
cancel: &AtomicBool,
tracker: &mut ProgressTracker<impl FnMut(u64, u64)>,
) -> Result<(), TransferError> {
let mut file = File::open(local_path)?;
let handle = client.open_file(remote_path, SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC)?;
let mut offset = 0u64;
let mut buf = vec![0u8; CHUNK_SIZE];
let mut pending: VecDeque<(u32, u64)> = VecDeque::with_capacity(PIPELINE_DEPTH);
let transfer_res: Result<(), TransferError> = (|| {
loop {
if cancel.load(Ordering::Acquire) {
return Err(TransferError::Cancelled);
}
let read_len = file.read(&mut buf)?;
if read_len == 0 {
break;
}
let req_id = client.send_write(&handle, offset, &buf[..read_len])?;
offset = offset.saturating_add(read_len as u64);
pending.push_back((req_id, read_len as u64));
if pending.len() >= PIPELINE_DEPTH {
client.flush()?;
let (expected_id, chunk_bytes) = pending.pop_front().expect("pending non-empty");
let actual_id = client.read_status_reply()?;
if actual_id != expected_id {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"SFTP write reply order mismatch",
)
.into());
}
tracker.advance(chunk_bytes);
}
}
client.flush()?;
while let Some((expected_id, chunk_bytes)) = pending.pop_front() {
let actual_id = client.read_status_reply()?;
if actual_id != expected_id {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"SFTP write reply order mismatch",
)
.into());
}
tracker.advance(chunk_bytes);
}
Ok(())
})();
let _ = client.close_handle(&handle);
transfer_res
}
fn run_download(
session: &SshSession,
remote_path: &str,
is_dir: bool,
cancel: &AtomicBool,
emit: impl FnMut(u64, u64),
) -> Result<(u64, u64, PathBuf), TransferError> {
let base_name = remote_path
.trim_end_matches('/')
.rsplit('/')
.next()
.filter(|n| is_safe_entry_name(n))
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Invalid remote filename"))?;
let download_dir = resolve_download_dir()?;
fs::create_dir_all(&download_dir)?;
let local_root = unique_destination(&download_dir, base_name);
let mut conn = LiveConnection::open(session)?;
let result = (|| -> Result<(u64, u64, PathBuf), TransferError> {
let mut dirs = Vec::new();
let mut files = Vec::new();
let mut total_bytes = 0u64;
let effective_dir = if is_dir {
true
} else {
conn.client
.stat(remote_path, true)
.map(|attrs| {
total_bytes = attrs.size.unwrap_or(0);
attrs.entry_kind() == EntryKind::Directory
})
.unwrap_or(false)
};
if effective_dir {
total_bytes = 0;
dirs.push(local_root.clone());
collect_remote_tree(
&mut conn.client,
remote_path,
&local_root,
0,
cancel,
&mut dirs,
&mut files,
&mut total_bytes,
)?;
} else {
files.push((remote_path.to_owned(), local_root.clone()));
}
let mut tracker = ProgressTracker::new(total_bytes, emit);
for dir in &dirs {
if cancel.load(Ordering::Acquire) {
return Err(TransferError::Cancelled);
}
fs::create_dir_all(dir)?;
}
for (src, dst) in &files {
download_single_file(&mut conn.client, src, dst, cancel, &mut tracker)?;
}
Ok((tracker.done, tracker.total, local_root))
})();
conn.close();
result
}
#[allow(clippy::too_many_arguments)]
fn collect_remote_tree<R: Read, W: Write>(
client: &mut SftpClient<R, W>,
remote_dir: &str,
local_dir: &Path,
depth: usize,
cancel: &AtomicBool,
dirs: &mut Vec<PathBuf>,
files: &mut Vec<(String, PathBuf)>,
total_bytes: &mut u64,
) -> Result<(), TransferError> {
if depth >= MAX_RECURSIVE_DEPTH {
return Err(io::Error::other("Remote directory nesting exceeds safety limit").into());
}
if cancel.load(Ordering::Acquire) {
return Err(TransferError::Cancelled);
}
for entry in client.list_dir(remote_dir)? {
if !is_safe_entry_name(&entry.name) {
continue;
}
let child_remote = join_remote_path(remote_dir, &entry.name);
let child_local = local_dir.join(&entry.name);
match entry.kind {
EntryKind::Directory => {
dirs.push(child_local.clone());
collect_remote_tree(
client,
&child_remote,
&child_local,
depth + 1,
cancel,
dirs,
files,
total_bytes,
)?;
}
EntryKind::File => {
if files.len() >= MAX_RECURSIVE_FILES {
return Err(io::Error::other("Too many files in recursive download").into());
}
*total_bytes = total_bytes.saturating_add(entry.size.unwrap_or(0));
files.push((child_remote, child_local));
}
EntryKind::Symlink | EntryKind::Other => {}
}
}
Ok(())
}
fn download_single_file<R: Read, W: Write>(
client: &mut SftpClient<R, W>,
remote_path: &str,
local_path: &Path,
cancel: &AtomicBool,
tracker: &mut ProgressTracker<impl FnMut(u64, u64)>,
) -> Result<(), TransferError> {
let handle = client.open_file(remote_path, SSH_FXF_READ)?;
let mut file = File::create(local_path)?;
let mut file_pos = 0u64;
let mut next_offset = 0u64;
let mut pending: VecDeque<(u32, u64, u32)> = VecDeque::with_capacity(PIPELINE_DEPTH);
let mut eof_offset: Option<u64> = None;
let transfer_res: Result<(), TransferError> = (|| {
while pending.len() < PIPELINE_DEPTH {
let req_id = client.send_read(&handle, next_offset, CHUNK_SIZE as u32)?;
pending.push_back((req_id, next_offset, CHUNK_SIZE as u32));
next_offset = next_offset.saturating_add(CHUNK_SIZE as u64);
}
client.flush()?;
while let Some((expected_id, offset, requested)) = pending.pop_front() {
if cancel.load(Ordering::Acquire) {
return Err(TransferError::Cancelled);
}
let (actual_id, chunk) = client.read_data_reply()?;
if actual_id != expected_id {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"SFTP read reply order mismatch",
)
.into());
}
match chunk {
Some(bytes) if !bytes.is_empty() => {
let received = bytes.len();
if offset != file_pos {
file.seek(SeekFrom::Start(offset))?;
}
file.write_all(&bytes)?;
file_pos = offset.saturating_add(received as u64);
tracker.advance(received as u64);
if received < requested as usize {
let rem_offset = offset.saturating_add(received as u64);
let rem_len = requested - received as u32;
if eof_offset.is_none_or(|eof| rem_offset < eof) {
let req_id = client.send_read(&handle, rem_offset, rem_len)?;
pending.push_back((req_id, rem_offset, rem_len));
client.flush()?;
}
} else if eof_offset.is_none() {
let req_id = client.send_read(&handle, next_offset, CHUNK_SIZE as u32)?;
pending.push_back((req_id, next_offset, CHUNK_SIZE as u32));
next_offset = next_offset.saturating_add(CHUNK_SIZE as u64);
client.flush()?;
}
}
_ => {
eof_offset = Some(eof_offset.map_or(offset, |prev| prev.min(offset)));
}
}
}
file.flush()?;
Ok(())
})();
drop(file);
let _ = client.close_handle(&handle);
if transfer_res.is_err() {
let _ = fs::remove_file(local_path);
}
transfer_res
}
pub(super) fn is_safe_entry_name(name: &str) -> bool {
!name.is_empty()
&& name != "."
&& name != ".."
&& !name.contains('/')
&& !name.contains('\\')
&& !name.contains('\0')
}
pub(super) fn unique_destination(dir: &Path, name: &str) -> PathBuf {
let candidate = dir.join(name);
if !candidate.exists() {
return candidate;
}
let path = Path::new(name);
let stem = path
.file_stem()
.and_then(|s| s.to_str())
.filter(|s| !s.is_empty())
.unwrap_or(name);
let ext = path.extension().and_then(|e| e.to_str());
for n in 1..10_000u32 {
let next = match ext {
Some(_) if name.starts_with('.') && name[1..].find('.').is_none() => {
format!("{name} ({n})")
}
Some(ext) => format!("{stem} ({n}).{ext}"),
None => format!("{name} ({n})"),
};
let path = dir.join(next);
if !path.exists() {
return path;
}
}
dir.join(format!("{name}.download"))
}
fn resolve_download_dir() -> io::Result<PathBuf> {
if let Some(explicit) = env::var_os("XDG_DOWNLOAD_DIR")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
{
return Ok(explicit);
}
let home = env::var_os("HOME")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.ok_or_else(|| io::Error::other("HOME directory is not set"))?;
let user_dirs = env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.unwrap_or_else(|| home.join(".config"))
.join("user-dirs.dirs");
if let Ok(content) = fs::read_to_string(user_dirs)
&& let Some(parsed) = parse_xdg_download_dir(&content, &home)
{
return Ok(parsed);
}
Ok(home.join("Downloads"))
}
fn parse_xdg_download_dir(content: &str, home: &Path) -> Option<PathBuf> {
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') {
continue;
}
let Some(value) = trimmed.strip_prefix("XDG_DOWNLOAD_DIR=") else {
continue;
};
let unquoted = value.trim().trim_matches('"');
if let Some(rel) = unquoted.strip_prefix("$HOME/") {
return Some(home.join(rel));
}
if unquoted == "$HOME" {
return Some(home.to_path_buf());
}
let path = PathBuf::from(unquoted);
if path.is_absolute() {
return Some(path);
}
}
None
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::*;
#[test]
fn validates_entry_names_xdg_dirs_and_unique_destinations() {
assert!(is_safe_entry_name("report.pdf"));
assert!(is_safe_entry_name(".env"));
assert!(!is_safe_entry_name(""));
assert!(!is_safe_entry_name("."));
assert!(!is_safe_entry_name(".."));
assert!(!is_safe_entry_name("a/b"));
assert!(!is_safe_entry_name("a\\b"));
assert!(!is_safe_entry_name("bad\0name"));
let home = Path::new("/tmp/test-home");
assert_eq!(
parse_xdg_download_dir("XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n", home),
Some(PathBuf::from("/tmp/test-home/Downloads"))
);
assert_eq!(
parse_xdg_download_dir("# comment\nXDG_DOWNLOAD_DIR=\"/var/dl\"\n", home),
Some(PathBuf::from("/var/dl"))
);
let dir = env::temp_dir().join(format!("lune-xfer-unique-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
assert_eq!(unique_destination(&dir, "demo.txt"), dir.join("demo.txt"));
fs::write(dir.join("demo.txt"), b"x").unwrap();
assert_eq!(
unique_destination(&dir, "demo.txt"),
dir.join("demo (1).txt")
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn pipelined_download_and_upload_exchange_complete_payloads() {
fn pkt(packet_type: u8, payload: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(5 + payload.len());
out.extend_from_slice(&((payload.len() + 1) as u32).to_be_bytes());
out.push(packet_type);
out.extend_from_slice(payload);
out
}
fn u32_bytes(v: u32) -> [u8; 4] {
v.to_be_bytes()
}
let mut replies = Vec::new();
replies.extend_from_slice(&pkt(2, &u32_bytes(3)));
let mut open_reply = Vec::new();
open_reply.extend_from_slice(&u32_bytes(1));
open_reply.extend_from_slice(&u32_bytes(2));
open_reply.extend_from_slice(b"f1");
replies.extend_from_slice(&pkt(102, &open_reply));
let mut data_reply_1 = Vec::new();
data_reply_1.extend_from_slice(&u32_bytes(2));
data_reply_1.extend_from_slice(&u32_bytes(6));
data_reply_1.extend_from_slice(b"hello ");
replies.extend_from_slice(&pkt(103, &data_reply_1));
for id in 3..=(1 + PIPELINE_DEPTH as u32) {
let mut eof = Vec::new();
eof.extend_from_slice(&u32_bytes(id));
eof.extend_from_slice(&u32_bytes(1)); eof.extend_from_slice(&u32_bytes(0));
eof.extend_from_slice(&u32_bytes(0));
replies.extend_from_slice(&pkt(101, &eof));
}
let rem_1 = 2 + PIPELINE_DEPTH as u32;
let mut data_reply_2 = Vec::new();
data_reply_2.extend_from_slice(&u32_bytes(rem_1));
data_reply_2.extend_from_slice(&u32_bytes(5));
data_reply_2.extend_from_slice(b"world");
replies.extend_from_slice(&pkt(103, &data_reply_2));
let rem_2 = rem_1 + 1;
let mut eof_tail = Vec::new();
eof_tail.extend_from_slice(&u32_bytes(rem_2));
eof_tail.extend_from_slice(&u32_bytes(1)); eof_tail.extend_from_slice(&u32_bytes(0));
eof_tail.extend_from_slice(&u32_bytes(0));
replies.extend_from_slice(&pkt(101, &eof_tail));
let mut close_ok = Vec::new();
close_ok.extend_from_slice(&u32_bytes(rem_2 + 1));
close_ok.extend_from_slice(&u32_bytes(0)); close_ok.extend_from_slice(&u32_bytes(0));
close_ok.extend_from_slice(&u32_bytes(0));
replies.extend_from_slice(&pkt(101, &close_ok));
let tmp = env::temp_dir().join(format!("lune-dl-test-{}.txt", std::process::id()));
let _ = fs::remove_file(&tmp);
let mut sent = Vec::new();
let mut client = SftpClient::new(Cursor::new(replies), &mut sent).unwrap();
let cancel = AtomicBool::new(false);
let mut tracker = ProgressTracker::new(11, |_, _| {});
download_single_file(&mut client, "/srv/demo.txt", &tmp, &cancel, &mut tracker)
.ok()
.unwrap();
assert_eq!(fs::read(&tmp).unwrap(), b"hello world");
assert_eq!(tracker.done, 11);
let _ = fs::remove_file(&tmp);
}
}