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
//! # aria2-core
//!
//! Core library for the aria2-rust download utility — a high-performance,
//! multi-protocol download manager rewritten in Rust.
//!
//! ## Supported Protocols & Features
//!
//! | Protocol / Feature | Status | Notes |
//! |---|---|---|
//! | HTTP / HTTPS | ✅ Full | Range requests, redirects, cookies, gzip/bzip2/chunked decoding |
//! | FTP / SFTP | ✅ Full | Passive/active mode, REST resume, LIST/MLSD parsing |
//! | BitTorrent | ✅ Full | Piece picker, choke algorithm, DHT, tracker (HTTP/UDP), seeding |
//! | Metalink | ✅ Full | v3/v4 parsing, multi-source, checksum verification |
//! | Auth: Basic (RFC 7617) | ✅ | Base64 credential encoding, HTTPS-only enforcement |
//! | Auth: Digest (RFC 7616) | ✅ | MD5/SHA256/SHA512 HA1→HA2→Response chain, nonce/qop/stale |
//! | LPD (BEP 14) | ✅ | UDP multicast peer discovery on 239.192.152.143:6771 |
//! | MSE (BEP 10) | ✅ | X25519 DH key exchange, RC4 encryption, plaintext fallback |
//! | Stream Filters | ✅ | Composable GZip/BZip2/Chunked decoder pipeline |
//! | Post-Download Hooks | ✅ | Move/Rename/Touch/Exec hook chain with env injection |
//! | BT Progress Persistence | ✅ | Atomic .aria2 file save/load, C++ format compatible |
//!
//! ## Module Overview
//!
//! - **[`config`]** — Configuration system with ~95 core options, multi-source
//! merging (defaults → env → file → CLI), `ConfigManager` runtime manager,
//! NetRC authentication parser, and URI list file parser.
//!
//! - **[`engine`]** — Shared event loop, task lifecycle, scheduling, and protocol
//! command assembly. Protocol-specific execution lives under `engine::http`,
//! `engine::ftp`, `engine::sftp`, `engine::bittorrent`, and `engine::metalink`.
//!
//! - **[`request`]** — Request management layer: `RequestGroupMan` (global task manager),
//! `RequestGroup` (per-task lifecycle: Waiting → Active → Paused → Complete/Error/Removed),
//! segment tracking, and bitfield management.
//!
//! - **[`auth`]** — HTTP authentication: [`BasicAuthProvider`](auth::basic_auth::BasicAuthProvider),
//! [`DigestAuthProvider`](auth::digest_auth::DigestAuthProvider), thread-safe
//! [`CredentialStore`](auth::credential_store::CredentialStore) with automatic secret zeroing.
//!
//! - **[`http`]** — HTTP request policy and reusable helpers for authentication,
//! redirects, cookies, response processing, TLS identity, and stream filters
//! ([`GzDecoder`](http::stream_filter::GzDecoder), [`ChunkedDecoder`](http::stream_filter::ChunkedDecoder)).
//!
//! - **[`ftp`]** — FTP control/data connection support, passive/active negotiation,
//! listing parsing, proxy handling, and connection pooling. SFTP lives in its
//! own protocol module.
//!
//! - **[`filesystem`]** — Disk I/O abstraction: `DiskAdaptor`, `DiskWriter`,
//! file pre-allocation strategies, write cache (LRU eviction), and checksum verification.
//!
//! - **[`ui`]** — Console UI components: `ProgressBar`, `MultiProgress` (multi-task summary),
//! `StatusPanel`, and formatting utilities (`format_size`, `format_speed`, `format_duration`).
//!
//! ## BitTorrent Library API
//!
//! BitTorrent task state and scheduling are exposed from this crate's root so
//! downstream users do not need to depend on the internal `engine` layout.
//! Use [`PiecePicker`] for task-level piece selection, [`PieceManager`] for
//! completion and hash accounting, [`PeerBitfieldTracker`] for peer
//! availability, and [`BtMessageValidator`] for validation against torrent
//! metadata.
//!
//! ```rust,no_run
//! fn bittorrent_library_example() {
//! #[cfg(feature = "bittorrent")]
//! {
//! use aria2_core::{
//! BtMessageValidator, PeerBitfieldTracker, PieceManager, PiecePicker,
//! PieceSelectionStrategy,
//! };
//!
//! let mut picker = PiecePicker::new(128);
//! picker.set_strategy(PieceSelectionStrategy::RarestFirst);
//! let mut peers = PeerBitfieldTracker::new(128);
//! peers.update_peer_bitfield("peer-1", &[0xff; 16]);
//!
//! let hashes = vec![[0u8; 20]; 128];
//! let manager = PieceManager::new(128, 262_144, 128 * 262_144, &hashes);
//! let validator = BtMessageValidator::new(manager.num_pieces(), manager.piece_length());
//! assert!(validator.validate_index(0).is_ok());
//! let _ = (picker, peers);
//! }
//! }
//! ```
//!
//! The companion `aria2-protocol` crate owns reusable protocol wire formats,
//! parsers, and clients, such as Bencode, BitTorrent messages, Handshake, and
//! `Bitfield`. `aria2-core::engine` assembles them with download policy,
//! request state, and storage.
//! Applications should import the task-facing types from `aria2_core` rather
//! than from `aria2_protocol`.
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use std::sync::Arc;
//!
//! use aria2_core::request::request_group::DownloadOptions;
//! use aria2_core::request::request_group_man::RequestGroupMan;
//! use aria2_core::DownloadEngine;
//!
//! #[tokio::main]
//! async fn main() {
//! let groups = Arc::new(RequestGroupMan::new());
//! let mut engine = DownloadEngine::new();
//! engine.set_request_group_man(Arc::clone(&groups));
//! let engine = engine.start().unwrap();
//!
//! let download = engine.downloads().add_uri(
//! vec!["http://example.com/file.zip".into()],
//! DownloadOptions::default(),
//! ).unwrap();
//! let result = download.wait().await.unwrap();
//! println!("{}: {}", download.gid_hex(), result.status);
//!
//! engine.shutdown_and_wait().await.unwrap();
//! }
//! ```
//!
//! Magnet downloads use the same handle and event stream. Metadata is a
//! notification rather than a `DownloadStatus` variant, so callers do not
//! need to parse messages or poll `getFiles`:
//!
//! ```rust,no_run
//! use std::sync::Arc;
//!
//! use aria2_core::request::request_group::DownloadOptions;
//! use aria2_core::request::request_group_man::RequestGroupMan;
//! use aria2_core::{DownloadEngine, DownloadNotification};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let groups = Arc::new(RequestGroupMan::new());
//! let mut engine = DownloadEngine::new();
//! engine.set_request_group_man(Arc::clone(&groups));
//! let engine = engine.start()?;
//!
//! let mut events = engine.downloads().subscribe();
//! let mut options = DownloadOptions::default();
//! options.dir = Some("./downloads".into());
//! options.out = None;
//! options.enable_dht = true;
//!
//! let download = engine.downloads().add_uri(
//! vec!["magnet:?xt=urn:btih:YOUR_INFO_HASH".into()],
//! options,
//! )?;
//!
//! let _metadata = events.recv_metadata_for(download.gid()).await?;
//! for file in download.get_files().unwrap_or_default() {
//! println!("{}: {} bytes", file.path, file.length);
//! }
//!
//! let _result = download.wait().await?;
//! engine.shutdown_and_wait().await?;
//! Ok(())
//! }
//! ```
// `async_trait` marks its boxed futures as `must_use`; Clippy 1.99 also sees
// the wrapped `Result` and flags the generated trait methods as double-must-use.
pub use dht;
// Re-export commonly used types for downstream crates.
// This avoids forcing consumers to depend on internal module paths.
pub use ;
pub use ;
pub use TorrentFileEntry;
pub use DownloadEngine;
pub use ;
pub use ;
pub use ;
pub use ;
/// Initialize the logging subsystem with optional file output.
///
/// Sets up `tracing-subscriber` with console output (colorized) and optionally
/// writes to a log file. When `log_max_size` is `Some`, size-based rotation is
/// used (keeping `log_max_files` rotated copies); otherwise daily time-based
/// rotation is used (controlled by `log_backup_count`).