1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! SFTP download execution logic.
//!
//! Executes one SFTP attempt: SSH connect, SFTP session init, remote file
//! inspection, chunked reads, and cleanup/finalize. Retry and command lifecycle
//! behavior lives in `command.rs`.
use std::future::Future;
use std::sync::Arc;
use std::time::Instant;
use tracing::{debug, error, info, warn};
use crate::checksum::checksum::Checksum;
use crate::constants;
use crate::engine::work_commit::SequentialWorkCommitter;
use crate::error::{Aria2Error, FatalError, Result};
use crate::filesystem::disk_writer::{DiskWriter, new_sequential_download_writer};
use crate::rate_limiter::{RateLimiter, RateLimiterConfig, ThrottledWriter};
use crate::request::request_group::ActiveConnectionGuard;
use crate::util::rwlock_ext::RwLockRecover;
use aria2_protocol::sftp::connection::SshConnection;
use aria2_protocol::sftp::file_ops::SftpFileOps;
use aria2_protocol::sftp::session::SftpSession;
use aria2_protocol::sftp::transfer::SftpDownloadReader;
use super::types::SftpDownloadCommand;
mod connection;
use connection::{connect_sftp_host, connect_with_timeout};
#[cfg(test)]
mod tests;
impl SftpDownloadCommand {
async fn await_with_lifecycle<T, F>(&self, future: F) -> Result<T>
where
F: Future<Output = Result<T>>,
{
let notifier = self.group.recover().lifecycle_notifier();
tokio::pin!(future);
loop {
let notified = notifier.notified();
tokio::pin!(notified);
notified.as_mut().enable();
self.check_cancelled()?;
tokio::select! {
biased;
_ = &mut notified => self.check_cancelled()?,
result = &mut future => return result,
}
}
}
pub(super) fn check_cancelled(&self) -> Result<()> {
let group = self.group.recover();
if group.is_removed() {
Err(Aria2Error::DownloadFailed(
"Download cancelled by user".into(),
))
} else if group.is_paused_flag() {
Err(Aria2Error::DownloadFailed("Download paused".into()))
} else if group.is_force_halt_requested() || group.is_halt_requested() {
Err(Aria2Error::DownloadFailed("SFTP download halted".into()))
} else {
Ok(())
}
}
/// Execute the SFTP download.
///
/// This is the main entry point called by the download engine. It orchestrates
/// the entire download lifecycle from connection establishment through data
/// transfer to cleanup.
pub(super) async fn execute_once(&mut self) -> Result<()> {
self.check_cancelled()?;
let connection_guard = ActiveConnectionGuard::new(Arc::clone(&self.group));
connection_guard.set(1);
// -----------------------------------------------------------------
// Phase 0: Initialization
// -----------------------------------------------------------------
if !self.started {
self.group.recover_mut().start()?;
self.started = true;
}
let in_memory_download = self.group.recover().is_in_memory_download();
debug!(
"[SFTP-CMD] Starting download: {}@{}:{} -> {}",
self.username,
self.host,
self.port,
self.output_path.display()
);
// Ensure output directory exists
if !in_memory_download
&& let Some(parent) = self.output_path.parent()
&& !parent.as_os_str().is_empty()
&& !parent.exists()
{
std::fs::create_dir_all(parent).map_err(|e| {
Aria2Error::Fatal(FatalError::Config(format!(
"Failed to create output directory: {}",
e
)))
})?;
}
// -----------------------------------------------------------------
// Phase 1: SSH Connection
// -----------------------------------------------------------------
let ssh_options = self.build_ssh_options();
let connect_timeout = ssh_options.connect_timeout;
let host = self.host.as_str();
let port = self.port;
let outbound_network_policy = Arc::clone(&self.outbound_network_policy);
let dns_cache = self.dns_cache.clone();
let host_for_error = self.host.clone();
let remote_path_for_error = self.remote_path.clone();
let conn_result = self
.await_with_lifecycle(async move {
connect_with_timeout(host, port, connect_timeout, async move {
let stream = connect_sftp_host(
host,
port,
dns_cache.as_deref(),
&outbound_network_policy,
)
.await?;
SshConnection::connect_with_stream(ssh_options, stream).await
})
.await
.map_err(|error| {
Self::map_ssh_error(&error, &host_for_error, port, &remote_path_for_error)
})
})
.await;
let mut conn = match conn_result {
Ok(c) => c,
Err(error) => return Err(error),
};
info!(
"[SFTP-CMD] SSH connected: {}@{}:{}",
self.username, self.host, self.port
);
// -----------------------------------------------------------------
// Phase 2: SFTP Session Initialization
// -----------------------------------------------------------------
let session_result = self
.await_with_lifecycle(async {
SftpSession::open(&mut conn)
.await
.map_err(|error| Self::map_session_error(&error))
})
.await;
let session: SftpSession = match session_result {
Ok(s) => s,
Err(error) => {
// Attempt graceful disconnect before returning error
let _ = conn.disconnect().await;
return Err(error);
}
};
debug!(
"[SFTP-CMD] SFTP session established (v{})",
session.server_version()
);
// -----------------------------------------------------------------
// Phase 3: Stat Remote File
// -----------------------------------------------------------------
let ops = SftpFileOps::new(&session);
let file_attrs = match self
.await_with_lifecycle(async {
ops.stat(&self.remote_path)
.await
.map_err(|error| Self::map_file_op_error(&error, &self.host, &self.remote_path))
})
.await
{
Ok(attrs) => attrs,
Err(error) => {
let _ = conn.disconnect().await;
return Err(error);
}
};
if !file_attrs.is_regular_file {
let _ = conn.disconnect().await;
return Err(Aria2Error::Fatal(FatalError::FileNotFound {
path: format!("{} (not a regular file)", self.remote_path),
}));
}
let total_length = file_attrs.size;
info!(
"[SFTP-CMD] Remote file size: {} bytes ({:.2} MB)",
total_length,
total_length as f64 / (1024.0 * 1024.0)
);
// Update RequestGroup with total length and recover a local prefix.
// SFTP reads are positioned, so an existing partial file can be resumed
// without downloading or rewriting its already-present prefix.
let existing_length = if in_memory_download {
0
} else {
tokio::fs::metadata(&self.output_path)
.await
.map(|metadata| metadata.len())
.unwrap_or(0)
};
let continue_download = self.group.recover().options().continue_download;
let checksum_config = self.group.recover().options().checksum.clone();
let complete_local_checksum_candidate =
!in_memory_download && existing_length == total_length && checksum_config.is_some();
let resume_input_length = if complete_local_checksum_candidate {
// aria2_original routes a complete local file with a configured
// checksum through ChecksumCheckIntegrityEntry even without
// `--continue`; only a failed check returns to remote download.
existing_length
} else {
crate::engine::progress_checkpoint::ProgressCheckpoint::resume_input_length(
&self.output_path,
existing_length,
continue_download,
total_length,
)
.await
};
Self::validate_resume_offset(resume_input_length, total_length)?;
if in_memory_download {
self.checkpoint = None;
self.completed_bytes = 0;
} else {
self.checkpoint = Some(
crate::engine::progress_checkpoint::ProgressCheckpoint::open(
&self.output_path,
total_length,
resume_input_length,
)
.await,
);
self.completed_bytes = self
.checkpoint
.as_ref()
.map(|checkpoint| checkpoint.resume_offset(resume_input_length))
.unwrap_or(resume_input_length);
}
{
let g = self.group.recover();
g.set_total_length(total_length);
g.update_progress(self.completed_bytes);
}
if complete_local_checksum_candidate && self.completed_bytes == total_length {
let (algorithm, expected) = checksum_config
.as_ref()
.expect("complete local checksum candidate has a checksum");
let checksum = Checksum::from_type_and_value(algorithm, expected)?;
if crate::checksum::check_integrity::man::enqueue_file_checksum_for_group(
&crate::checksum::check_integrity::man::shared(),
std::sync::Arc::clone(&self.group),
&self.output_path,
total_length,
checksum,
)
.await?
{
self.group.recover().set_checksum_verified(true);
self.group.recover().set_completed_length(total_length);
self.group.recover_mut().complete()?;
self.complete_checkpoint().await;
info!(
path = %self.output_path.display(),
size = total_length,
"SFTP target already matches remote size and checksum"
);
let _ = conn.disconnect().await;
return Ok(());
}
warn!(
path = %self.output_path.display(),
"SFTP target checksum mismatch; restarting from byte zero"
);
self.completed_bytes = 0;
if let Some(checkpoint) = self.checkpoint.as_mut() {
checkpoint.update(0, true).await;
}
}
// -----------------------------------------------------------------
// Phase 4: Open Remote File for Reading
// -----------------------------------------------------------------
let mut remote_reader = match self
.await_with_lifecycle(async {
SftpDownloadReader::open(
&ops,
&self.remote_path,
total_length,
self.completed_bytes,
constants::SFTP_DISK_WRITE_CHUNK_SIZE,
)
.await
.map_err(|error| Self::map_file_op_error(&error, &self.host, &self.remote_path))
})
.await
{
Ok(reader) => reader,
Err(error) => {
let _ = conn.disconnect().await;
return Err(error);
}
};
// -----------------------------------------------------------------
// Phase 5: Prepare Local Disk Writer
// -----------------------------------------------------------------
let raw_writer = new_sequential_download_writer(
&self.output_path,
in_memory_download,
self.completed_bytes,
Some(total_length),
);
// Apply rate limiting if configured
let rate_limit = {
let g = self.group.recover();
g.options().max_download_limit
};
// Global (process-wide) limiter: when present and enabled, the writer
// acquires tokens after the per-download limiter so all concurrent
// downloads share a single bandwidth ceiling.
let global_limited = self
.global_limiter
.as_ref()
.is_some_and(|g| g.is_download_limited());
let mut writer: Box<dyn DiskWriter> = if rate_limit.is_some() || global_limited {
let per_rate = rate_limit.filter(|&r| r > 0);
let limiter = per_rate
.map(|rate| RateLimiter::new(&RateLimiterConfig::new(Some(rate), None)))
.unwrap_or_else(RateLimiter::unlimited);
let mut tw = ThrottledWriter::new(raw_writer, limiter);
if let Some(ref gl) = self.global_limiter {
tw = tw.with_global_limiter(gl.clone());
}
Box::new(tw)
} else {
raw_writer
};
// -----------------------------------------------------------------
// Phase 6: Main Download Loop (Chunked Read + Write)
// -----------------------------------------------------------------
let start_time = Instant::now();
let mut last_speed_update = Instant::now();
let mut last_completed: u64 = 0;
info!("[SFTP-CMD] Starting transfer loop: {} bytes", total_length);
loop {
let halted = {
let group = self.group.recover();
group.is_removed() || group.is_force_halt_requested() || group.is_halt_requested()
};
if halted {
let halt_error = {
let group = self.group.recover();
if group.is_removed() {
"Download cancelled by user"
} else if group.is_paused_flag() {
"Download paused"
} else {
"SFTP download halted"
}
};
let _ = remote_reader.close().await;
self.finalize_partial_writer(&mut writer).await;
self.flush_checkpoint().await;
let _ = conn.disconnect().await;
return Err(Aria2Error::DownloadFailed(halt_error.into()));
}
if self.completed_bytes >= total_length {
break; // Download complete
}
// Retain the in-flight SFTP request across non-terminal lifecycle
// notifications. Dropping a request/response future poisons its
// session because the eventual response could not be correlated
// safely with a later operation.
let read_result = self
.await_with_lifecycle(async {
let result = remote_reader.read_next().await;
if let Err(error) = &result {
error!(
offset = self.completed_bytes,
%error,
"SFTP read failed"
);
}
Ok(result)
})
.await;
let data = match read_result {
Ok(Ok(Some(data))) => data,
Ok(Ok(None)) => break,
Ok(Err(error)) => {
let _ = remote_reader.close().await;
self.finalize_partial_writer(&mut writer).await;
let _ = conn.disconnect().await;
return Err(Self::map_download_read_error(
error,
&self.host,
&self.remote_path,
));
}
Err(error) => {
let _ = remote_reader.close().await;
self.finalize_partial_writer(&mut writer).await;
self.flush_checkpoint().await;
let _ = conn.disconnect().await;
return Err(error);
}
};
self.group.recover().record_network_activity();
// Core work output commits source chunks, progress, and
// checkpoints through the same ordered path used by other sources.
let write_result = {
let mut committer = SequentialWorkCommitter::new(
&mut writer,
&mut self.completed_bytes,
&self.group,
&mut self.checkpoint,
);
committer.commit_chunk(data.as_slice()).await
};
if let Err(error) = write_result {
error!("[SFTP-CMD] Disk write error: {}", error);
let _ = remote_reader.close().await;
self.finalize_partial_writer(&mut writer).await;
let _ = conn.disconnect().await;
return Err(Aria2Error::Fatal(FatalError::Config(format!(
"Disk write failed: {}",
error
))));
}
// Update download speed in RequestGroup.
{
let g = self.group.recover();
// Periodic speed calculation (every ~500ms)
let elapsed = last_speed_update.elapsed();
if elapsed.as_millis() >= constants::SFTP_SPEED_UPDATE_INTERVAL_MS as u128 {
let delta = self.completed_bytes - last_completed;
let speed = (delta as f64 / elapsed.as_secs_f64()) as u64;
g.update_speed(speed, 0);
last_speed_update = Instant::now();
last_completed = self.completed_bytes;
}
}
}
// -----------------------------------------------------------------
// Phase 7: Finalize and Cleanup
// -----------------------------------------------------------------
// Close remote file handle
if let Err(e) = remote_reader.close().await {
warn!("[SFTP-CMD] Warning closing remote file: {}", e);
}
// Finalize disk writer (flush, sync, etc.). Completion is not valid
// unless the local bytes have been durably finalized.
let mut finalized_data = match writer.finalize().await {
Ok(data) => data,
Err(error) => {
self.flush_checkpoint().await;
let _ = conn.disconnect().await;
return Err(Aria2Error::FileIo(format!(
"[SFTP-CMD] Failed to finalize disk writer: {error}"
)));
}
};
// aria2_original schedules ChecksumCheckIntegrityEntry after the
// SFTP transfer, including when the local output was already complete.
// Keep that verification at the Rust-owned completion seam so the
// output is never marked complete before its configured checksum is
// known to match.
if let Some((algorithm, expected)) = checksum_config {
let checksum = match Checksum::from_type_and_value(&algorithm, &expected) {
Ok(checksum) => checksum,
Err(error) => {
let _ = conn.disconnect().await;
return Err(error);
}
};
let verified = if in_memory_download {
let (data, verified) = checksum.verify_async(finalized_data).await?;
finalized_data = data;
verified
} else {
match crate::checksum::check_integrity::man::enqueue_file_checksum_for_group(
&crate::checksum::check_integrity::man::shared(),
std::sync::Arc::clone(&self.group),
&self.output_path,
self.completed_bytes,
checksum,
)
.await
{
Ok(verified) => verified,
Err(error) => {
self.flush_checkpoint().await;
let _ = conn.disconnect().await;
return Err(error);
}
}
};
if !verified {
self.flush_checkpoint().await;
let _ = conn.disconnect().await;
return Err(Aria2Error::Checksum(format!(
"{} checksum mismatch for {}",
algorithm,
self.output_path.display()
)));
}
self.group.recover().set_checksum_verified(true);
}
if in_memory_download {
let group = self.group.recover();
group.set_total_length(self.completed_bytes);
group.set_completed_length(self.completed_bytes);
group.set_in_memory_data(finalized_data);
}
// Disconnect SSH session
if let Err(e) = conn.disconnect().await {
warn!("[SFTP-CMD] Warning during SSH disconnect: {}", e);
}
self.complete_checkpoint().await;
// Calculate final statistics
let final_speed = {
let elapsed = start_time.elapsed().as_secs_f64();
if elapsed > 0.0 {
(self.completed_bytes as f64 / elapsed) as u64
} else {
0
}
};
// Mark RequestGroup as complete
{
let g = self.group.recover();
g.update_progress(self.completed_bytes);
g.update_speed(final_speed, 0);
drop(g);
let mut g = self.group.recover_mut();
g.complete()?;
}
info!(
"[SFTP-CMD] Download complete: {} ({} bytes, {:.1} KB/s)",
self.output_path.display(),
self.completed_bytes,
final_speed as f64 / 1024.0
);
Ok(())
}
}