use std::time::Duration;
use luciola::link::secure::SecureStream;
use luciola_transfer::protocol::{is_chunk_frame, is_intro_frame, FileAck, FileChunk, FileIntro};
use luciola_transfer::{FileReceiver, FileSender, ReceiverConfig};
async fn admit(stream: &mut SecureStream, tx: &FileSender) -> Result<(), String> {
let mut channel = stream.channel_type();
if tx.check_channel_policy(channel).is_err() && stream.may_migrate() {
channel = stream
.wait_channel_settle(std::time::Duration::from_secs(30))
.await;
}
tx.check_channel_policy(channel).map_err(|e| e.to_string())
}
pub async fn run_send(
mut stream: SecureStream,
mut tx: FileSender,
file_name: &str,
) -> Result<FileSender, String> {
admit(&mut stream, &tx).await?;
let intro = FileIntro {
transfer_id: tx.transfer_id().to_string(),
file_name: sanitize_name(file_name),
total_size: tx.total_size(),
};
let total = tx.total_size();
stream
.send(&intro.encode())
.await
.map_err(|e| e.to_string())?;
let mut buf: Vec<u8> = Vec::new();
let mut last_reported = 0u64;
let mut last_channel_type = stream.channel_type();
eprintln!("[INFO] Active channel: {}", last_channel_type.as_str());
loop {
let current_channel = stream.channel_type();
if current_channel != last_channel_type {
eprintln!(
"[INFO] Channel upgraded: {} -> {}!",
last_channel_type.as_str(),
current_channel.as_str()
);
last_channel_type = current_channel;
}
if tx.is_done() {
return Ok(tx);
}
for chunk in tx.fill_window().await.map_err(|e| e.to_string())? {
stream
.send(&chunk.encode())
.await
.map_err(|e| e.to_string())?;
}
tokio::select! {
frame = stream.recv(&mut buf) => match frame {
Ok(()) if !is_chunk_frame(&buf) => {
let ack = FileAck::decode(&buf).map_err(|e| e.to_string())?;
if ack.resume {
eprintln!(
"[INFO] Remote peer requested resume: skipping {}/{} bytes ({:.1}%)",
ack.acked_up_to,
total,
(ack.acked_up_to as f64 / total.max(1) as f64) * 100.0
);
}
tx.on_ack(ack.acked_up_to);
report_progress(total, tx.acked_up_to(), &mut last_reported);
}
Ok(()) => {} Err(e) => return Err(format!("channel closed at {} / {} bytes: {e}", tx.acked_up_to(), total)),
},
_ = tokio::time::sleep(Duration::from_millis(100)) => {}
}
for chunk in tx.expired_in_flight().await.map_err(|e| e.to_string())? {
stream
.send(&chunk.encode())
.await
.map_err(|e| e.to_string())?;
}
}
}
pub async fn run_recv(
mut stream: SecureStream,
dest_dir: &std::path::Path,
quiet: Duration,
) -> Result<FileReceiver, String> {
let mut buf: Vec<u8> = Vec::new();
stream.recv(&mut buf).await.map_err(|e| e.to_string())?;
let intro = if is_intro_frame(&buf) {
FileIntro::decode(&buf).map_err(|e| e.to_string())?
} else {
return Err("peer's first message was not a transfer intro".into());
};
let safe_name = std::path::Path::new(&intro.file_name)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("received.bin");
let dest = dest_dir.join(safe_name);
let mut rx = FileReceiver::create(
&intro.transfer_id,
&dest,
intro.total_size,
ReceiverConfig::default(),
)
.await
.map_err(|e| e.to_string())?;
let total = rx.total_size();
let mut last_reported = 0u64;
if rx.acked_up_to() > 0 {
eprintln!(
"[INFO] Resuming transfer from checkpoint: {}/{} bytes ({:.1}%) already on disk",
rx.acked_up_to(),
total,
(rx.acked_up_to() as f64 / total.max(1) as f64) * 100.0
);
let resume_ack = FileAck {
transfer_id: rx.transfer_id().to_string(),
acked_up_to: rx.acked_up_to(),
resume: true,
};
stream
.send(&resume_ack.encode())
.await
.map_err(|e| e.to_string())?;
last_reported = rx.acked_up_to();
}
loop {
if rx.is_complete() {
match tokio::time::timeout(quiet, stream.recv(&mut buf)).await {
Ok(Ok(())) => { }
_ => return Ok(rx),
}
} else {
stream.recv(&mut buf).await.map_err(|e| {
format!(
"peer closed before transfer complete ({} / {} bytes): {e}",
rx.acked_up_to(),
total
)
})?;
}
if !is_chunk_frame(&buf) {
continue;
}
let chunk = FileChunk::decode(&buf).map_err(|e| e.to_string())?;
let acked = rx.on_chunk(&chunk).await.map_err(|e| e.to_string())?;
report_progress(total, acked, &mut last_reported);
let ack = FileAck {
transfer_id: chunk.transfer_id.clone(),
acked_up_to: acked,
resume: false,
};
if let Err(e) = stream.send(&ack.encode()).await {
if rx.is_complete() {
return Ok(rx);
}
return Err(e.to_string());
}
}
}
fn report_progress(total: u64, acked: u64, last_reported: &mut u64) {
let pct = if total == 0 { 100 } else { acked * 100 / total };
let last_pct = if total == 0 {
100
} else {
*last_reported * 100 / total
};
if pct >= last_pct + 5 || (*last_reported == 0 && acked > 0) {
eprintln!(" ⏳ {}/{} bytes ({}%)", acked, total, pct);
*last_reported = acked;
}
}
pub(crate) fn make_transfer_id(file_name: &str, total_size: u64) -> String {
let mtime = std::fs::metadata(file_name)
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis());
let stamp = mtime.unwrap_or_else(|| {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0)
});
format!("{}-{}-{stamp}", sanitize_name(file_name), total_size)
}
fn sanitize_name(name: &str) -> String {
std::path::Path::new(name)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("file")
.to_string()
}
#[cfg(test)]
mod tests {
use super::{admit, make_transfer_id, run_recv, run_send, sanitize_name, FileSender};
use luciola::link::secure::{accept_secure, SecureStream};
use luciola::trust::generate_identity;
use luciola_transfer::protocol::FileIntro;
use luciola_transfer::SenderConfig;
use std::sync::Arc;
use std::time::Duration;
async fn secure_pair() -> (SecureStream, SecureStream) {
let a = generate_identity();
let b = generate_identity();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let seed_b = b.seed.clone();
let key_a = a.public_key.clone();
let server: tokio::task::JoinHandle<SecureStream> = tokio::spawn(async move {
accept_secure(&listener, &seed_b, Some(&key_a))
.await
.unwrap()
});
let client =
luciola::link::secure::connect_secure("127.0.0.1", port, &a.seed, &b.public_key)
.await
.expect("client handshake");
let server = server.await.expect("server task");
(client, server)
}
#[tokio::test(flavor = "multi_thread")]
async fn large_transfer_is_admitted_once_the_channel_migrates() {
use luciola_proto::ChannelType;
use std::sync::atomic::{AtomicU8, Ordering};
let dir =
std::env::temp_dir().join(format!("luciola-cli-quota-migrate-{}", std::process::id()));
tokio::fs::create_dir_all(&dir).await.unwrap();
let src = dir.join("big.bin");
let file = tokio::fs::File::create(&src).await.unwrap();
file.set_len(120 * 1024 * 1024).await.unwrap();
drop(file);
let (mut client, _server) = secure_pair().await;
let tracker = Arc::new(AtomicU8::new(ChannelType::RelayForwarded as u8));
client.set_channel_tracker(tracker.clone());
assert!(client.may_migrate());
let tx = FileSender::open("big", &src, SenderConfig::default())
.await
.unwrap();
assert!(tx
.check_channel_policy(ChannelType::RelayForwarded)
.is_err());
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
tracker.store(ChannelType::HolePunchedDirect as u8, Ordering::Release);
});
admit(&mut client, &tx)
.await
.expect("a migrating connection must not be judged on its transient relay hop");
tokio::fs::remove_dir_all(&dir).await.ok();
}
#[tokio::test(flavor = "multi_thread")]
async fn large_transfer_over_a_pure_relay_is_still_refused() {
use luciola_proto::ChannelType;
let dir = std::env::temp_dir().join(format!("luciola-cli-quota2-{}", std::process::id()));
tokio::fs::create_dir_all(&dir).await.unwrap();
let src = dir.join("big.bin");
let file = tokio::fs::File::create(&src).await.unwrap();
file.set_len(120 * 1024 * 1024).await.unwrap();
drop(file);
let (mut client, _server) = secure_pair().await;
client.set_channel_type(ChannelType::RelayForwarded);
assert!(!client.may_migrate());
let tx = FileSender::open("big", &src, SenderConfig::default())
.await
.unwrap();
let err = admit(&mut client, &tx).await.unwrap_err();
assert!(err.contains("exceeds limit"), "{err}");
tokio::fs::remove_dir_all(&dir).await.ok();
}
#[test]
fn sanitize_name_strips_directories() {
assert_eq!(sanitize_name("../../.ssh/id_ed25519"), "id_ed25519");
assert_eq!(sanitize_name("normal.bin"), "normal.bin");
assert_eq!(sanitize_name("/abs/path/file"), "file");
}
#[test]
fn transfer_id_is_stable_per_file_shape() {
let a = make_transfer_id("a.bin", 100);
assert!(a.starts_with("a.bin-100-"), "{a}");
}
#[tokio::test(flavor = "multi_thread")]
async fn send_recv_roundtrip_over_real_secure_stream() {
let dir = std::env::temp_dir().join(format!("luciola-cli-transfer-{}", std::process::id()));
tokio::fs::create_dir_all(&dir).await.unwrap();
let src = dir.join("hello.bin");
let out = dir.join("out");
tokio::fs::create_dir_all(&out).await.unwrap();
let payload: Arc<Vec<u8>> = Arc::new((0..512 * 1024u32).map(|i| (i % 251) as u8).collect());
tokio::fs::write(&src, payload.as_slice()).await.unwrap();
let (client, server) = secure_pair().await;
let id = make_transfer_id("hello.bin", payload.len() as u64);
let tx = FileSender::open(
&id,
&src,
SenderConfig {
chunk_size: 64 * 1024,
window: 8,
retransmit_after: Duration::from_millis(200),
..Default::default()
},
)
.await
.unwrap();
let sender = tokio::spawn(async move {
let tx = run_send(client, tx, "hello.bin")
.await
.expect("send driver");
tx
});
let out2 = out.clone();
let receiver =
tokio::spawn(async move { run_recv(server, &out2, Duration::from_millis(500)).await });
let _tx = sender.await.unwrap();
let rx = receiver.await.unwrap().expect("recv driver");
assert!(rx.is_complete());
assert_eq!(rx.acked_up_to(), payload.len() as u64);
let dest = out.join("hello.bin");
let got = tokio::fs::read(&dest).await.unwrap();
assert_eq!(got.len(), payload.len(), "byte count must match");
assert_eq!(got, *payload, "bytes must match");
tokio::fs::remove_dir_all(&dir).await.ok();
}
#[tokio::test(flavor = "multi_thread")]
async fn relay_quota_is_enforced_before_the_first_frame() {
let dir = std::env::temp_dir().join(format!("luciola-cli-quota-{}", std::process::id()));
tokio::fs::create_dir_all(&dir).await.unwrap();
let src = dir.join("big.bin");
tokio::fs::write(&src, vec![0u8; 4096]).await.unwrap();
let (mut client, mut server) = secure_pair().await;
client.set_channel_type(luciola_proto::ChannelType::RelayForwarded);
let tx = FileSender::open(
"quota-check",
&src,
SenderConfig {
relay_max_bytes: Some(1024),
..Default::default()
},
)
.await
.unwrap();
let err = match run_send(client, tx, "big.bin").await {
Ok(_) => panic!("relay quota must deny an oversized file"),
Err(e) => e,
};
assert!(err.contains("exceeds limit"), "{err}");
let mut buf = Vec::new();
let received = tokio::time::timeout(Duration::from_secs(1), server.recv(&mut buf)).await;
assert!(
!matches!(received, Ok(Ok(()))),
"no intro frame may be sent before the channel quota check"
);
tokio::fs::remove_dir_all(&dir).await.ok();
}
#[tokio::test(flavor = "multi_thread")]
async fn receiver_never_escapes_the_out_dir() {
use luciola_transfer::protocol::FileChunk;
let dir = std::env::temp_dir().join(format!("luciola-cli-xform-{}", std::process::id()));
let out = dir.join("out");
tokio::fs::create_dir_all(&out).await.unwrap();
let payload: Vec<u8> = (0..64 * 1024u32).map(|i| (i % 251) as u8).collect();
let total = payload.len() as u64;
let (mut evil, server) = secure_pair().await;
let id = format!("xform-{}", std::process::id());
let evil_intro = FileIntro {
transfer_id: id.clone(),
file_name: "../../evil.txt".into(),
total_size: total,
};
let chunk = FileChunk {
transfer_id: id,
offset: 0,
total_size: total,
payload: payload.clone(),
};
let out2 = out.clone();
let receiver =
tokio::spawn(async move { run_recv(server, &out2, Duration::from_millis(400)).await });
evil.send(&evil_intro.encode()).await.unwrap();
evil.send(&chunk.encode()).await.unwrap();
let rx = receiver.await.unwrap().expect("recv driver must complete");
assert!(
rx.is_complete(),
"traversal-targeted transfer must still complete"
);
let landed = out.join("evil.txt");
assert!(
tokio::fs::metadata(&landed).await.is_ok(),
"file must land at the sanitized basename inside --out"
);
assert_eq!(tokio::fs::read(&landed).await.unwrap(), payload);
assert!(
tokio::fs::metadata(dir.join("evil.txt")).await.is_err(),
"no file may escape --out via ../"
);
tokio::fs::remove_dir_all(&dir).await.ok();
}
}