├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md └── workflows │ ├── ci.yml │ └── release.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── progresslib ├── Cargo.toml └── src │ ├── lib.rs │ ├── progress.rs │ └── progress │ └── format.rs ├── samfuslib ├── Cargo.toml └── src │ ├── crypto.rs │ ├── fus.rs │ ├── lib.rs │ ├── range.rs │ └── version.rs └── src ├── file.rs ├── main.rs └── state.rs /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report an issue with samfusdl's functionality 4 | labels: 'bug' 5 | --- 6 | 7 | 12 | 13 | ### Description 14 | 15 | 16 | 17 | ### Command output 18 | 19 | ``` 20 | # Paste your download command here 21 | ``` 22 | 23 |
24 | Full debug output 25 | 26 | ``` 27 | # Rerun your download command with `--loglevel debug` and paste the full output here 28 | ``` 29 |
30 | 31 | ### Environment 32 | 33 | * OS platform and version: 34 | * samfusdl version: 35 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | blank_issues_enabled: false 3 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for improving samfusdl 4 | labels: 'enhancement' 5 | --- 6 | 7 | 10 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | jobs: 8 | build_and_upload: 9 | name: Build and archive artifacts 10 | runs-on: ${{ matrix.os }} 11 | env: 12 | CARGO_TERM_COLOR: always 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | os: [windows-latest, ubuntu-latest, macos-latest] 17 | steps: 18 | - name: Check out repository 19 | uses: actions/checkout@v2 20 | with: 21 | fetch-depth: 1 22 | 23 | - name: Get Rust LLVM target triple 24 | id: get_target 25 | shell: bash 26 | run: | 27 | echo -n 'name=' >> "${GITHUB_OUTPUT}" 28 | RUSTC_BOOTSTRAP=1 rustc -Z unstable-options --print target-spec-json \ 29 | | jq -r '."llvm-target"' \ 30 | >> "${GITHUB_OUTPUT}" 31 | 32 | - name: Install clippy 33 | run: rustup component add clippy 34 | 35 | - name: Run tests in debug mode 36 | env: 37 | RUST_BACKTRACE: 1 38 | # ENABLE_VIRTUAL_TERMINAL_PROCESSING does not work in GitHub Actions, 39 | # so set TERM to force crossterm to output ANSI sequences. 40 | TERM: xterm 41 | run: | 42 | cargo clippy --workspace -- -D warnings 43 | cargo test --workspace 44 | 45 | - name: Build in debug mode 46 | run: cargo build --verbose 47 | 48 | - name: Archive artifacts 49 | uses: actions/upload-artifact@v2 50 | with: 51 | name: samfusdl-${{ steps.get_target.outputs.name }} 52 | path: | 53 | target/debug/samfusdl.exe 54 | target/debug/samfusdl.pdb 55 | target/debug/samfusdl 56 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | --- 2 | on: 3 | push: 4 | # Uncomment to test against a branch 5 | #branches: 6 | # - ci 7 | tags: 8 | - 'v*' 9 | jobs: 10 | create_release: 11 | name: Create GitHub release 12 | runs-on: ubuntu-latest 13 | outputs: 14 | upload_url: ${{ steps.create_release.outputs.upload_url }} 15 | version: ${{ steps.get_version.outputs.version }} 16 | steps: 17 | - name: Get version from tag 18 | id: get_version 19 | run: | 20 | if [[ "${GITHUB_REF}" == refs/tags/* ]]; then 21 | version=${GITHUB_REF#refs/tags/v} 22 | else 23 | version=0.0.0-${GITHUB_REF#refs/heads/} 24 | fi 25 | echo "version=${version}" >> "${GITHUB_OUTPUT}" 26 | 27 | - name: Create release 28 | id: create_release 29 | uses: actions/create-release@latest 30 | env: 31 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 32 | with: 33 | tag_name: v${{ steps.get_version.outputs.version }} 34 | release_name: Version ${{ steps.get_version.outputs.version }} 35 | draft: false 36 | prerelease: false 37 | 38 | build_and_upload: 39 | name: Build and upload assets 40 | needs: create_release 41 | runs-on: ${{ matrix.os }} 42 | env: 43 | CARGO_TERM_COLOR: always 44 | strategy: 45 | fail-fast: false 46 | matrix: 47 | os: [windows-latest, ubuntu-latest, macos-latest] 48 | steps: 49 | - name: Check out repository 50 | uses: actions/checkout@v2 51 | with: 52 | fetch-depth: 1 53 | 54 | - name: Get Rust LLVM target triple 55 | id: get_target 56 | shell: bash 57 | run: | 58 | echo -n 'name=' >> "${GITHUB_OUTPUT}" 59 | RUSTC_BOOTSTRAP=1 rustc -Z unstable-options --print target-spec-json \ 60 | | jq -r '."llvm-target"' \ 61 | >> "${GITHUB_OUTPUT}" 62 | 63 | - name: Install clippy 64 | run: rustup component add clippy 65 | 66 | - name: Run tests in release mode 67 | env: 68 | RUST_BACKTRACE: 1 69 | # ENABLE_VIRTUAL_TERMINAL_PROCESSING does not work in GitHub Actions, 70 | # so set TERM to force crossterm to output ANSI sequences. 71 | TERM: xterm 72 | run: | 73 | cargo clippy --workspace --release -- -D warnings 74 | cargo test --workspace --release 75 | 76 | - name: Build in release mode 77 | run: cargo build --release --verbose 78 | 79 | - name: Strip release binary (non-Windows) 80 | if: matrix.os == 'ubuntu-latest' || matrix.os == 'macos-latest' 81 | run: strip target/release/samfusdl 82 | 83 | - name: Build archive 84 | shell: bash 85 | run: | 86 | base_name=samfusdl-${{ needs.create_release.outputs.version }}-${{ steps.get_target.outputs.name }} 87 | mkdir "${base_name}" 88 | cp {README.md,LICENSE} "${base_name}/" 89 | 90 | if [[ "${{ matrix.os }}" == windows-* ]]; then 91 | cp target/release/samfusdl.exe "${base_name}/" 92 | 7z a "${base_name}.zip" "${base_name}" 93 | echo "ASSET=${base_name}.zip" >> "${GITHUB_ENV}" 94 | else 95 | cp target/release/samfusdl "${base_name}/" 96 | tar -Jcvf "${base_name}.tar.xz" "${base_name}" 97 | echo "ASSET=${base_name}.tar.xz" >> "${GITHUB_ENV}" 98 | fi 99 | 100 | - name: Upload release assets 101 | uses: actions/upload-release-asset@v1.0.2 102 | env: 103 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 104 | with: 105 | upload_url: ${{ needs.create_release.outputs.upload_url }} 106 | asset_name: ${{ env.ASSET }} 107 | asset_path: ${{ env.ASSET }} 108 | asset_content_type: application/octet-stream 109 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "aes" 7 | version = "0.8.2" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "433cfd6710c9986c576a25ca913c39d66a6474107b406f34f91d4a8923395241" 10 | dependencies = [ 11 | "cfg-if", 12 | "cipher", 13 | "cpufeatures", 14 | ] 15 | 16 | [[package]] 17 | name = "aho-corasick" 18 | version = "1.0.1" 19 | source = "registry+https://github.com/rust-lang/crates.io-index" 20 | checksum = "67fc08ce920c31afb70f013dcce1bfc3a3195de6a228474e45e1f145b36f8d04" 21 | dependencies = [ 22 | "memchr", 23 | ] 24 | 25 | [[package]] 26 | name = "anstream" 27 | version = "0.3.2" 28 | source = "registry+https://github.com/rust-lang/crates.io-index" 29 | checksum = "0ca84f3628370c59db74ee214b3263d58f9aadd9b4fe7e711fd87dc452b7f163" 30 | dependencies = [ 31 | "anstyle", 32 | "anstyle-parse", 33 | "anstyle-query", 34 | "anstyle-wincon", 35 | "colorchoice", 36 | "is-terminal", 37 | "utf8parse", 38 | ] 39 | 40 | [[package]] 41 | name = "anstyle" 42 | version = "1.0.0" 43 | source = "registry+https://github.com/rust-lang/crates.io-index" 44 | checksum = "41ed9a86bf92ae6580e0a31281f65a1b1d867c0cc68d5346e2ae128dddfa6a7d" 45 | 46 | [[package]] 47 | name = "anstyle-parse" 48 | version = "0.2.0" 49 | source = "registry+https://github.com/rust-lang/crates.io-index" 50 | checksum = "e765fd216e48e067936442276d1d57399e37bce53c264d6fefbe298080cb57ee" 51 | dependencies = [ 52 | "utf8parse", 53 | ] 54 | 55 | [[package]] 56 | name = "anstyle-query" 57 | version = "1.0.0" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" 60 | dependencies = [ 61 | "windows-sys 0.48.0", 62 | ] 63 | 64 | [[package]] 65 | name = "anstyle-wincon" 66 | version = "1.0.1" 67 | source = "registry+https://github.com/rust-lang/crates.io-index" 68 | checksum = "180abfa45703aebe0093f79badacc01b8fd4ea2e35118747e5811127f926e188" 69 | dependencies = [ 70 | "anstyle", 71 | "windows-sys 0.48.0", 72 | ] 73 | 74 | [[package]] 75 | name = "anyhow" 76 | version = "1.0.71" 77 | source = "registry+https://github.com/rust-lang/crates.io-index" 78 | checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8" 79 | 80 | [[package]] 81 | name = "assert_matches" 82 | version = "1.5.0" 83 | source = "registry+https://github.com/rust-lang/crates.io-index" 84 | checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" 85 | 86 | [[package]] 87 | name = "autocfg" 88 | version = "1.1.0" 89 | source = "registry+https://github.com/rust-lang/crates.io-index" 90 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 91 | 92 | [[package]] 93 | name = "base64" 94 | version = "0.21.0" 95 | source = "registry+https://github.com/rust-lang/crates.io-index" 96 | checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a" 97 | 98 | [[package]] 99 | name = "bitflags" 100 | version = "1.3.2" 101 | source = "registry+https://github.com/rust-lang/crates.io-index" 102 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 103 | 104 | [[package]] 105 | name = "block-padding" 106 | version = "0.3.3" 107 | source = "registry+https://github.com/rust-lang/crates.io-index" 108 | checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" 109 | dependencies = [ 110 | "generic-array", 111 | ] 112 | 113 | [[package]] 114 | name = "bumpalo" 115 | version = "3.12.2" 116 | source = "registry+https://github.com/rust-lang/crates.io-index" 117 | checksum = "3c6ed94e98ecff0c12dd1b04c15ec0d7d9458ca8fe806cea6f12954efe74c63b" 118 | 119 | [[package]] 120 | name = "bytes" 121 | version = "1.4.0" 122 | source = "registry+https://github.com/rust-lang/crates.io-index" 123 | checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" 124 | 125 | [[package]] 126 | name = "cbc" 127 | version = "0.1.2" 128 | source = "registry+https://github.com/rust-lang/crates.io-index" 129 | checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" 130 | dependencies = [ 131 | "cipher", 132 | ] 133 | 134 | [[package]] 135 | name = "cc" 136 | version = "1.0.79" 137 | source = "registry+https://github.com/rust-lang/crates.io-index" 138 | checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" 139 | 140 | [[package]] 141 | name = "cfg-if" 142 | version = "1.0.0" 143 | source = "registry+https://github.com/rust-lang/crates.io-index" 144 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 145 | 146 | [[package]] 147 | name = "cipher" 148 | version = "0.4.4" 149 | source = "registry+https://github.com/rust-lang/crates.io-index" 150 | checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" 151 | dependencies = [ 152 | "crypto-common", 153 | "inout", 154 | ] 155 | 156 | [[package]] 157 | name = "clap" 158 | version = "4.3.0" 159 | source = "registry+https://github.com/rust-lang/crates.io-index" 160 | checksum = "93aae7a4192245f70fe75dd9157fc7b4a5bf53e88d30bd4396f7d8f9284d5acc" 161 | dependencies = [ 162 | "clap_builder", 163 | "clap_derive", 164 | "once_cell", 165 | ] 166 | 167 | [[package]] 168 | name = "clap_builder" 169 | version = "4.3.0" 170 | source = "registry+https://github.com/rust-lang/crates.io-index" 171 | checksum = "4f423e341edefb78c9caba2d9c7f7687d0e72e89df3ce3394554754393ac3990" 172 | dependencies = [ 173 | "anstream", 174 | "anstyle", 175 | "bitflags", 176 | "clap_lex", 177 | "strsim", 178 | ] 179 | 180 | [[package]] 181 | name = "clap_derive" 182 | version = "4.3.0" 183 | source = "registry+https://github.com/rust-lang/crates.io-index" 184 | checksum = "191d9573962933b4027f932c600cd252ce27a8ad5979418fe78e43c07996f27b" 185 | dependencies = [ 186 | "heck", 187 | "proc-macro2", 188 | "quote", 189 | "syn", 190 | ] 191 | 192 | [[package]] 193 | name = "clap_lex" 194 | version = "0.5.0" 195 | source = "registry+https://github.com/rust-lang/crates.io-index" 196 | checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" 197 | 198 | [[package]] 199 | name = "colorchoice" 200 | version = "1.0.0" 201 | source = "registry+https://github.com/rust-lang/crates.io-index" 202 | checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" 203 | 204 | [[package]] 205 | name = "cookie" 206 | version = "0.16.2" 207 | source = "registry+https://github.com/rust-lang/crates.io-index" 208 | checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" 209 | dependencies = [ 210 | "percent-encoding", 211 | "time", 212 | "version_check", 213 | ] 214 | 215 | [[package]] 216 | name = "cookie_store" 217 | version = "0.16.1" 218 | source = "registry+https://github.com/rust-lang/crates.io-index" 219 | checksum = "2e4b6aa369f41f5faa04bb80c9b1f4216ea81646ed6124d76ba5c49a7aafd9cd" 220 | dependencies = [ 221 | "cookie", 222 | "idna 0.2.3", 223 | "log", 224 | "publicsuffix", 225 | "serde", 226 | "serde_json", 227 | "time", 228 | "url", 229 | ] 230 | 231 | [[package]] 232 | name = "core-foundation" 233 | version = "0.9.3" 234 | source = "registry+https://github.com/rust-lang/crates.io-index" 235 | checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" 236 | dependencies = [ 237 | "core-foundation-sys", 238 | "libc", 239 | ] 240 | 241 | [[package]] 242 | name = "core-foundation-sys" 243 | version = "0.8.4" 244 | source = "registry+https://github.com/rust-lang/crates.io-index" 245 | checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" 246 | 247 | [[package]] 248 | name = "cpufeatures" 249 | version = "0.2.7" 250 | source = "registry+https://github.com/rust-lang/crates.io-index" 251 | checksum = "3e4c1eaa2012c47becbbad2ab175484c2a84d1185b566fb2cc5b8707343dfe58" 252 | dependencies = [ 253 | "libc", 254 | ] 255 | 256 | [[package]] 257 | name = "crc32fast" 258 | version = "1.3.2" 259 | source = "registry+https://github.com/rust-lang/crates.io-index" 260 | checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" 261 | dependencies = [ 262 | "cfg-if", 263 | ] 264 | 265 | [[package]] 266 | name = "crossterm" 267 | version = "0.26.1" 268 | source = "registry+https://github.com/rust-lang/crates.io-index" 269 | checksum = "a84cda67535339806297f1b331d6dd6320470d2a0fe65381e79ee9e156dd3d13" 270 | dependencies = [ 271 | "bitflags", 272 | "crossterm_winapi", 273 | "libc", 274 | "mio", 275 | "parking_lot", 276 | "signal-hook", 277 | "signal-hook-mio", 278 | "winapi", 279 | ] 280 | 281 | [[package]] 282 | name = "crossterm_winapi" 283 | version = "0.9.0" 284 | source = "registry+https://github.com/rust-lang/crates.io-index" 285 | checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c" 286 | dependencies = [ 287 | "winapi", 288 | ] 289 | 290 | [[package]] 291 | name = "crypto-common" 292 | version = "0.1.6" 293 | source = "registry+https://github.com/rust-lang/crates.io-index" 294 | checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" 295 | dependencies = [ 296 | "generic-array", 297 | "typenum", 298 | ] 299 | 300 | [[package]] 301 | name = "dirs" 302 | version = "5.0.1" 303 | source = "registry+https://github.com/rust-lang/crates.io-index" 304 | checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" 305 | dependencies = [ 306 | "dirs-sys", 307 | ] 308 | 309 | [[package]] 310 | name = "dirs-sys" 311 | version = "0.4.1" 312 | source = "registry+https://github.com/rust-lang/crates.io-index" 313 | checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" 314 | dependencies = [ 315 | "libc", 316 | "option-ext", 317 | "redox_users", 318 | "windows-sys 0.48.0", 319 | ] 320 | 321 | [[package]] 322 | name = "encoding_rs" 323 | version = "0.8.32" 324 | source = "registry+https://github.com/rust-lang/crates.io-index" 325 | checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394" 326 | dependencies = [ 327 | "cfg-if", 328 | ] 329 | 330 | [[package]] 331 | name = "env_logger" 332 | version = "0.10.0" 333 | source = "registry+https://github.com/rust-lang/crates.io-index" 334 | checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" 335 | dependencies = [ 336 | "humantime", 337 | "is-terminal", 338 | "log", 339 | "regex", 340 | "termcolor", 341 | ] 342 | 343 | [[package]] 344 | name = "errno" 345 | version = "0.3.1" 346 | source = "registry+https://github.com/rust-lang/crates.io-index" 347 | checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" 348 | dependencies = [ 349 | "errno-dragonfly", 350 | "libc", 351 | "windows-sys 0.48.0", 352 | ] 353 | 354 | [[package]] 355 | name = "errno-dragonfly" 356 | version = "0.1.2" 357 | source = "registry+https://github.com/rust-lang/crates.io-index" 358 | checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" 359 | dependencies = [ 360 | "cc", 361 | "libc", 362 | ] 363 | 364 | [[package]] 365 | name = "fastrand" 366 | version = "1.9.0" 367 | source = "registry+https://github.com/rust-lang/crates.io-index" 368 | checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" 369 | dependencies = [ 370 | "instant", 371 | ] 372 | 373 | [[package]] 374 | name = "fnv" 375 | version = "1.0.7" 376 | source = "registry+https://github.com/rust-lang/crates.io-index" 377 | checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" 378 | 379 | [[package]] 380 | name = "foreign-types" 381 | version = "0.3.2" 382 | source = "registry+https://github.com/rust-lang/crates.io-index" 383 | checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" 384 | dependencies = [ 385 | "foreign-types-shared", 386 | ] 387 | 388 | [[package]] 389 | name = "foreign-types-shared" 390 | version = "0.1.1" 391 | source = "registry+https://github.com/rust-lang/crates.io-index" 392 | checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" 393 | 394 | [[package]] 395 | name = "form_urlencoded" 396 | version = "1.1.0" 397 | source = "registry+https://github.com/rust-lang/crates.io-index" 398 | checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" 399 | dependencies = [ 400 | "percent-encoding", 401 | ] 402 | 403 | [[package]] 404 | name = "futures-channel" 405 | version = "0.3.28" 406 | source = "registry+https://github.com/rust-lang/crates.io-index" 407 | checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" 408 | dependencies = [ 409 | "futures-core", 410 | ] 411 | 412 | [[package]] 413 | name = "futures-core" 414 | version = "0.3.28" 415 | source = "registry+https://github.com/rust-lang/crates.io-index" 416 | checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" 417 | 418 | [[package]] 419 | name = "futures-io" 420 | version = "0.3.28" 421 | source = "registry+https://github.com/rust-lang/crates.io-index" 422 | checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" 423 | 424 | [[package]] 425 | name = "futures-macro" 426 | version = "0.3.28" 427 | source = "registry+https://github.com/rust-lang/crates.io-index" 428 | checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" 429 | dependencies = [ 430 | "proc-macro2", 431 | "quote", 432 | "syn", 433 | ] 434 | 435 | [[package]] 436 | name = "futures-sink" 437 | version = "0.3.28" 438 | source = "registry+https://github.com/rust-lang/crates.io-index" 439 | checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" 440 | 441 | [[package]] 442 | name = "futures-task" 443 | version = "0.3.28" 444 | source = "registry+https://github.com/rust-lang/crates.io-index" 445 | checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" 446 | 447 | [[package]] 448 | name = "futures-util" 449 | version = "0.3.28" 450 | source = "registry+https://github.com/rust-lang/crates.io-index" 451 | checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" 452 | dependencies = [ 453 | "futures-core", 454 | "futures-io", 455 | "futures-macro", 456 | "futures-sink", 457 | "futures-task", 458 | "memchr", 459 | "pin-project-lite", 460 | "pin-utils", 461 | "slab", 462 | ] 463 | 464 | [[package]] 465 | name = "generic-array" 466 | version = "0.14.7" 467 | source = "registry+https://github.com/rust-lang/crates.io-index" 468 | checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" 469 | dependencies = [ 470 | "typenum", 471 | "version_check", 472 | ] 473 | 474 | [[package]] 475 | name = "getrandom" 476 | version = "0.2.9" 477 | source = "registry+https://github.com/rust-lang/crates.io-index" 478 | checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4" 479 | dependencies = [ 480 | "cfg-if", 481 | "libc", 482 | "wasi", 483 | ] 484 | 485 | [[package]] 486 | name = "h2" 487 | version = "0.3.19" 488 | source = "registry+https://github.com/rust-lang/crates.io-index" 489 | checksum = "d357c7ae988e7d2182f7d7871d0b963962420b0678b0997ce7de72001aeab782" 490 | dependencies = [ 491 | "bytes", 492 | "fnv", 493 | "futures-core", 494 | "futures-sink", 495 | "futures-util", 496 | "http", 497 | "indexmap", 498 | "slab", 499 | "tokio", 500 | "tokio-util", 501 | "tracing", 502 | ] 503 | 504 | [[package]] 505 | name = "hashbrown" 506 | version = "0.12.3" 507 | source = "registry+https://github.com/rust-lang/crates.io-index" 508 | checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" 509 | 510 | [[package]] 511 | name = "heck" 512 | version = "0.4.1" 513 | source = "registry+https://github.com/rust-lang/crates.io-index" 514 | checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" 515 | 516 | [[package]] 517 | name = "hermit-abi" 518 | version = "0.2.6" 519 | source = "registry+https://github.com/rust-lang/crates.io-index" 520 | checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" 521 | dependencies = [ 522 | "libc", 523 | ] 524 | 525 | [[package]] 526 | name = "hermit-abi" 527 | version = "0.3.1" 528 | source = "registry+https://github.com/rust-lang/crates.io-index" 529 | checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" 530 | 531 | [[package]] 532 | name = "hex-literal" 533 | version = "0.4.1" 534 | source = "registry+https://github.com/rust-lang/crates.io-index" 535 | checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" 536 | 537 | [[package]] 538 | name = "http" 539 | version = "0.2.9" 540 | source = "registry+https://github.com/rust-lang/crates.io-index" 541 | checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" 542 | dependencies = [ 543 | "bytes", 544 | "fnv", 545 | "itoa", 546 | ] 547 | 548 | [[package]] 549 | name = "http-body" 550 | version = "0.4.5" 551 | source = "registry+https://github.com/rust-lang/crates.io-index" 552 | checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" 553 | dependencies = [ 554 | "bytes", 555 | "http", 556 | "pin-project-lite", 557 | ] 558 | 559 | [[package]] 560 | name = "httparse" 561 | version = "1.8.0" 562 | source = "registry+https://github.com/rust-lang/crates.io-index" 563 | checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" 564 | 565 | [[package]] 566 | name = "httpdate" 567 | version = "1.0.2" 568 | source = "registry+https://github.com/rust-lang/crates.io-index" 569 | checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" 570 | 571 | [[package]] 572 | name = "humantime" 573 | version = "2.1.0" 574 | source = "registry+https://github.com/rust-lang/crates.io-index" 575 | checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" 576 | 577 | [[package]] 578 | name = "hyper" 579 | version = "0.14.26" 580 | source = "registry+https://github.com/rust-lang/crates.io-index" 581 | checksum = "ab302d72a6f11a3b910431ff93aae7e773078c769f0a3ef15fb9ec692ed147d4" 582 | dependencies = [ 583 | "bytes", 584 | "futures-channel", 585 | "futures-core", 586 | "futures-util", 587 | "h2", 588 | "http", 589 | "http-body", 590 | "httparse", 591 | "httpdate", 592 | "itoa", 593 | "pin-project-lite", 594 | "socket2", 595 | "tokio", 596 | "tower-service", 597 | "tracing", 598 | "want", 599 | ] 600 | 601 | [[package]] 602 | name = "hyper-tls" 603 | version = "0.5.0" 604 | source = "registry+https://github.com/rust-lang/crates.io-index" 605 | checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" 606 | dependencies = [ 607 | "bytes", 608 | "hyper", 609 | "native-tls", 610 | "tokio", 611 | "tokio-native-tls", 612 | ] 613 | 614 | [[package]] 615 | name = "idna" 616 | version = "0.2.3" 617 | source = "registry+https://github.com/rust-lang/crates.io-index" 618 | checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" 619 | dependencies = [ 620 | "matches", 621 | "unicode-bidi", 622 | "unicode-normalization", 623 | ] 624 | 625 | [[package]] 626 | name = "idna" 627 | version = "0.3.0" 628 | source = "registry+https://github.com/rust-lang/crates.io-index" 629 | checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" 630 | dependencies = [ 631 | "unicode-bidi", 632 | "unicode-normalization", 633 | ] 634 | 635 | [[package]] 636 | name = "indexmap" 637 | version = "1.9.3" 638 | source = "registry+https://github.com/rust-lang/crates.io-index" 639 | checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" 640 | dependencies = [ 641 | "autocfg", 642 | "hashbrown", 643 | ] 644 | 645 | [[package]] 646 | name = "inout" 647 | version = "0.1.3" 648 | source = "registry+https://github.com/rust-lang/crates.io-index" 649 | checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" 650 | dependencies = [ 651 | "block-padding", 652 | "generic-array", 653 | ] 654 | 655 | [[package]] 656 | name = "instant" 657 | version = "0.1.12" 658 | source = "registry+https://github.com/rust-lang/crates.io-index" 659 | checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" 660 | dependencies = [ 661 | "cfg-if", 662 | ] 663 | 664 | [[package]] 665 | name = "io-lifetimes" 666 | version = "1.0.10" 667 | source = "registry+https://github.com/rust-lang/crates.io-index" 668 | checksum = "9c66c74d2ae7e79a5a8f7ac924adbe38ee42a859c6539ad869eb51f0b52dc220" 669 | dependencies = [ 670 | "hermit-abi 0.3.1", 671 | "libc", 672 | "windows-sys 0.48.0", 673 | ] 674 | 675 | [[package]] 676 | name = "ipnet" 677 | version = "2.7.2" 678 | source = "registry+https://github.com/rust-lang/crates.io-index" 679 | checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" 680 | 681 | [[package]] 682 | name = "is-terminal" 683 | version = "0.4.7" 684 | source = "registry+https://github.com/rust-lang/crates.io-index" 685 | checksum = "adcf93614601c8129ddf72e2d5633df827ba6551541c6d8c59520a371475be1f" 686 | dependencies = [ 687 | "hermit-abi 0.3.1", 688 | "io-lifetimes", 689 | "rustix", 690 | "windows-sys 0.48.0", 691 | ] 692 | 693 | [[package]] 694 | name = "itoa" 695 | version = "1.0.6" 696 | source = "registry+https://github.com/rust-lang/crates.io-index" 697 | checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" 698 | 699 | [[package]] 700 | name = "js-sys" 701 | version = "0.3.63" 702 | source = "registry+https://github.com/rust-lang/crates.io-index" 703 | checksum = "2f37a4a5928311ac501dee68b3c7613a1037d0edb30c8e5427bd832d55d1b790" 704 | dependencies = [ 705 | "wasm-bindgen", 706 | ] 707 | 708 | [[package]] 709 | name = "lazy_static" 710 | version = "1.4.0" 711 | source = "registry+https://github.com/rust-lang/crates.io-index" 712 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 713 | 714 | [[package]] 715 | name = "libc" 716 | version = "0.2.144" 717 | source = "registry+https://github.com/rust-lang/crates.io-index" 718 | checksum = "2b00cc1c228a6782d0f076e7b232802e0c5689d41bb5df366f2a6b6621cfdfe1" 719 | 720 | [[package]] 721 | name = "linux-raw-sys" 722 | version = "0.3.8" 723 | source = "registry+https://github.com/rust-lang/crates.io-index" 724 | checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" 725 | 726 | [[package]] 727 | name = "lock_api" 728 | version = "0.4.9" 729 | source = "registry+https://github.com/rust-lang/crates.io-index" 730 | checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" 731 | dependencies = [ 732 | "autocfg", 733 | "scopeguard", 734 | ] 735 | 736 | [[package]] 737 | name = "log" 738 | version = "0.4.17" 739 | source = "registry+https://github.com/rust-lang/crates.io-index" 740 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 741 | dependencies = [ 742 | "cfg-if", 743 | ] 744 | 745 | [[package]] 746 | name = "matches" 747 | version = "0.1.10" 748 | source = "registry+https://github.com/rust-lang/crates.io-index" 749 | checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" 750 | 751 | [[package]] 752 | name = "md5" 753 | version = "0.7.0" 754 | source = "registry+https://github.com/rust-lang/crates.io-index" 755 | checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" 756 | 757 | [[package]] 758 | name = "memchr" 759 | version = "2.5.0" 760 | source = "registry+https://github.com/rust-lang/crates.io-index" 761 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 762 | 763 | [[package]] 764 | name = "memoffset" 765 | version = "0.9.0" 766 | source = "registry+https://github.com/rust-lang/crates.io-index" 767 | checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" 768 | dependencies = [ 769 | "autocfg", 770 | ] 771 | 772 | [[package]] 773 | name = "mime" 774 | version = "0.3.17" 775 | source = "registry+https://github.com/rust-lang/crates.io-index" 776 | checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" 777 | 778 | [[package]] 779 | name = "mio" 780 | version = "0.8.6" 781 | source = "registry+https://github.com/rust-lang/crates.io-index" 782 | checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9" 783 | dependencies = [ 784 | "libc", 785 | "log", 786 | "wasi", 787 | "windows-sys 0.45.0", 788 | ] 789 | 790 | [[package]] 791 | name = "native-tls" 792 | version = "0.2.11" 793 | source = "registry+https://github.com/rust-lang/crates.io-index" 794 | checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" 795 | dependencies = [ 796 | "lazy_static", 797 | "libc", 798 | "log", 799 | "openssl", 800 | "openssl-probe", 801 | "openssl-sys", 802 | "schannel", 803 | "security-framework", 804 | "security-framework-sys", 805 | "tempfile", 806 | ] 807 | 808 | [[package]] 809 | name = "num_cpus" 810 | version = "1.15.0" 811 | source = "registry+https://github.com/rust-lang/crates.io-index" 812 | checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" 813 | dependencies = [ 814 | "hermit-abi 0.2.6", 815 | "libc", 816 | ] 817 | 818 | [[package]] 819 | name = "number_prefix" 820 | version = "0.4.0" 821 | source = "registry+https://github.com/rust-lang/crates.io-index" 822 | checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" 823 | 824 | [[package]] 825 | name = "once_cell" 826 | version = "1.17.1" 827 | source = "registry+https://github.com/rust-lang/crates.io-index" 828 | checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" 829 | 830 | [[package]] 831 | name = "openssl" 832 | version = "0.10.52" 833 | source = "registry+https://github.com/rust-lang/crates.io-index" 834 | checksum = "01b8574602df80f7b85fdfc5392fa884a4e3b3f4f35402c070ab34c3d3f78d56" 835 | dependencies = [ 836 | "bitflags", 837 | "cfg-if", 838 | "foreign-types", 839 | "libc", 840 | "once_cell", 841 | "openssl-macros", 842 | "openssl-sys", 843 | ] 844 | 845 | [[package]] 846 | name = "openssl-macros" 847 | version = "0.1.1" 848 | source = "registry+https://github.com/rust-lang/crates.io-index" 849 | checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" 850 | dependencies = [ 851 | "proc-macro2", 852 | "quote", 853 | "syn", 854 | ] 855 | 856 | [[package]] 857 | name = "openssl-probe" 858 | version = "0.1.5" 859 | source = "registry+https://github.com/rust-lang/crates.io-index" 860 | checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" 861 | 862 | [[package]] 863 | name = "openssl-sys" 864 | version = "0.9.87" 865 | source = "registry+https://github.com/rust-lang/crates.io-index" 866 | checksum = "8e17f59264b2809d77ae94f0e1ebabc434773f370d6ca667bd223ea10e06cc7e" 867 | dependencies = [ 868 | "cc", 869 | "libc", 870 | "pkg-config", 871 | "vcpkg", 872 | ] 873 | 874 | [[package]] 875 | name = "option-ext" 876 | version = "0.2.0" 877 | source = "registry+https://github.com/rust-lang/crates.io-index" 878 | checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" 879 | 880 | [[package]] 881 | name = "parking_lot" 882 | version = "0.12.1" 883 | source = "registry+https://github.com/rust-lang/crates.io-index" 884 | checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" 885 | dependencies = [ 886 | "lock_api", 887 | "parking_lot_core", 888 | ] 889 | 890 | [[package]] 891 | name = "parking_lot_core" 892 | version = "0.9.7" 893 | source = "registry+https://github.com/rust-lang/crates.io-index" 894 | checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" 895 | dependencies = [ 896 | "cfg-if", 897 | "libc", 898 | "redox_syscall 0.2.16", 899 | "smallvec", 900 | "windows-sys 0.45.0", 901 | ] 902 | 903 | [[package]] 904 | name = "percent-encoding" 905 | version = "2.2.0" 906 | source = "registry+https://github.com/rust-lang/crates.io-index" 907 | checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" 908 | 909 | [[package]] 910 | name = "pin-project-lite" 911 | version = "0.2.9" 912 | source = "registry+https://github.com/rust-lang/crates.io-index" 913 | checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" 914 | 915 | [[package]] 916 | name = "pin-utils" 917 | version = "0.1.0" 918 | source = "registry+https://github.com/rust-lang/crates.io-index" 919 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" 920 | 921 | [[package]] 922 | name = "pkg-config" 923 | version = "0.3.27" 924 | source = "registry+https://github.com/rust-lang/crates.io-index" 925 | checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" 926 | 927 | [[package]] 928 | name = "proc-macro2" 929 | version = "1.0.58" 930 | source = "registry+https://github.com/rust-lang/crates.io-index" 931 | checksum = "fa1fb82fc0c281dd9671101b66b771ebbe1eaf967b96ac8740dcba4b70005ca8" 932 | dependencies = [ 933 | "unicode-ident", 934 | ] 935 | 936 | [[package]] 937 | name = "progresslib" 938 | version = "0.1.6" 939 | dependencies = [ 940 | "crossterm", 941 | "number_prefix", 942 | ] 943 | 944 | [[package]] 945 | name = "psl-types" 946 | version = "2.0.11" 947 | source = "registry+https://github.com/rust-lang/crates.io-index" 948 | checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" 949 | 950 | [[package]] 951 | name = "publicsuffix" 952 | version = "2.2.3" 953 | source = "registry+https://github.com/rust-lang/crates.io-index" 954 | checksum = "96a8c1bda5ae1af7f99a2962e49df150414a43d62404644d98dd5c3a93d07457" 955 | dependencies = [ 956 | "idna 0.3.0", 957 | "psl-types", 958 | ] 959 | 960 | [[package]] 961 | name = "quote" 962 | version = "1.0.27" 963 | source = "registry+https://github.com/rust-lang/crates.io-index" 964 | checksum = "8f4f29d145265ec1c483c7c654450edde0bfe043d3938d6972630663356d9500" 965 | dependencies = [ 966 | "proc-macro2", 967 | ] 968 | 969 | [[package]] 970 | name = "redox_syscall" 971 | version = "0.2.16" 972 | source = "registry+https://github.com/rust-lang/crates.io-index" 973 | checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" 974 | dependencies = [ 975 | "bitflags", 976 | ] 977 | 978 | [[package]] 979 | name = "redox_syscall" 980 | version = "0.3.5" 981 | source = "registry+https://github.com/rust-lang/crates.io-index" 982 | checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" 983 | dependencies = [ 984 | "bitflags", 985 | ] 986 | 987 | [[package]] 988 | name = "redox_users" 989 | version = "0.4.3" 990 | source = "registry+https://github.com/rust-lang/crates.io-index" 991 | checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" 992 | dependencies = [ 993 | "getrandom", 994 | "redox_syscall 0.2.16", 995 | "thiserror", 996 | ] 997 | 998 | [[package]] 999 | name = "regex" 1000 | version = "1.8.1" 1001 | source = "registry+https://github.com/rust-lang/crates.io-index" 1002 | checksum = "af83e617f331cc6ae2da5443c602dfa5af81e517212d9d611a5b3ba1777b5370" 1003 | dependencies = [ 1004 | "aho-corasick", 1005 | "memchr", 1006 | "regex-syntax", 1007 | ] 1008 | 1009 | [[package]] 1010 | name = "regex-syntax" 1011 | version = "0.7.1" 1012 | source = "registry+https://github.com/rust-lang/crates.io-index" 1013 | checksum = "a5996294f19bd3aae0453a862ad728f60e6600695733dd5df01da90c54363a3c" 1014 | 1015 | [[package]] 1016 | name = "reqwest" 1017 | version = "0.11.18" 1018 | source = "registry+https://github.com/rust-lang/crates.io-index" 1019 | checksum = "cde824a14b7c14f85caff81225f411faacc04a2013f41670f41443742b1c1c55" 1020 | dependencies = [ 1021 | "base64", 1022 | "bytes", 1023 | "cookie", 1024 | "cookie_store", 1025 | "encoding_rs", 1026 | "futures-core", 1027 | "futures-util", 1028 | "h2", 1029 | "http", 1030 | "http-body", 1031 | "hyper", 1032 | "hyper-tls", 1033 | "ipnet", 1034 | "js-sys", 1035 | "log", 1036 | "mime", 1037 | "native-tls", 1038 | "once_cell", 1039 | "percent-encoding", 1040 | "pin-project-lite", 1041 | "serde", 1042 | "serde_json", 1043 | "serde_urlencoded", 1044 | "tokio", 1045 | "tokio-native-tls", 1046 | "tokio-util", 1047 | "tower-service", 1048 | "url", 1049 | "wasm-bindgen", 1050 | "wasm-bindgen-futures", 1051 | "wasm-streams", 1052 | "web-sys", 1053 | "winreg", 1054 | ] 1055 | 1056 | [[package]] 1057 | name = "rustix" 1058 | version = "0.37.19" 1059 | source = "registry+https://github.com/rust-lang/crates.io-index" 1060 | checksum = "acf8729d8542766f1b2cf77eb034d52f40d375bb8b615d0b147089946e16613d" 1061 | dependencies = [ 1062 | "bitflags", 1063 | "errno", 1064 | "io-lifetimes", 1065 | "libc", 1066 | "linux-raw-sys", 1067 | "windows-sys 0.48.0", 1068 | ] 1069 | 1070 | [[package]] 1071 | name = "ryu" 1072 | version = "1.0.13" 1073 | source = "registry+https://github.com/rust-lang/crates.io-index" 1074 | checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" 1075 | 1076 | [[package]] 1077 | name = "samfusdl" 1078 | version = "0.1.10" 1079 | dependencies = [ 1080 | "anyhow", 1081 | "clap", 1082 | "crc32fast", 1083 | "dirs", 1084 | "env_logger", 1085 | "log", 1086 | "memoffset", 1087 | "progresslib", 1088 | "samfuslib", 1089 | "serde", 1090 | "serde_json", 1091 | "tokio", 1092 | "tokio-stream", 1093 | "winapi", 1094 | ] 1095 | 1096 | [[package]] 1097 | name = "samfuslib" 1098 | version = "0.1.6" 1099 | dependencies = [ 1100 | "aes", 1101 | "assert_matches", 1102 | "base64", 1103 | "block-padding", 1104 | "bytes", 1105 | "cbc", 1106 | "cipher", 1107 | "futures-core", 1108 | "hex-literal", 1109 | "log", 1110 | "md5", 1111 | "reqwest", 1112 | "thiserror", 1113 | "xmltree", 1114 | ] 1115 | 1116 | [[package]] 1117 | name = "schannel" 1118 | version = "0.1.21" 1119 | source = "registry+https://github.com/rust-lang/crates.io-index" 1120 | checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3" 1121 | dependencies = [ 1122 | "windows-sys 0.42.0", 1123 | ] 1124 | 1125 | [[package]] 1126 | name = "scopeguard" 1127 | version = "1.1.0" 1128 | source = "registry+https://github.com/rust-lang/crates.io-index" 1129 | checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" 1130 | 1131 | [[package]] 1132 | name = "security-framework" 1133 | version = "2.9.1" 1134 | source = "registry+https://github.com/rust-lang/crates.io-index" 1135 | checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8" 1136 | dependencies = [ 1137 | "bitflags", 1138 | "core-foundation", 1139 | "core-foundation-sys", 1140 | "libc", 1141 | "security-framework-sys", 1142 | ] 1143 | 1144 | [[package]] 1145 | name = "security-framework-sys" 1146 | version = "2.9.0" 1147 | source = "registry+https://github.com/rust-lang/crates.io-index" 1148 | checksum = "f51d0c0d83bec45f16480d0ce0058397a69e48fcdc52d1dc8855fb68acbd31a7" 1149 | dependencies = [ 1150 | "core-foundation-sys", 1151 | "libc", 1152 | ] 1153 | 1154 | [[package]] 1155 | name = "serde" 1156 | version = "1.0.163" 1157 | source = "registry+https://github.com/rust-lang/crates.io-index" 1158 | checksum = "2113ab51b87a539ae008b5c6c02dc020ffa39afd2d83cffcb3f4eb2722cebec2" 1159 | dependencies = [ 1160 | "serde_derive", 1161 | ] 1162 | 1163 | [[package]] 1164 | name = "serde_derive" 1165 | version = "1.0.163" 1166 | source = "registry+https://github.com/rust-lang/crates.io-index" 1167 | checksum = "8c805777e3930c8883389c602315a24224bcc738b63905ef87cd1420353ea93e" 1168 | dependencies = [ 1169 | "proc-macro2", 1170 | "quote", 1171 | "syn", 1172 | ] 1173 | 1174 | [[package]] 1175 | name = "serde_json" 1176 | version = "1.0.96" 1177 | source = "registry+https://github.com/rust-lang/crates.io-index" 1178 | checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" 1179 | dependencies = [ 1180 | "itoa", 1181 | "ryu", 1182 | "serde", 1183 | ] 1184 | 1185 | [[package]] 1186 | name = "serde_urlencoded" 1187 | version = "0.7.1" 1188 | source = "registry+https://github.com/rust-lang/crates.io-index" 1189 | checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" 1190 | dependencies = [ 1191 | "form_urlencoded", 1192 | "itoa", 1193 | "ryu", 1194 | "serde", 1195 | ] 1196 | 1197 | [[package]] 1198 | name = "signal-hook" 1199 | version = "0.3.15" 1200 | source = "registry+https://github.com/rust-lang/crates.io-index" 1201 | checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9" 1202 | dependencies = [ 1203 | "libc", 1204 | "signal-hook-registry", 1205 | ] 1206 | 1207 | [[package]] 1208 | name = "signal-hook-mio" 1209 | version = "0.2.3" 1210 | source = "registry+https://github.com/rust-lang/crates.io-index" 1211 | checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af" 1212 | dependencies = [ 1213 | "libc", 1214 | "mio", 1215 | "signal-hook", 1216 | ] 1217 | 1218 | [[package]] 1219 | name = "signal-hook-registry" 1220 | version = "1.4.1" 1221 | source = "registry+https://github.com/rust-lang/crates.io-index" 1222 | checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" 1223 | dependencies = [ 1224 | "libc", 1225 | ] 1226 | 1227 | [[package]] 1228 | name = "slab" 1229 | version = "0.4.8" 1230 | source = "registry+https://github.com/rust-lang/crates.io-index" 1231 | checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" 1232 | dependencies = [ 1233 | "autocfg", 1234 | ] 1235 | 1236 | [[package]] 1237 | name = "smallvec" 1238 | version = "1.10.0" 1239 | source = "registry+https://github.com/rust-lang/crates.io-index" 1240 | checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" 1241 | 1242 | [[package]] 1243 | name = "socket2" 1244 | version = "0.4.9" 1245 | source = "registry+https://github.com/rust-lang/crates.io-index" 1246 | checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" 1247 | dependencies = [ 1248 | "libc", 1249 | "winapi", 1250 | ] 1251 | 1252 | [[package]] 1253 | name = "strsim" 1254 | version = "0.10.0" 1255 | source = "registry+https://github.com/rust-lang/crates.io-index" 1256 | checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 1257 | 1258 | [[package]] 1259 | name = "syn" 1260 | version = "2.0.16" 1261 | source = "registry+https://github.com/rust-lang/crates.io-index" 1262 | checksum = "a6f671d4b5ffdb8eadec19c0ae67fe2639df8684bd7bc4b83d986b8db549cf01" 1263 | dependencies = [ 1264 | "proc-macro2", 1265 | "quote", 1266 | "unicode-ident", 1267 | ] 1268 | 1269 | [[package]] 1270 | name = "tempfile" 1271 | version = "3.5.0" 1272 | source = "registry+https://github.com/rust-lang/crates.io-index" 1273 | checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998" 1274 | dependencies = [ 1275 | "cfg-if", 1276 | "fastrand", 1277 | "redox_syscall 0.3.5", 1278 | "rustix", 1279 | "windows-sys 0.45.0", 1280 | ] 1281 | 1282 | [[package]] 1283 | name = "termcolor" 1284 | version = "1.2.0" 1285 | source = "registry+https://github.com/rust-lang/crates.io-index" 1286 | checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" 1287 | dependencies = [ 1288 | "winapi-util", 1289 | ] 1290 | 1291 | [[package]] 1292 | name = "thiserror" 1293 | version = "1.0.40" 1294 | source = "registry+https://github.com/rust-lang/crates.io-index" 1295 | checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" 1296 | dependencies = [ 1297 | "thiserror-impl", 1298 | ] 1299 | 1300 | [[package]] 1301 | name = "thiserror-impl" 1302 | version = "1.0.40" 1303 | source = "registry+https://github.com/rust-lang/crates.io-index" 1304 | checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" 1305 | dependencies = [ 1306 | "proc-macro2", 1307 | "quote", 1308 | "syn", 1309 | ] 1310 | 1311 | [[package]] 1312 | name = "time" 1313 | version = "0.3.21" 1314 | source = "registry+https://github.com/rust-lang/crates.io-index" 1315 | checksum = "8f3403384eaacbca9923fa06940178ac13e4edb725486d70e8e15881d0c836cc" 1316 | dependencies = [ 1317 | "itoa", 1318 | "serde", 1319 | "time-core", 1320 | "time-macros", 1321 | ] 1322 | 1323 | [[package]] 1324 | name = "time-core" 1325 | version = "0.1.1" 1326 | source = "registry+https://github.com/rust-lang/crates.io-index" 1327 | checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" 1328 | 1329 | [[package]] 1330 | name = "time-macros" 1331 | version = "0.2.9" 1332 | source = "registry+https://github.com/rust-lang/crates.io-index" 1333 | checksum = "372950940a5f07bf38dbe211d7283c9e6d7327df53794992d293e534c733d09b" 1334 | dependencies = [ 1335 | "time-core", 1336 | ] 1337 | 1338 | [[package]] 1339 | name = "tinyvec" 1340 | version = "1.6.0" 1341 | source = "registry+https://github.com/rust-lang/crates.io-index" 1342 | checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" 1343 | dependencies = [ 1344 | "tinyvec_macros", 1345 | ] 1346 | 1347 | [[package]] 1348 | name = "tinyvec_macros" 1349 | version = "0.1.1" 1350 | source = "registry+https://github.com/rust-lang/crates.io-index" 1351 | checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" 1352 | 1353 | [[package]] 1354 | name = "tokio" 1355 | version = "1.28.1" 1356 | source = "registry+https://github.com/rust-lang/crates.io-index" 1357 | checksum = "0aa32867d44e6f2ce3385e89dceb990188b8bb0fb25b0cf576647a6f98ac5105" 1358 | dependencies = [ 1359 | "autocfg", 1360 | "bytes", 1361 | "libc", 1362 | "mio", 1363 | "num_cpus", 1364 | "parking_lot", 1365 | "pin-project-lite", 1366 | "signal-hook-registry", 1367 | "socket2", 1368 | "tokio-macros", 1369 | "windows-sys 0.48.0", 1370 | ] 1371 | 1372 | [[package]] 1373 | name = "tokio-macros" 1374 | version = "2.1.0" 1375 | source = "registry+https://github.com/rust-lang/crates.io-index" 1376 | checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" 1377 | dependencies = [ 1378 | "proc-macro2", 1379 | "quote", 1380 | "syn", 1381 | ] 1382 | 1383 | [[package]] 1384 | name = "tokio-native-tls" 1385 | version = "0.3.1" 1386 | source = "registry+https://github.com/rust-lang/crates.io-index" 1387 | checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" 1388 | dependencies = [ 1389 | "native-tls", 1390 | "tokio", 1391 | ] 1392 | 1393 | [[package]] 1394 | name = "tokio-stream" 1395 | version = "0.1.14" 1396 | source = "registry+https://github.com/rust-lang/crates.io-index" 1397 | checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" 1398 | dependencies = [ 1399 | "futures-core", 1400 | "pin-project-lite", 1401 | "tokio", 1402 | ] 1403 | 1404 | [[package]] 1405 | name = "tokio-util" 1406 | version = "0.7.8" 1407 | source = "registry+https://github.com/rust-lang/crates.io-index" 1408 | checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d" 1409 | dependencies = [ 1410 | "bytes", 1411 | "futures-core", 1412 | "futures-sink", 1413 | "pin-project-lite", 1414 | "tokio", 1415 | "tracing", 1416 | ] 1417 | 1418 | [[package]] 1419 | name = "tower-service" 1420 | version = "0.3.2" 1421 | source = "registry+https://github.com/rust-lang/crates.io-index" 1422 | checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" 1423 | 1424 | [[package]] 1425 | name = "tracing" 1426 | version = "0.1.37" 1427 | source = "registry+https://github.com/rust-lang/crates.io-index" 1428 | checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" 1429 | dependencies = [ 1430 | "cfg-if", 1431 | "pin-project-lite", 1432 | "tracing-core", 1433 | ] 1434 | 1435 | [[package]] 1436 | name = "tracing-core" 1437 | version = "0.1.31" 1438 | source = "registry+https://github.com/rust-lang/crates.io-index" 1439 | checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" 1440 | dependencies = [ 1441 | "once_cell", 1442 | ] 1443 | 1444 | [[package]] 1445 | name = "try-lock" 1446 | version = "0.2.4" 1447 | source = "registry+https://github.com/rust-lang/crates.io-index" 1448 | checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" 1449 | 1450 | [[package]] 1451 | name = "typenum" 1452 | version = "1.16.0" 1453 | source = "registry+https://github.com/rust-lang/crates.io-index" 1454 | checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" 1455 | 1456 | [[package]] 1457 | name = "unicode-bidi" 1458 | version = "0.3.13" 1459 | source = "registry+https://github.com/rust-lang/crates.io-index" 1460 | checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" 1461 | 1462 | [[package]] 1463 | name = "unicode-ident" 1464 | version = "1.0.8" 1465 | source = "registry+https://github.com/rust-lang/crates.io-index" 1466 | checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" 1467 | 1468 | [[package]] 1469 | name = "unicode-normalization" 1470 | version = "0.1.22" 1471 | source = "registry+https://github.com/rust-lang/crates.io-index" 1472 | checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" 1473 | dependencies = [ 1474 | "tinyvec", 1475 | ] 1476 | 1477 | [[package]] 1478 | name = "url" 1479 | version = "2.3.1" 1480 | source = "registry+https://github.com/rust-lang/crates.io-index" 1481 | checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" 1482 | dependencies = [ 1483 | "form_urlencoded", 1484 | "idna 0.3.0", 1485 | "percent-encoding", 1486 | ] 1487 | 1488 | [[package]] 1489 | name = "utf8parse" 1490 | version = "0.2.1" 1491 | source = "registry+https://github.com/rust-lang/crates.io-index" 1492 | checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" 1493 | 1494 | [[package]] 1495 | name = "vcpkg" 1496 | version = "0.2.15" 1497 | source = "registry+https://github.com/rust-lang/crates.io-index" 1498 | checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" 1499 | 1500 | [[package]] 1501 | name = "version_check" 1502 | version = "0.9.4" 1503 | source = "registry+https://github.com/rust-lang/crates.io-index" 1504 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" 1505 | 1506 | [[package]] 1507 | name = "want" 1508 | version = "0.3.0" 1509 | source = "registry+https://github.com/rust-lang/crates.io-index" 1510 | checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" 1511 | dependencies = [ 1512 | "log", 1513 | "try-lock", 1514 | ] 1515 | 1516 | [[package]] 1517 | name = "wasi" 1518 | version = "0.11.0+wasi-snapshot-preview1" 1519 | source = "registry+https://github.com/rust-lang/crates.io-index" 1520 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" 1521 | 1522 | [[package]] 1523 | name = "wasm-bindgen" 1524 | version = "0.2.86" 1525 | source = "registry+https://github.com/rust-lang/crates.io-index" 1526 | checksum = "5bba0e8cb82ba49ff4e229459ff22a191bbe9a1cb3a341610c9c33efc27ddf73" 1527 | dependencies = [ 1528 | "cfg-if", 1529 | "wasm-bindgen-macro", 1530 | ] 1531 | 1532 | [[package]] 1533 | name = "wasm-bindgen-backend" 1534 | version = "0.2.86" 1535 | source = "registry+https://github.com/rust-lang/crates.io-index" 1536 | checksum = "19b04bc93f9d6bdee709f6bd2118f57dd6679cf1176a1af464fca3ab0d66d8fb" 1537 | dependencies = [ 1538 | "bumpalo", 1539 | "log", 1540 | "once_cell", 1541 | "proc-macro2", 1542 | "quote", 1543 | "syn", 1544 | "wasm-bindgen-shared", 1545 | ] 1546 | 1547 | [[package]] 1548 | name = "wasm-bindgen-futures" 1549 | version = "0.4.36" 1550 | source = "registry+https://github.com/rust-lang/crates.io-index" 1551 | checksum = "2d1985d03709c53167ce907ff394f5316aa22cb4e12761295c5dc57dacb6297e" 1552 | dependencies = [ 1553 | "cfg-if", 1554 | "js-sys", 1555 | "wasm-bindgen", 1556 | "web-sys", 1557 | ] 1558 | 1559 | [[package]] 1560 | name = "wasm-bindgen-macro" 1561 | version = "0.2.86" 1562 | source = "registry+https://github.com/rust-lang/crates.io-index" 1563 | checksum = "14d6b024f1a526bb0234f52840389927257beb670610081360e5a03c5df9c258" 1564 | dependencies = [ 1565 | "quote", 1566 | "wasm-bindgen-macro-support", 1567 | ] 1568 | 1569 | [[package]] 1570 | name = "wasm-bindgen-macro-support" 1571 | version = "0.2.86" 1572 | source = "registry+https://github.com/rust-lang/crates.io-index" 1573 | checksum = "e128beba882dd1eb6200e1dc92ae6c5dbaa4311aa7bb211ca035779e5efc39f8" 1574 | dependencies = [ 1575 | "proc-macro2", 1576 | "quote", 1577 | "syn", 1578 | "wasm-bindgen-backend", 1579 | "wasm-bindgen-shared", 1580 | ] 1581 | 1582 | [[package]] 1583 | name = "wasm-bindgen-shared" 1584 | version = "0.2.86" 1585 | source = "registry+https://github.com/rust-lang/crates.io-index" 1586 | checksum = "ed9d5b4305409d1fc9482fee2d7f9bcbf24b3972bf59817ef757e23982242a93" 1587 | 1588 | [[package]] 1589 | name = "wasm-streams" 1590 | version = "0.2.3" 1591 | source = "registry+https://github.com/rust-lang/crates.io-index" 1592 | checksum = "6bbae3363c08332cadccd13b67db371814cd214c2524020932f0804b8cf7c078" 1593 | dependencies = [ 1594 | "futures-util", 1595 | "js-sys", 1596 | "wasm-bindgen", 1597 | "wasm-bindgen-futures", 1598 | "web-sys", 1599 | ] 1600 | 1601 | [[package]] 1602 | name = "web-sys" 1603 | version = "0.3.63" 1604 | source = "registry+https://github.com/rust-lang/crates.io-index" 1605 | checksum = "3bdd9ef4e984da1187bf8110c5cf5b845fbc87a23602cdf912386a76fcd3a7c2" 1606 | dependencies = [ 1607 | "js-sys", 1608 | "wasm-bindgen", 1609 | ] 1610 | 1611 | [[package]] 1612 | name = "winapi" 1613 | version = "0.3.9" 1614 | source = "registry+https://github.com/rust-lang/crates.io-index" 1615 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 1616 | dependencies = [ 1617 | "winapi-i686-pc-windows-gnu", 1618 | "winapi-x86_64-pc-windows-gnu", 1619 | ] 1620 | 1621 | [[package]] 1622 | name = "winapi-i686-pc-windows-gnu" 1623 | version = "0.4.0" 1624 | source = "registry+https://github.com/rust-lang/crates.io-index" 1625 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 1626 | 1627 | [[package]] 1628 | name = "winapi-util" 1629 | version = "0.1.5" 1630 | source = "registry+https://github.com/rust-lang/crates.io-index" 1631 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 1632 | dependencies = [ 1633 | "winapi", 1634 | ] 1635 | 1636 | [[package]] 1637 | name = "winapi-x86_64-pc-windows-gnu" 1638 | version = "0.4.0" 1639 | source = "registry+https://github.com/rust-lang/crates.io-index" 1640 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 1641 | 1642 | [[package]] 1643 | name = "windows-sys" 1644 | version = "0.42.0" 1645 | source = "registry+https://github.com/rust-lang/crates.io-index" 1646 | checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" 1647 | dependencies = [ 1648 | "windows_aarch64_gnullvm 0.42.2", 1649 | "windows_aarch64_msvc 0.42.2", 1650 | "windows_i686_gnu 0.42.2", 1651 | "windows_i686_msvc 0.42.2", 1652 | "windows_x86_64_gnu 0.42.2", 1653 | "windows_x86_64_gnullvm 0.42.2", 1654 | "windows_x86_64_msvc 0.42.2", 1655 | ] 1656 | 1657 | [[package]] 1658 | name = "windows-sys" 1659 | version = "0.45.0" 1660 | source = "registry+https://github.com/rust-lang/crates.io-index" 1661 | checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" 1662 | dependencies = [ 1663 | "windows-targets 0.42.2", 1664 | ] 1665 | 1666 | [[package]] 1667 | name = "windows-sys" 1668 | version = "0.48.0" 1669 | source = "registry+https://github.com/rust-lang/crates.io-index" 1670 | checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" 1671 | dependencies = [ 1672 | "windows-targets 0.48.0", 1673 | ] 1674 | 1675 | [[package]] 1676 | name = "windows-targets" 1677 | version = "0.42.2" 1678 | source = "registry+https://github.com/rust-lang/crates.io-index" 1679 | checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" 1680 | dependencies = [ 1681 | "windows_aarch64_gnullvm 0.42.2", 1682 | "windows_aarch64_msvc 0.42.2", 1683 | "windows_i686_gnu 0.42.2", 1684 | "windows_i686_msvc 0.42.2", 1685 | "windows_x86_64_gnu 0.42.2", 1686 | "windows_x86_64_gnullvm 0.42.2", 1687 | "windows_x86_64_msvc 0.42.2", 1688 | ] 1689 | 1690 | [[package]] 1691 | name = "windows-targets" 1692 | version = "0.48.0" 1693 | source = "registry+https://github.com/rust-lang/crates.io-index" 1694 | checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" 1695 | dependencies = [ 1696 | "windows_aarch64_gnullvm 0.48.0", 1697 | "windows_aarch64_msvc 0.48.0", 1698 | "windows_i686_gnu 0.48.0", 1699 | "windows_i686_msvc 0.48.0", 1700 | "windows_x86_64_gnu 0.48.0", 1701 | "windows_x86_64_gnullvm 0.48.0", 1702 | "windows_x86_64_msvc 0.48.0", 1703 | ] 1704 | 1705 | [[package]] 1706 | name = "windows_aarch64_gnullvm" 1707 | version = "0.42.2" 1708 | source = "registry+https://github.com/rust-lang/crates.io-index" 1709 | checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" 1710 | 1711 | [[package]] 1712 | name = "windows_aarch64_gnullvm" 1713 | version = "0.48.0" 1714 | source = "registry+https://github.com/rust-lang/crates.io-index" 1715 | checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" 1716 | 1717 | [[package]] 1718 | name = "windows_aarch64_msvc" 1719 | version = "0.42.2" 1720 | source = "registry+https://github.com/rust-lang/crates.io-index" 1721 | checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" 1722 | 1723 | [[package]] 1724 | name = "windows_aarch64_msvc" 1725 | version = "0.48.0" 1726 | source = "registry+https://github.com/rust-lang/crates.io-index" 1727 | checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" 1728 | 1729 | [[package]] 1730 | name = "windows_i686_gnu" 1731 | version = "0.42.2" 1732 | source = "registry+https://github.com/rust-lang/crates.io-index" 1733 | checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" 1734 | 1735 | [[package]] 1736 | name = "windows_i686_gnu" 1737 | version = "0.48.0" 1738 | source = "registry+https://github.com/rust-lang/crates.io-index" 1739 | checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" 1740 | 1741 | [[package]] 1742 | name = "windows_i686_msvc" 1743 | version = "0.42.2" 1744 | source = "registry+https://github.com/rust-lang/crates.io-index" 1745 | checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" 1746 | 1747 | [[package]] 1748 | name = "windows_i686_msvc" 1749 | version = "0.48.0" 1750 | source = "registry+https://github.com/rust-lang/crates.io-index" 1751 | checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" 1752 | 1753 | [[package]] 1754 | name = "windows_x86_64_gnu" 1755 | version = "0.42.2" 1756 | source = "registry+https://github.com/rust-lang/crates.io-index" 1757 | checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" 1758 | 1759 | [[package]] 1760 | name = "windows_x86_64_gnu" 1761 | version = "0.48.0" 1762 | source = "registry+https://github.com/rust-lang/crates.io-index" 1763 | checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" 1764 | 1765 | [[package]] 1766 | name = "windows_x86_64_gnullvm" 1767 | version = "0.42.2" 1768 | source = "registry+https://github.com/rust-lang/crates.io-index" 1769 | checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" 1770 | 1771 | [[package]] 1772 | name = "windows_x86_64_gnullvm" 1773 | version = "0.48.0" 1774 | source = "registry+https://github.com/rust-lang/crates.io-index" 1775 | checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" 1776 | 1777 | [[package]] 1778 | name = "windows_x86_64_msvc" 1779 | version = "0.42.2" 1780 | source = "registry+https://github.com/rust-lang/crates.io-index" 1781 | checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" 1782 | 1783 | [[package]] 1784 | name = "windows_x86_64_msvc" 1785 | version = "0.48.0" 1786 | source = "registry+https://github.com/rust-lang/crates.io-index" 1787 | checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" 1788 | 1789 | [[package]] 1790 | name = "winreg" 1791 | version = "0.10.1" 1792 | source = "registry+https://github.com/rust-lang/crates.io-index" 1793 | checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" 1794 | dependencies = [ 1795 | "winapi", 1796 | ] 1797 | 1798 | [[package]] 1799 | name = "xml-rs" 1800 | version = "0.8.11" 1801 | source = "registry+https://github.com/rust-lang/crates.io-index" 1802 | checksum = "1690519550bfa95525229b9ca2350c63043a4857b3b0013811b2ccf4a2420b01" 1803 | 1804 | [[package]] 1805 | name = "xmltree" 1806 | version = "0.10.3" 1807 | source = "registry+https://github.com/rust-lang/crates.io-index" 1808 | checksum = "d7d8a75eaf6557bb84a65ace8609883db44a29951042ada9b393151532e41fcb" 1809 | dependencies = [ 1810 | "xml-rs", 1811 | ] 1812 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "samfusdl" 3 | version = "0.1.10" 4 | authors = ["Andrew Gunnerson "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | anyhow = "1.0.69" 9 | clap = { version = "4.1.6", features = ["derive", "env"] } 10 | crc32fast = "1.3.2" 11 | dirs = "5.0.1" 12 | env_logger = "0.10.0" 13 | log = "0.4.17" 14 | progresslib = { path = "progresslib" } 15 | samfuslib = { path = "samfuslib" } 16 | serde = { version = "1.0.152", features = ["derive"] } 17 | serde_json = "1.0.93" 18 | tokio = { version = "1.25.0", features = ["full"] } 19 | tokio-stream = "0.1.12" 20 | 21 | [target.'cfg(windows)'.dependencies] 22 | memoffset = "0.9.0" 23 | winapi = "0.3.9" 24 | 25 | [workspace] 26 | members = ["progresslib", "samfuslib"] 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **2024-03-10 Update**: Due to Samsung's increasing disdain for folks who like to tinker with custom firmware, I'm getting rid of all my Samsung Android devices. Thus, this project is no longer in development. 2 | 3 | # samfusdl 4 | 5 | samfusdl is an unofficial tool for downloading firmware images from Samsung's FUS (firmware update service). 6 | 7 | Features: 8 | * Downloads firmware chunks in parallel for faster downloads 9 | * Interrupted downloads can be resumed 10 | * Supports downloading both home and factory images 11 | * Supports both old and new-style firmware decryption (`.enc2` and `.enc4`) 12 | * Supports downloading the latest firmware or a specific version 13 | * Supports AES-NI for fast firmware decryption on x86_64 (falls back to SIMD for other CPU architectures or if AES-NI is not available) 14 | 15 | ## Encryption keys 16 | 17 | Access to FUS requires two encryption keys: the fixed key and the flexible key suffix. These are the same for every user and are hard-coded into the official clients. **samfusdl does not and will never include these encryption keys.** You must acquire them yourself. 18 | 19 | **Please do not open any issues or contact the author about how to reverse-engineer any of the official clients. They will be ignored.** 20 | 21 | Once you have the keys, there are a few different ways to make them available to samfusdl: 22 | 23 | * Inside the config file: 24 | 25 | * Windows: `%APPDATA%\samfusdl.conf` (eg. `C:\Users\\AppData\Roaming\samfusdl.conf`) 26 | * Linux (and other unix-like OS's): `$XDG_CONFIG_HOME/samfusdl.conf` or `~/.config/samfusdl.conf` 27 | * macOS: `~/Library/Application Support/samfusdl.conf` 28 | 29 | Contents: 30 | 31 | ```json 32 | { 33 | "fus_fixed_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 34 | "fus_flexible_key_suffix": "XXXXXXXXXXXXXXXX" 35 | } 36 | ``` 37 | 38 | * As environment variables: 39 | 40 | sh/bash/zsh: 41 | 42 | ```sh 43 | export FUS_FIXED_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 44 | export FUS_FLEXIBLE_KEY_SUFFIX=XXXXXXXXXXXXXXXX 45 | ``` 46 | 47 | powershell: 48 | 49 | ```powershell 50 | $env:FUS_FIXED_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' 51 | $env:FUS_FLEXIBLE_KEY_SUFFIX = 'XXXXXXXXXXXXXXXX' 52 | ``` 53 | 54 | * As command-line arguments: 55 | 56 | When running `samfusdl`, add the `--fus-fixed-key XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX` and `--fus-flexible-key-suffix XXXXXXXXXXXXXXXX` arguments. 57 | 58 | ## Usage 59 | 60 | To download the latest firmware for a device, run: 61 | 62 | ``` 63 | samfusdl -m -r -i 64 | ``` 65 | 66 | FUS now requires the IMEI or serial number (for devices without a modem) to be specified. It is no longer possible to download arbitrary firmware for any device. 67 | 68 | To download a specific firmware version, add the `-v`/`--version` argument. The version string is in the form: `///`. For most devices, the shorthand `/` can be used because `` and `` have the same value as ``. 69 | 70 | To change the output path, use the `-o ` argument. 71 | 72 | Firmware files are downloaded with 4 parallel connections. This can be changed using the `-c`/`--chunks` argument. To interrupt a download, simply use Ctrl-C as usual. Rerunning the same command will resume the download. 73 | 74 | By default, the "home" firmware type (also known as "binary nature") is downloaded instead of the "factory" image. For newer devices, both firmware types are the same. To specify which type of firmware to download, use the `-t`/`--firmware-type` argument. 75 | 76 | For more information about other command-line arguments, see `--help`. 77 | 78 | ## Building from source 79 | 80 | To build from source, first make sure that the Rust toolchain is installed. It can be installed from https://rustup.rs/ or the OS's package manager. 81 | 82 | Build samfusdl using the following command: 83 | 84 | ``` 85 | cargo build --release 86 | ``` 87 | 88 | The resulting executable will be in `target/release/samfusdl` or `target\release\samfusdl.exe`. 89 | 90 | ## Debugging 91 | 92 | Debug logging can be enabled with the `--loglevel debug` argument. This will disable the fancy progress bar and print out significantly more information, such as how the parallel download chunks are split. Note that encryption keys are not logged unless the `SAMFUSDL_LOG_KEYS` environment variable is set to `true`. 93 | 94 | If `--loglevel trace` is set, each file I/O operation during the download stage is logged. This is generally not useful for anything besides debugging the parallel download mechanism or `pwrite`/overlapped-I/O. 95 | 96 | Instead of setting `--loglevel`, it is also possible to set the `RUST_LOG` environment variable, which allows log messages of samfusdl's dependencies to be printed out. 97 | 98 | To debug the actual HTTP requests and responses, any HTTPS-compatible MITM software, like mitmproxy, can be used. samfusdl respects both the OS proxy settings and the `http_proxy`/`https_proxy` environment variables. Note that TLS certificate validation is enabled by default. The MITM software's CA certificate will either need to be added to the OS's trust store or the `--ignore-tls-validation` argument can be used. 99 | 100 | ## Caveats 101 | 102 | * For Windows, only Windows 10 1607 and newer are supported. samfusdl uses atomic file rename/replace, which isn't supported on earlier versions of Windows. 103 | 104 | ## License 105 | 106 | samfusdl is licensed under the GPLv3 license. For details, please see [`LICENSE`](./LICENSE). 107 | 108 | ## TODO 109 | 110 | * Stop using FOTA for querying the latest firmware as it does not work for `ATT` or `VZW`. 111 | -------------------------------------------------------------------------------- /progresslib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "progresslib" 3 | version = "0.1.6" 4 | authors = ["Andrew Gunnerson "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | crossterm = "0.26.0" 9 | number_prefix = "0.4.0" 10 | -------------------------------------------------------------------------------- /progresslib/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod progress; 2 | 3 | pub use progress::{ProgressBar, ProgressDrawMode}; -------------------------------------------------------------------------------- /progresslib/src/progress.rs: -------------------------------------------------------------------------------- 1 | mod format; 2 | 3 | use format::{BinarySize, ClockDuration, HumanDuration}; 4 | 5 | use std::{ 6 | collections::VecDeque, 7 | io::Write, 8 | time::{Duration, Instant}, 9 | }; 10 | 11 | use crossterm::{ 12 | cursor::{Hide, MoveToColumn, Show}, 13 | QueueableCommand, 14 | Result, 15 | style::{Print, Stylize}, 16 | terminal::{self, Clear, ClearType}, 17 | tty::IsTty, 18 | }; 19 | 20 | /// Type that receives progress values and buffers them to compute the average 21 | /// progress progression speed over the specified period of time. 22 | #[derive(Debug)] 23 | pub struct ProgressSpeed { 24 | /// Period of time to accumulate records. 25 | duration: Duration, 26 | /// Buffer containing progress records over the specified period of time. 27 | buf: VecDeque<(Instant, u64)>, 28 | } 29 | 30 | impl ProgressSpeed { 31 | pub fn new(duration: Duration) -> Self { 32 | Self { 33 | duration, 34 | buf: VecDeque::new(), 35 | } 36 | } 37 | 38 | /// Clear all recorded values. 39 | pub fn reset(&mut self) { 40 | self.buf.clear(); 41 | } 42 | 43 | /// Record progress value to be used for the speed calculation. 44 | pub fn record_value(&mut self, value: u64) { 45 | let now = Instant::now(); 46 | self.buf.push_back((now, value)); 47 | 48 | // Only keep enough records to represent self.duration amount of time 49 | let end = self.buf 50 | .iter() 51 | .position(|x| now - x.0 < self.duration) 52 | .and_then(|x| x.checked_sub(1)); 53 | if let Some(v) = end { 54 | self.buf.drain(0..v); 55 | } 56 | } 57 | 58 | /// Get progress speed as the number of progress units per second. 59 | pub fn units_per_sec(&self) -> f64 { 60 | if let (Some(f), Some(b)) = (self.buf.front(), self.buf.back()) { 61 | if f != b { 62 | return (b.1 - f.1) as f64 / (b.0 - f.0).as_secs_f64(); 63 | } 64 | } 65 | 66 | 0.0 67 | } 68 | } 69 | 70 | /// Progress bar for showing progress in bytes. The elapsed time, current 71 | /// progress, current percentage, (moving) average speed, and ETA are displayed. 72 | /// The rendering FPS is also configurable. 73 | pub struct ProgressBar { 74 | /// Maximum value 75 | len: u64, 76 | /// Current value 77 | pos: u64, 78 | /// Output terminal 79 | term: T, 80 | /// Output mode 81 | mode: ProgressDrawMode, 82 | /// (Maximum) frames per second for rendering 83 | fps: f64, 84 | /// Time of last draw 85 | last_draw: Instant, 86 | /// Timestamp of when the progress bar started 87 | started: Instant, 88 | /// Speed calculator 89 | speed: ProgressSpeed, 90 | } 91 | 92 | /// How the progress bar should be drawn 93 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] 94 | pub enum ProgressDrawMode { 95 | /// Draw to the terminal. The same line is overwritten with the new progress 96 | /// during each rendering frame. This mode is useful when the terminal is 97 | /// interactive. The default rendering frame rate in this mode is 15 fps. 98 | Interactive, 99 | /// Draw to the terminal. A new line is appended with the new progress 100 | /// during each rendering frame. This mode is useful when the terminal is 101 | /// not interactive or output is being redirected to a file. The default 102 | /// rendering frame rate in this mode is 0.2 fps. 103 | Append, 104 | /// Do not draw to the terminal. 105 | None, 106 | } 107 | 108 | impl ProgressDrawMode { 109 | fn default_fps(self) -> f64 { 110 | match self { 111 | Self::Interactive => 15.0, 112 | Self::Append => 0.2, 113 | Self::None => 0.0, 114 | } 115 | } 116 | } 117 | 118 | impl ProgressBar { 119 | /// Construct a new progress bar. By default, every update is rendered 120 | /// immediately. Call `set_fps` to reduce the rendering rate. 121 | pub fn new(term: T, len: u64) -> Self { 122 | let mode = if term.is_tty() { 123 | ProgressDrawMode::Interactive 124 | } else { 125 | ProgressDrawMode::Append 126 | }; 127 | let now = Instant::now(); 128 | 129 | Self { 130 | len, 131 | pos: 0, 132 | term, 133 | mode, 134 | fps: mode.default_fps(), 135 | last_draw: now, 136 | started: now, 137 | speed: ProgressSpeed::new(Duration::from_secs(10)), 138 | } 139 | } 140 | 141 | /// Get the current draw mode. 142 | pub fn mode(&self) -> ProgressDrawMode { 143 | self.mode 144 | } 145 | 146 | /// Set the draw mode. It the mode is set to [`None`], then the function 147 | /// will automatically pick [`Interactive`] or [`Append`] depending on if 148 | /// the terminal is interactive. This will reset the output fps to the 149 | /// default for the draw mode. 150 | pub fn set_mode(&mut self, mode: Option) { 151 | self.mode = match mode { 152 | Some(m) => m, 153 | None => if self.term.is_tty() { 154 | ProgressDrawMode::Interactive 155 | } else { 156 | ProgressDrawMode::Append 157 | } 158 | }; 159 | self.fps = self.mode.default_fps(); 160 | } 161 | 162 | pub fn fps(&self) -> f64 { 163 | self.fps 164 | } 165 | 166 | /// Set maximum rendering frequency in frames per second. 167 | pub fn set_fps(&mut self, fps: f64) { 168 | self.fps = fps; 169 | } 170 | 171 | /// Get the maximum value of the progress bar. 172 | pub fn length(&self) -> u64 { 173 | self.len 174 | } 175 | 176 | /// Set the maximum value of the progress bar. This performs an immediate 177 | /// redraw. 178 | pub fn set_length(&mut self, len: u64) -> Result<()> { 179 | self.len = len; 180 | self.draw(true) 181 | } 182 | 183 | /// Get the current value of the progress bar. 184 | pub fn position(&self) -> u64 { 185 | self.pos 186 | } 187 | 188 | /// Set the current value of the progress bar. This performs an immediate 189 | /// redraw. 190 | pub fn set_position(&mut self, pos: u64) -> Result<()> { 191 | self.pos = pos; 192 | self.speed.record_value(self.pos); 193 | self.draw(true) 194 | } 195 | 196 | /// Advances the current position of the progress bar by the specified 197 | /// amount. This performs a redraw, subject to the output rate limiting. 198 | pub fn advance(&mut self, delta: u64) -> Result<()> { 199 | self.pos = self.pos.saturating_add(delta); 200 | self.speed.record_value(self.pos); 201 | self.draw(false) 202 | } 203 | 204 | /// Print a line to the progress bar's terminal without clobbering the 205 | /// progress bar itself. 206 | pub fn println>(&mut self, msg: I) -> Result<()> { 207 | if self.mode != ProgressDrawMode::None { 208 | if self.mode == ProgressDrawMode::Interactive { 209 | self.term 210 | .queue(Clear(ClearType::CurrentLine))? 211 | .queue(MoveToColumn(0))?; 212 | } 213 | 214 | self.term 215 | .queue(Print(msg.into()))? 216 | .queue(Print('\n'))?; 217 | 218 | if self.mode == ProgressDrawMode::Interactive { 219 | self.draw(true)?; 220 | } 221 | } 222 | Ok(()) 223 | } 224 | 225 | /// Draw the final frame and clear the progress bar from the terminal. 226 | /// The progress bar will reappear if the progress bar state changes again. 227 | /// This is automatically called when the progress bar is dropped. 228 | pub fn finish(&mut self) -> Result<()> { 229 | match self.mode { 230 | ProgressDrawMode::Interactive => { 231 | self.term 232 | .queue(Clear(ClearType::CurrentLine))? 233 | .queue(MoveToColumn(0))? 234 | .queue(Show)? 235 | .flush()?; 236 | } 237 | ProgressDrawMode::Append => self.draw(true)?, 238 | ProgressDrawMode::None => {} 239 | } 240 | Ok(()) 241 | } 242 | 243 | /// If the output mode is interactive, print a newline to the terminal 244 | /// causing the current progress bar state to be kept on-screen on the 245 | /// previous line. Further progress bar state changes will appear on the 246 | /// last line as usual. 247 | pub fn keep(&mut self) -> Result<()> { 248 | if self.mode == ProgressDrawMode::Interactive { 249 | self.term 250 | .queue(Print('\n'))? 251 | .flush()?; 252 | } 253 | Ok(()) 254 | } 255 | 256 | /// Reset the progress bar, including the elapsed time, the ETA, and the 257 | /// current position. This performs an immediate redraw. 258 | pub fn reset(&mut self) -> Result<()> { 259 | self.pos = 0; 260 | self.started = Instant::now(); 261 | self.speed.reset(); 262 | self.draw(true) 263 | } 264 | 265 | /// Draw the progress bar. This is normally done by setting the position or 266 | /// the length. If `force` is true, then the draw will always occur. 267 | /// Otherwise, the rendering is subject to the rate limit of the progress 268 | /// bar. 269 | pub fn draw(&mut self, force: bool) -> Result<()> { 270 | if !force && self.fps > 0.0 { 271 | let frame_dur = Duration::from_secs_f64(1.0 / self.fps); 272 | if self.last_draw != self.started && self.last_draw.elapsed() < frame_dur { 273 | return Ok(()); 274 | } 275 | } 276 | 277 | if self.mode == ProgressDrawMode::None { 278 | return Ok(()); 279 | } 280 | 281 | let elapsed = Duration::from_secs(self.started.elapsed().as_secs()); 282 | let eta = Duration::from_secs(self.eta().as_secs()); 283 | let ratio = (self.pos as f64 / self.len as f64).clamp(0.0, 1.0); 284 | 285 | let mut result = format!( 286 | "[{elapsed}] {bar_placeholder}{percent:.0}% {pos}/{len} ({speed}/s, {eta})", 287 | elapsed = ClockDuration(elapsed), 288 | bar_placeholder = if self.mode == ProgressDrawMode::Interactive { 289 | "\x00" 290 | } else { 291 | "" 292 | }, 293 | percent = ratio * 100.0, 294 | pos = BinarySize(self.pos), 295 | len = BinarySize(self.len), 296 | speed = BinarySize(self.speed()), 297 | eta = HumanDuration(eta), 298 | ); 299 | 300 | if self.mode == ProgressDrawMode::Interactive { 301 | let term_width = terminal::size().unwrap_or((80, 24)).0 as usize; 302 | // result.len() includes the placeholder (+1), which works because 303 | // there is a space after the bar. 304 | let bar_width = term_width.saturating_sub(result.len()); 305 | let bar_consumed = (ratio * bar_width as f64).round() as usize; 306 | let bar_remaining = bar_width.saturating_sub(bar_consumed); 307 | 308 | if bar_width != 0 { 309 | result = result.replace('\x00', &format!( 310 | "{}{} ", 311 | "#".repeat(bar_consumed).cyan(), 312 | "-".repeat(bar_remaining).blue(), 313 | )); 314 | } 315 | 316 | self.term 317 | .queue(Hide)? 318 | .queue(Clear(ClearType::CurrentLine))? 319 | .queue(MoveToColumn(0))?; 320 | } else { 321 | result.push('\n'); 322 | }; 323 | 324 | self.term 325 | .queue(Print(result))? 326 | .flush()?; 327 | 328 | self.last_draw = Instant::now(); 329 | 330 | Ok(()) 331 | } 332 | 333 | /// Compute the expected ETA over a 10 second window. 334 | fn eta(&self) -> Duration { 335 | let s = self.speed.units_per_sec(); 336 | if s > 0.0 { 337 | Duration::from_secs_f64((self.len.saturating_sub(self.pos)) as f64 / s) 338 | } else { 339 | Duration::new(0, 0) 340 | } 341 | } 342 | 343 | /// Compute the progress speed as progress units per second over a 10 second 344 | /// window. 345 | fn speed(&self) -> u64 { 346 | self.speed.units_per_sec() as u64 347 | } 348 | } 349 | 350 | impl Drop for ProgressBar { 351 | fn drop(&mut self) { 352 | let _ = self.finish(); 353 | } 354 | } 355 | 356 | #[cfg(test)] 357 | mod tests { 358 | use std::{ 359 | io::{self, Error, ErrorKind}, 360 | rc::Rc, 361 | str, 362 | sync::Mutex, 363 | }; 364 | 365 | use super::*; 366 | 367 | struct TestTerm { 368 | buf: Rc>, 369 | tty: bool, 370 | } 371 | 372 | impl TestTerm { 373 | fn new(tty: bool) -> Self { 374 | Self { 375 | buf: Rc::new(Mutex::new(String::new())), 376 | tty, 377 | } 378 | } 379 | } 380 | 381 | impl Write for TestTerm { 382 | fn write(&mut self, buf: &[u8]) -> io::Result { 383 | let s = str::from_utf8(buf) 384 | .map_err(|e| Error::new(ErrorKind::InvalidData, e))?; 385 | self.buf.lock().unwrap().push_str(s); 386 | Ok(buf.len()) 387 | } 388 | 389 | fn flush(&mut self) -> io::Result<()> { 390 | Ok(()) 391 | } 392 | } 393 | 394 | impl IsTty for TestTerm { 395 | fn is_tty(&self) -> bool { 396 | self.tty 397 | } 398 | } 399 | 400 | impl IsTty for &mut TestTerm { 401 | fn is_tty(&self) -> bool { 402 | self.tty 403 | } 404 | } 405 | 406 | #[test] 407 | fn test_non_output_components() { 408 | let mut term = TestTerm::new(false); 409 | let buf = term.buf.clone(); 410 | let mut bar = ProgressBar::new(&mut term, 10); 411 | 412 | bar.set_mode(Some(ProgressDrawMode::None)); 413 | assert_eq!(bar.mode(), ProgressDrawMode::None); 414 | 415 | assert_eq!(bar.fps(), 0.0); 416 | bar.set_fps(1.0); 417 | assert_eq!(bar.fps(), 1.0); 418 | 419 | assert_eq!(bar.position(), 0); 420 | bar.set_position(5).unwrap(); 421 | assert_eq!(bar.position(), 5); 422 | 423 | assert_eq!(bar.length(), 10); 424 | bar.set_length(15).unwrap(); 425 | assert_eq!(bar.length(), 15); 426 | 427 | bar.println("hello").unwrap(); 428 | 429 | drop(bar); 430 | 431 | assert_eq!(*buf.lock().unwrap(), ""); 432 | } 433 | 434 | #[test] 435 | fn test_non_tty() { 436 | let mut term = TestTerm::new(false); 437 | let buf = term.buf.clone(); 438 | let mut bar = ProgressBar::new(&mut term, 10); 439 | 440 | assert_eq!(bar.mode(), ProgressDrawMode::Append); 441 | assert_eq!(bar.fps(), 0.2); 442 | assert_eq!(bar.position(), 0); 443 | assert_eq!(bar.length(), 10); 444 | 445 | bar.set_fps(0.0); 446 | assert_eq!(*buf.lock().unwrap(), ""); 447 | 448 | bar.advance(1).unwrap(); 449 | assert_eq!(bar.position(), 1); 450 | { 451 | let mut output = buf.lock().unwrap(); 452 | let pieces: Vec<&str> = output.split(' ').collect(); 453 | assert_eq!(pieces[1], "10%"); 454 | assert_eq!(pieces[2], "1B/10B"); 455 | output.clear(); 456 | } 457 | 458 | bar.set_position(10).unwrap(); 459 | assert_eq!(bar.position(), 10); 460 | { 461 | let mut output = buf.lock().unwrap(); 462 | let pieces: Vec<&str> = output.split(' ').collect(); 463 | assert_eq!(pieces[1], "100%"); 464 | assert_eq!(pieces[2], "10B/10B"); 465 | output.clear(); 466 | } 467 | 468 | bar.keep().unwrap(); 469 | assert_eq!(buf.lock().unwrap().len(), 0); 470 | 471 | bar.println("hello").unwrap(); 472 | { 473 | let mut output = buf.lock().unwrap(); 474 | assert_eq!(*output, "hello\n"); 475 | output.clear(); 476 | } 477 | 478 | bar.reset().unwrap(); 479 | { 480 | let mut output = buf.lock().unwrap(); 481 | let pieces: Vec<&str> = output.split(' ').collect(); 482 | assert_eq!(pieces[1], "0%"); 483 | assert_eq!(pieces[2], "0B/10B"); 484 | output.clear(); 485 | } 486 | 487 | drop(bar); 488 | } 489 | 490 | #[test] 491 | fn test_tty() { 492 | let mut term = TestTerm::new(true); 493 | let buf = term.buf.clone(); 494 | let mut bar = ProgressBar::new(&mut term, 10); 495 | 496 | assert_eq!(bar.mode(), ProgressDrawMode::Interactive); 497 | assert_eq!(bar.fps(), 15.0); 498 | assert_eq!(bar.position(), 0); 499 | assert_eq!(bar.length(), 10); 500 | 501 | bar.set_fps(0.0); 502 | assert_eq!(*buf.lock().unwrap(), ""); 503 | 504 | bar.advance(1).unwrap(); 505 | assert_eq!(bar.position(), 1); 506 | { 507 | let mut output = buf.lock().unwrap(); 508 | let pieces: Vec<&str> = output.split(' ').collect(); 509 | assert!(pieces[1].starts_with("\u{1b}")); 510 | assert_eq!(pieces[2], "10%"); 511 | assert_eq!(pieces[3], "1B/10B"); 512 | output.clear(); 513 | } 514 | 515 | bar.set_position(10).unwrap(); 516 | assert_eq!(bar.position(), 10); 517 | { 518 | let mut output = buf.lock().unwrap(); 519 | let pieces: Vec<&str> = output.split(' ').collect(); 520 | assert!(pieces[1].starts_with("\u{1b}")); 521 | assert_eq!(pieces[2], "100%"); 522 | assert_eq!(pieces[3], "10B/10B"); 523 | output.clear(); 524 | } 525 | 526 | bar.keep().unwrap(); 527 | { 528 | let mut output = buf.lock().unwrap(); 529 | assert_eq!(output.bytes().last().unwrap(), b'\n'); 530 | output.clear(); 531 | } 532 | 533 | bar.println("hello").unwrap(); 534 | { 535 | let mut output = buf.lock().unwrap(); 536 | let lines: Vec<&str> = output.lines().collect(); 537 | assert!(lines[0].ends_with("hello")); 538 | let pieces: Vec<&str> = lines[1].split(' ').collect(); 539 | assert!(pieces[1].starts_with("\u{1b}")); 540 | assert_eq!(pieces[2], "100%"); 541 | assert_eq!(pieces[3], "10B/10B"); 542 | output.clear(); 543 | } 544 | 545 | bar.reset().unwrap(); 546 | { 547 | let mut output = buf.lock().unwrap(); 548 | let pieces: Vec<&str> = output.split(' ').collect(); 549 | assert!(pieces[1].starts_with("\u{1b}")); 550 | assert_eq!(pieces[2], "0%"); 551 | assert_eq!(pieces[3], "0B/10B"); 552 | output.clear(); 553 | } 554 | 555 | drop(bar); 556 | } 557 | } 558 | -------------------------------------------------------------------------------- /progresslib/src/progress/format.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fmt, 3 | time::Duration, 4 | }; 5 | 6 | use number_prefix::NumberPrefix; 7 | 8 | /// Type to represent a file size in base 2 units. 9 | #[derive(Debug)] 10 | pub struct BinarySize(pub u64); 11 | 12 | impl fmt::Display for BinarySize { 13 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 14 | match NumberPrefix::binary(self.0 as f64) { 15 | NumberPrefix::Standalone(number) => { 16 | write!(f, "{number:.0}B") 17 | } 18 | NumberPrefix::Prefixed(prefix, number) => { 19 | write!(f, "{number:.2}{prefix}B") 20 | } 21 | } 22 | } 23 | } 24 | 25 | const SECS_PER_MINUTE: u64 = 60; 26 | const SECS_PER_HOUR: u64 = 60 * SECS_PER_MINUTE; 27 | const SECS_PER_DAY: u64 = 24 * SECS_PER_HOUR; 28 | const SECS_PER_YEAR: u64 = (365.25 * SECS_PER_DAY as f64) as u64; 29 | const SECS_PER_MONTH: u64 = SECS_PER_YEAR / 12; 30 | 31 | /// Type to represent a duration in human readable form. 32 | #[derive(Debug)] 33 | pub struct HumanDuration(pub Duration); 34 | 35 | impl fmt::Display for HumanDuration { 36 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 37 | let secs = self.0.as_secs(); 38 | let nanos = u64::from(self.0.subsec_nanos()); 39 | 40 | if secs == 0 && nanos == 0 { 41 | return if f.alternate() { 42 | f.write_str("0 seconds") 43 | } else { 44 | f.write_str("0s") 45 | }; 46 | } 47 | 48 | let years = secs / SECS_PER_YEAR; 49 | let remain = secs % SECS_PER_YEAR; 50 | 51 | let months = remain / SECS_PER_MONTH; 52 | let remain = remain % SECS_PER_MONTH; 53 | 54 | let days = remain / SECS_PER_DAY; 55 | let remain = remain % SECS_PER_DAY; 56 | 57 | let hours = remain / SECS_PER_HOUR; 58 | let remain = remain % SECS_PER_HOUR; 59 | 60 | let minutes = remain / SECS_PER_MINUTE; 61 | let remain = remain % SECS_PER_MINUTE; 62 | 63 | let secs = remain; 64 | 65 | let millis = nanos / 1_000_000; 66 | let micros = nanos / 1_000 % 1_000; 67 | let nanos = nanos % 1_000; 68 | 69 | let mut first = true; 70 | 71 | for (value, full, abbrev) in &[ 72 | (years, "year", "y"), 73 | (months, "month", "M"), 74 | (days, "day", "d"), 75 | (hours, "hour", "h"), 76 | (minutes, "minute", "m"), 77 | (secs, "second", "s"), 78 | (millis, "millisecond", "ms"), 79 | (micros, "microsecond", "us"), 80 | (nanos, "nanosecond", "ns"), 81 | ] { 82 | if *value > 0 { 83 | if first { 84 | first = false; 85 | } else { 86 | f.write_str(" ")?; 87 | } 88 | 89 | write!(f, "{value}")?; 90 | 91 | if f.alternate() { 92 | write!(f, " {}{}", full, if *value > 1 { "s" } else { "" })?; 93 | } else { 94 | f.write_str(abbrev)?; 95 | } 96 | } 97 | } 98 | 99 | Ok(()) 100 | } 101 | } 102 | 103 | /// Type to represent a duration in a clock-like form. 104 | #[derive(Debug)] 105 | pub struct ClockDuration(pub Duration); 106 | 107 | impl fmt::Display for ClockDuration { 108 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 109 | let secs = self.0.as_secs(); 110 | let nanos = u64::from(self.0.subsec_nanos()); 111 | 112 | let hours = secs / SECS_PER_HOUR; 113 | let remain = secs % SECS_PER_HOUR; 114 | 115 | let minutes = remain / SECS_PER_MINUTE; 116 | let remain = remain % SECS_PER_MINUTE; 117 | 118 | let secs = remain; 119 | 120 | write!(f, "{hours:02}:{minutes:02}:{secs:02}")?; 121 | 122 | if nanos > 0 || f.alternate() { 123 | write!(f, ".{nanos:09}")?; 124 | } 125 | 126 | Ok(()) 127 | } 128 | } 129 | 130 | #[cfg(test)] 131 | mod tests { 132 | use super::*; 133 | 134 | #[test] 135 | fn test_binary_size() { 136 | assert_eq!(BinarySize(0).to_string(), "0B"); 137 | assert_eq!(BinarySize(1023).to_string(), "1023B"); 138 | assert_eq!(BinarySize(1024).to_string(), "1.00KiB"); 139 | assert_eq!(BinarySize(1536).to_string(), "1.50KiB"); 140 | assert_eq!(BinarySize(1024 * 1024).to_string(), "1.00MiB"); 141 | assert_eq!(BinarySize(1024 * 1024 * 1024).to_string(), "1.00GiB"); 142 | assert_eq!(BinarySize(1024 * 1024 * 1024 * 1024).to_string(), "1.00TiB"); 143 | assert_eq!(BinarySize(1024 * 1024 * 1024 * 1024 * 1024).to_string(), "1.00PiB"); 144 | assert_eq!(BinarySize(1024 * 1024 * 1024 * 1024 * 1024 * 1024).to_string(), "1.00EiB"); 145 | } 146 | 147 | #[test] 148 | fn test_human_duration() { 149 | // (secs, nanos, short, long) 150 | let test_cases = [ 151 | (0, 0, "0s", 152 | "0 seconds"), 153 | (0, 1, "1ns", 154 | "1 nanosecond"), 155 | (0, 1_001, "1us 1ns", 156 | "1 microsecond 1 nanosecond"), 157 | (0, 1_001_001, "1ms 1us 1ns", 158 | "1 millisecond 1 microsecond 1 nanosecond"), 159 | (1, 1_001_001, "1s 1ms 1us 1ns", 160 | "1 second 1 millisecond 1 microsecond 1 nanosecond"), 161 | (61, 1_001_001, "1m 1s 1ms 1us 1ns", 162 | "1 minute 1 second 1 millisecond 1 microsecond 1 nanosecond"), 163 | (3661, 1_001_001, "1h 1m 1s 1ms 1us 1ns", 164 | "1 hour 1 minute 1 second 1 millisecond 1 microsecond 1 nanosecond"), 165 | (90061, 1_001_001, "1d 1h 1m 1s 1ms 1us 1ns", 166 | "1 day 1 hour 1 minute 1 second 1 millisecond 1 microsecond 1 nanosecond"), 167 | (2719861, 1_001_001, "1M 1d 1h 1m 1s 1ms 1us 1ns", 168 | "1 month 1 day 1 hour 1 minute 1 second 1 millisecond 1 microsecond 1 nanosecond"), 169 | (34277461, 1_001_001, "1y 1M 1d 1h 1m 1s 1ms 1us 1ns", 170 | "1 year 1 month 1 day 1 hour 1 minute 1 second 1 millisecond 1 microsecond 1 nanosecond"), 171 | (68554922, 2_002_002, "2y 2M 2d 2h 2m 2s 2ms 2us 2ns", 172 | "2 years 2 months 2 days 2 hours 2 minutes 2 seconds 2 milliseconds 2 microseconds 2 nanoseconds"), 173 | ]; 174 | 175 | for &(secs, nanos, short, long) in test_cases.iter() { 176 | let d = HumanDuration(Duration::new(secs, nanos)); 177 | assert_eq!(format!("{d}"), short); 178 | assert_eq!(format!("{d:#}"), long); 179 | } 180 | } 181 | 182 | #[test] 183 | fn test_clock_duration() { 184 | // (secs, nanos, short, long) 185 | let test_cases = [ 186 | (0, 0, "00:00:00", "00:00:00.000000000"), 187 | (0, 1, "00:00:00.000000001", "00:00:00.000000001"), 188 | (0, 1_001, "00:00:00.000001001", "00:00:00.000001001"), 189 | (0, 1_001_001, "00:00:00.001001001", "00:00:00.001001001"), 190 | (1, 1_001_001, "00:00:01.001001001", "00:00:01.001001001"), 191 | (61, 1_001_001, "00:01:01.001001001", "00:01:01.001001001"), 192 | (3661, 1_001_001, "01:01:01.001001001", "01:01:01.001001001"), 193 | (u64::MAX, 999_999_999, "5124095576030431:00:15.999999999", 194 | "5124095576030431:00:15.999999999"), 195 | ]; 196 | 197 | for &(secs, nanos, short, long) in test_cases.iter() { 198 | let d = ClockDuration(Duration::new(secs, nanos)); 199 | assert_eq!(format!("{d}"), short); 200 | assert_eq!(format!("{d:#}"), long); 201 | } 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /samfuslib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "samfuslib" 3 | version = "0.1.6" 4 | authors = ["Andrew Gunnerson "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | aes = "0.8.2" 9 | base64 = "0.21.0" 10 | block-padding = "0.3.2" 11 | bytes = "1.4.0" 12 | cbc = "0.1.2" 13 | cipher = { version = "0.4.3", features = ["alloc", "block-padding"] } 14 | futures-core = "0.3.26" 15 | hex-literal = "0.4.1" 16 | log = "0.4.17" 17 | md5 = "0.7.0" 18 | reqwest = { version = "0.11.14", features = ["cookies", "stream"] } 19 | thiserror = "1.0.38" 20 | xmltree = "0.10.3" 21 | 22 | [dev-dependencies] 23 | assert_matches = "1.5.0" 24 | -------------------------------------------------------------------------------- /samfuslib/src/crypto.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | cmp, 3 | convert::TryInto, 4 | }; 5 | 6 | use aes::{Aes128, Aes256}; 7 | use block_padding::{NoPadding, Padding, Pkcs7}; 8 | use cbc::{Decryptor, Encryptor}; 9 | use cipher::{BlockDecryptMut, BlockEncryptMut, KeyInit, KeyIvInit}; 10 | use cipher::generic_array::{ArrayLength, GenericArray, typenum::{U32, Unsigned}}; 11 | use thiserror::Error; 12 | 13 | /// Block size for encrypted data 14 | pub type BlockSize = U32; 15 | /// Key size 16 | pub type KeySize = U32; 17 | 18 | #[derive(Debug, Error)] 19 | pub enum CryptoError { 20 | #[error("Fixed key has incorrect length")] 21 | IncorrectFixedKeyLength, 22 | #[error("Flexible key suffix has incorrect length")] 23 | IncorrectFlexibleKeySuffixLength, 24 | #[error("Ciphertext is smaller than block size")] 25 | CiphertextTooSmall, 26 | } 27 | 28 | /// Container for holding FUS encryption keys. 29 | #[derive(Clone, Debug)] 30 | pub struct FusKeys { 31 | pub fixed_key: [u8; 32], 32 | pub flexible_key_suffix: [u8; 16], 33 | } 34 | 35 | impl FusKeys { 36 | /// Load keys from the specified byte slices. The fixed key should be 32 37 | /// bytes and the flexible key suffix should be 16 bytes. 38 | pub fn new( 39 | fixed_key: &[u8], 40 | flexible_key_suffix: &[u8], 41 | ) -> Result { 42 | Ok(Self { 43 | fixed_key: fixed_key.try_into() 44 | .map_err(|_| CryptoError::IncorrectFixedKeyLength)?, 45 | flexible_key_suffix: flexible_key_suffix.try_into() 46 | .map_err(|_| CryptoError::IncorrectFlexibleKeySuffixLength)?, 47 | }) 48 | } 49 | 50 | /// Derive the FUS "flexible key" from a list of indexes of the fixed key + 51 | /// a hardcoded suffix. 52 | pub fn get_flexible_key_from_indexes(&self, key_indexes: &[usize]) -> Vec { 53 | key_indexes.iter() 54 | .map(|i| self.fixed_key[*i]) 55 | .chain(self.flexible_key_suffix.iter().copied()) 56 | .collect() 57 | } 58 | 59 | /// Derive the FUS "flexible key" from the given base. Mod 16 is applied to 60 | /// each element to form the fixed key index list. 61 | pub fn get_flexible_key(&self, key_base: &[u8]) -> Vec { 62 | let indexes: Vec = key_base.iter() 63 | .map(|x| (x % 16) as usize) 64 | .collect(); 65 | 66 | self.get_flexible_key_from_indexes(&indexes) 67 | } 68 | } 69 | 70 | /// Pad byte array to specified block size and optionally truncate to one block. 71 | fn pad>(mut data: &[u8], truncate_to_block_size: bool) -> Vec { 72 | let block_size = B::USIZE; 73 | 74 | if truncate_to_block_size { 75 | data = &data[..cmp::min(data.len(), block_size)]; 76 | } 77 | let mut buf = data.to_vec(); 78 | 79 | if data.is_empty() || data.len() % block_size != 0 { 80 | buf.resize((data.len() / block_size + 1) * block_size, 0); 81 | 82 | let last_block_offset = buf.len() - block_size; 83 | let last_block = &mut buf[last_block_offset..]; 84 | let ga_last_block = GenericArray::::from_mut_slice(last_block); 85 | Pkcs7::pad(ga_last_block, data.len() % block_size); 86 | } 87 | 88 | buf 89 | } 90 | 91 | /// Type for performing AES operations in the way that FUS expects. Notably: 92 | /// * The key is PKCS#7 padded to 32 bytes if it is too short or truncated to 93 | /// 32 bytes if it is too long. 94 | /// * The data uses a 32-byte block size. It is PKCS#7 padded to the next 95 | /// 32-byte boundary. During decryption, if the input is a multiple of 96 | /// 32-bytes and the last block looks like it has padding, then the padding 97 | /// will be truncated. There is no way to tell the difference between padding 98 | /// and some bytes that look like padding. 99 | /// 100 | /// If AES-NI is supported, it will be used. 101 | pub struct FusAes256 { 102 | dec: Decryptor, 103 | enc: Encryptor, 104 | } 105 | 106 | impl FusAes256 { 107 | /// Create a new cipher instance to perform AES operations in the way that 108 | /// FUS expects. The key will be PKCS#7 padded to 32 bytes if it is too 109 | /// short or truncated to 32 bytes if it is too long. 110 | pub fn new(key: &[u8]) -> Self { 111 | let padded_key = pad::(key, true); 112 | let iv = &padded_key[..16]; 113 | 114 | let dec = Decryptor::::new_from_slices(&padded_key, iv).unwrap(); 115 | let enc = Encryptor::::new_from_slices(&padded_key, iv).unwrap(); 116 | Self { 117 | dec, 118 | enc, 119 | } 120 | } 121 | 122 | /// Encrypt the provided plaintext data. The data will be PKCS#7 padded to 123 | /// the next 32-byte boundary. 124 | pub fn encrypt(self, data: &[u8]) -> Vec { 125 | let mut buf = pad::(data, false); 126 | let buf_size = buf.len(); 127 | 128 | self.enc.encrypt_padded_mut::(&mut buf, buf_size).unwrap(); 129 | 130 | buf 131 | } 132 | 133 | /// Decrypt the provided FUS ciphertext. The returned plain text will be 134 | /// PKCS#7 unpadded. 135 | pub fn decrypt(self, data: &[u8]) -> Result, CryptoError> { 136 | let mut plaintext = self.dec.decrypt_padded_vec_mut::(data) 137 | .map_err(|_| CryptoError::CiphertextTooSmall)?; 138 | 139 | if !plaintext.is_empty() { 140 | let last_block_offset = plaintext.len() - BlockSize::USIZE; 141 | let last_block = &mut plaintext[last_block_offset..]; 142 | let ga_last_block = GenericArray::::from_mut_slice(last_block); 143 | 144 | let plaintext_len = match Pkcs7::unpad(ga_last_block) { 145 | Ok(s) => s.len(), 146 | Err(_) => plaintext.len(), // Assume unpadded 147 | }; 148 | 149 | plaintext.resize(plaintext_len, 0); 150 | } 151 | Ok(plaintext) 152 | } 153 | } 154 | 155 | /// Type for decrypting files downloaded from FUS. This is just normal 156 | /// AES128-ECB with no padding. 157 | /// 158 | /// If AES-NI is supported, it will be used. 159 | #[derive(Clone)] 160 | pub struct FusFileAes128(Aes128); 161 | 162 | impl FusFileAes128 { 163 | /// Create a new cipher instance for decrypting FUS files. 164 | pub fn new(key: &[u8]) -> Self { 165 | let ga_key = GenericArray::from_slice(key); 166 | let cipher = Aes128::new(ga_key); 167 | Self(cipher) 168 | } 169 | 170 | /// Decrypt the provided ciphertext in-place. 171 | pub fn decrypt_in_place(self, buf: &mut [u8]) -> Result<(), CryptoError> { 172 | self.0.decrypt_padded_mut::(buf) 173 | .map_err(|_| CryptoError::CiphertextTooSmall)?; 174 | 175 | Ok(()) 176 | } 177 | } 178 | 179 | #[cfg(test)] 180 | mod tests { 181 | use assert_matches::assert_matches; 182 | use cipher::generic_array::typenum::U4; 183 | use hex_literal::hex; 184 | 185 | use super::*; 186 | 187 | #[test] 188 | fn test_pad() { 189 | let key = b"0123"; 190 | assert_eq!(pad::(key, false), key); 191 | assert_eq!(pad::(key, true), key); 192 | 193 | let key = b""; 194 | assert_eq!(pad::(key, false), [4, 4, 4, 4]); 195 | assert_eq!(pad::(key, true), [4, 4, 4, 4]); 196 | 197 | let key = b"01234"; 198 | assert_eq!(pad::(key, false), b"01234\x03\x03\x03"); 199 | assert_eq!(pad::(key, true), b"0123"); 200 | 201 | let key = b"01234567"; 202 | assert_eq!(pad::(key, false), b"01234567"); 203 | assert_eq!(pad::(key, true), b"0123"); 204 | } 205 | 206 | #[test] 207 | fn test_create_flexible_key() { 208 | let keys = FusKeys::new( 209 | b"testing_testing_testing_testing_", 210 | b"testing_testing_", 211 | ).unwrap(); 212 | 213 | assert_eq!(keys.get_flexible_key_from_indexes(&[]), b"testing_testing_"); 214 | assert_eq!(keys.get_flexible_key_from_indexes(&[1, 2, 3]), b"esttesting_testing_"); 215 | 216 | assert_eq!(keys.get_flexible_key(b""), b"testing_testing_"); 217 | assert_eq!(keys.get_flexible_key(b"abc"), b"esttesting_testing_"); 218 | } 219 | 220 | #[test] 221 | fn test_encrypt() { 222 | // Key smaller than IV length 223 | assert_eq!(FusAes256::new(b"testing_").encrypt(b""), 224 | hex!("ba575394750d7028b1ebf23bb82ad8978a2bb2183a0db9ca0d01f3f18c764eb4")); 225 | 226 | // Key equal to IV length 227 | assert_eq!(FusAes256::new(b"testing_testing_").encrypt(b""), 228 | hex!("dd3b9041a4d4f8be4c6aa4cee25776670d3d7ce4383f68f65bbb037575beb7cd")); 229 | 230 | // Key equal to max key length 231 | assert_eq!(FusAes256::new(b"testing_testing_testing_testing_").encrypt(b""), 232 | hex!("bccdc940c00de876757aa90693b01dab21ebefa70e46b4cb4ae2343b75c460d3")); 233 | 234 | // Key larger than max key length (truncation) 235 | assert_eq!(FusAes256::new(b"testing_testing_testing_testing_testing_").encrypt(b""), 236 | hex!("bccdc940c00de876757aa90693b01dab21ebefa70e46b4cb4ae2343b75c460d3")); 237 | 238 | // Data equal to block size 239 | assert_eq!(FusAes256::new(b"testing_testing_testing_testing_testing_") 240 | .encrypt(b"testing_testing_testing_testing_"), 241 | hex!("cab26214eca0a48c67ab89db59d4f6341d9dee81cc7e31906d8161a9eb90aad6")); 242 | 243 | // Data not equal to block size 244 | assert_eq!(FusAes256::new(b"testing_testing_testing_testing_testing_") 245 | .encrypt(b"testing_testing_"), 246 | hex!("cab26214eca0a48c67ab89db59d4f634b93539dbbc9b9fb37052902f83f35740")); 247 | } 248 | 249 | #[test] 250 | fn test_decrypt() { 251 | // Empty ciphertext 252 | assert_matches!(FusAes256::new(b"testing_testing_").decrypt(b""), 253 | Ok(x) if x == b""); 254 | 255 | // Ciphertext not multiple of block size 256 | assert_matches!(FusAes256::new(b"testing_testing_").decrypt(&[0]), 257 | Err(CryptoError::CiphertextTooSmall)); 258 | 259 | // Ciphertext with invalid padding should not be unpadded 260 | assert_matches!(FusAes256::new(b"testing_testing_") 261 | .decrypt(&hex!("ea016b97268c45b6201797452df6c688ae6fe6a2b756275f4528464339aca48e")), 262 | Ok(x) if x == hex!("74657374696e675f74657374696e675f10101010101010101010101010101002")); 263 | 264 | // Padding is correctly removed 265 | assert_matches!(FusAes256::new(b"testing_testing_") 266 | .decrypt(&hex!("ea016b97268c45b6201797452df6c688a70500f3e18d557474c10a55758b07d9")), 267 | Ok(x) if x == hex!("74657374696e675f74657374696e675f")); 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /samfuslib/src/fus.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | crypto::{CryptoError, FusAes256, FusKeys}, 3 | version::{FwVersion, ParseFwVersionError}, 4 | }; 5 | 6 | use std::{ 7 | borrow::Cow, 8 | convert::TryInto, 9 | fmt, 10 | ops::Range, 11 | path::Path, 12 | str, 13 | }; 14 | 15 | use base64::{ 16 | Engine, 17 | engine::general_purpose::STANDARD, 18 | }; 19 | use bytes::Bytes; 20 | use futures_core::Stream; 21 | use log::debug; 22 | use reqwest::{ 23 | header::{AUTHORIZATION, CONTENT_LENGTH, RANGE}, 24 | RequestBuilder, Response, 25 | StatusCode, 26 | }; 27 | use thiserror::Error; 28 | use xmltree::{Element, XMLNode}; 29 | 30 | const FOTA_BASE_URL: &str = "https://fota-cloud-dn.ospserver.net"; 31 | const FUS_BASE_URL: &str = "https://neofussvr.sslcs.cdngc.net"; 32 | const DOWNLOAD_BASE_URL: &str = "https://cloud-neofussvr.samsungmobile.com"; 33 | const NON_UTF8_MSG: &str = "[Non-UTF-8 data]"; 34 | 35 | fn to_utf8_or_error_string(data: &[u8]) -> &str { 36 | str::from_utf8(data).unwrap_or(NON_UTF8_MSG) 37 | } 38 | 39 | #[derive(Debug, Error)] 40 | pub enum FusError { 41 | #[error("Server did not provide a nonce value")] 42 | NonceNotFound, 43 | #[error("Nonce is not exactly 16 bytes")] 44 | NonceInvalidSize, 45 | #[error("The latest firmware could not be found")] 46 | FirmwareNotFound, 47 | #[error("Expected HTTP {0}, but got HTTP {1}")] 48 | BadHttpResponse(StatusCode, StatusCode), 49 | #[error("Received unsuccessful FUS response: {0}")] 50 | FusBadResponse(String), 51 | #[error("Could not find field '{0}' in FUS response")] 52 | FusMissingField(String), 53 | #[error("Could not parse the value for field '{0}': '{1}'")] 54 | FusBadField(String, String), 55 | #[error("Crypto error: {0}")] 56 | CryptoError(#[from] CryptoError), 57 | #[error("Failed to parse version string: {0}")] 58 | VersionParseError(#[from] ParseFwVersionError), 59 | #[error("Failed to decode base64 data: {0}")] 60 | Base64DecodeError(#[from] base64::DecodeError), 61 | #[error("HTTP request error: {0}")] 62 | RequestError(#[from] reqwest::Error), 63 | #[error("XML parse error: {0}")] 64 | XmlParseError(#[from] xmltree::ParseError), 65 | #[error("XML error: {0}")] 66 | XmlError(#[from] xmltree::Error), 67 | } 68 | 69 | /// A type representing the Authorization field for FUS requests. 70 | #[derive(Debug)] 71 | struct Authorization { 72 | pub nonce: String, 73 | pub signature: String, 74 | pub nc: String, 75 | pub type_: String, 76 | pub realm: String, 77 | pub newauth: bool, 78 | } 79 | 80 | impl Authorization { 81 | /// Construct a new instance with no component fields set and the new auth 82 | /// mechanism enabled. Same as [`Self::default()`]. 83 | fn new() -> Self { 84 | Self::default() 85 | } 86 | 87 | /// Construct a new instance with the specified nonce signature and the new 88 | /// auth mechanism enabled. 89 | fn with_signature(signature: &str) -> Self { 90 | Self { 91 | signature: signature.to_string(), 92 | ..Default::default() 93 | } 94 | } 95 | } 96 | 97 | impl Default for Authorization { 98 | fn default() -> Self { 99 | Self { 100 | nonce: Default::default(), 101 | signature: Default::default(), 102 | nc: Default::default(), 103 | type_: Default::default(), 104 | realm: Default::default(), 105 | // We do not support the legacy auth mechanism (unencrypted nonces) 106 | // so make the new mechanism the default 107 | newauth: true, 108 | } 109 | } 110 | } 111 | 112 | impl fmt::Display for Authorization { 113 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 114 | write!( 115 | f, 116 | "FUS nonce=\"{}\", signature=\"{}\", nc=\"{}\", type=\"{}\", realm=\"{}\", newauth=\"{}\"", 117 | self.nonce, 118 | self.signature, 119 | self.nc, 120 | self.type_, 121 | self.realm, 122 | u8::from(self.newauth), 123 | ) 124 | } 125 | } 126 | 127 | #[derive(Clone, Copy)] 128 | enum LogicCheckType<'a> { 129 | Data(&'a [u8]), 130 | Filename(&'a str), 131 | } 132 | 133 | /// A type representing a FUS nonce value. 134 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] 135 | struct Nonce { 136 | // The official implementation tries to convert the AES flexible key from 137 | // the platform string encoding to UTF-8 into a 33-byte NULL-terminated 138 | // buffer. It never checks the return value, but relies on the data being 139 | // written to the buffer. We can reasonably assume that the key is 32 bytes, 140 | // meaning the nonce must be at most 16 bytes. Many other functions, such as 141 | // one for computing the value expect the nonce to be at least 142 | // 16 bytes, so we can conclude that it must be exactly 16 bytes. 143 | data: [u8; 16], 144 | } 145 | 146 | impl Nonce { 147 | /// Create instance from a byte slice containing the nonce. 148 | /// [`FusError::InvalidNonceSize`] is returned if the slice is not 16 bytes. 149 | pub fn from_slice(data: &[u8]) -> Result { 150 | Ok(Self { 151 | data: data.try_into().map_err(|_| FusError::NonceInvalidSize)?, 152 | }) 153 | } 154 | 155 | /// Get byte slice containing the nonce. The slice is guaranteed to always 156 | /// be 16 bytes. 157 | pub fn as_slice(&self) -> &[u8] { 158 | &self.data 159 | } 160 | 161 | /// Create instance from a fixed-key-encrypted nonce value. 162 | pub fn from_encrypted(keys: &FusKeys, data: &[u8]) -> Result { 163 | let decoded = STANDARD.decode(data)?; 164 | let plaintext = FusAes256::new(&keys.fixed_key).decrypt(&decoded)?; 165 | Self::from_slice(&plaintext) 166 | } 167 | 168 | /// Convert nonce to fixed-key-encrypted nonce. 169 | pub fn to_encrypted(self, keys: &FusKeys) -> String { 170 | STANDARD.encode(FusAes256::new(&keys.fixed_key).encrypt(&self.data)) 171 | } 172 | 173 | /// Get the nonce signature to be used in the Authorization header for FUS 174 | /// requests. 175 | fn to_signature(self, keys: &FusKeys) -> String { 176 | let key = keys.get_flexible_key(self.as_slice()); 177 | let ciphertext = FusAes256::new(&key).encrypt(self.as_slice()); 178 | 179 | STANDARD.encode(ciphertext) 180 | } 181 | 182 | /// Get full Authorization header value containing the nonce signature. 183 | fn to_authorization(self, keys: &FusKeys) -> Authorization { 184 | Authorization::with_signature(&self.to_signature(keys)) 185 | } 186 | 187 | /// Get the scrambled nonce value to be used in the `` XML tag 188 | /// of FUS requests. 189 | fn to_logic_check(self, lc_type: LogicCheckType) -> String { 190 | match lc_type { 191 | LogicCheckType::Data(data) => { 192 | if data.is_empty() { 193 | return String::new(); 194 | } 195 | 196 | self.as_slice().iter() 197 | .map(|c| data[(*c as usize & 0xf) % data.len()] as char) 198 | .collect() 199 | } 200 | LogicCheckType::Filename(filename) => { 201 | let mut data = filename.as_bytes(); 202 | 203 | if let Some(n) = data.iter().position(|x| *x == b'.') { 204 | data = &data[..n]; 205 | } 206 | if data.len() > 16 { 207 | data = &data[data.len() - 16..]; 208 | } 209 | 210 | self.to_logic_check(LogicCheckType::Data(data)) 211 | } 212 | } 213 | } 214 | } 215 | 216 | impl fmt::Display for Nonce { 217 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 218 | // Intentionally keep error text at 16 bytes 219 | write!(f, "{}", to_utf8_or_error_string(&self.data)) 220 | } 221 | } 222 | 223 | #[derive(Debug)] 224 | pub struct FirmwareInfo { 225 | /// Firmware version 226 | pub version: FwVersion, 227 | /// Friendly version name 228 | pub version_name: String, 229 | /// Firmware OS/platform 230 | pub platform: String, 231 | /// Model number 232 | pub model: String, 233 | /// Human-readable model/marketing name 234 | pub model_name: String, 235 | /// [Unknown] Model type number 236 | pub model_type: u8, 237 | /// Region code 238 | pub region: String, 239 | /// Firmware download path component 240 | pub path: String, 241 | /// Firmware filename. Guaranteed to have no directory component 242 | pub filename: String, 243 | /// Firmware size in bytes 244 | pub size: u64, 245 | /// Firmware CRC32 checksum 246 | pub crc: u32, 247 | /// Firmware modification date 248 | pub last_modified: String, // TODO: date type? 249 | /// [Home] Whether the new encryption logic is used 250 | pub logic_option_home: bool, 251 | /// [Factory] Whether the new encryption logic is used 252 | pub logic_option_factory: bool, 253 | /// [home] Logic value for decryption 254 | pub logic_value_home: String, 255 | /// [Factory] Logic value for decryption 256 | pub logic_value_factory: String, 257 | /// Whether the binary is a factory binary 258 | pub binary_nature: bool, 259 | } 260 | 261 | impl FirmwareInfo { 262 | /// Compute the encryption key for the firmware. This function automatically 263 | /// handles factory vs home firmware and v2 vs v4 keys. 264 | pub fn encryption_key(&self) -> Result<[u8; 16], FusError> { 265 | let (new_logic, logic_value) = if self.binary_nature { 266 | (self.logic_option_factory, &self.logic_value_factory) 267 | } else { 268 | (self.logic_option_home, &self.logic_value_home) 269 | }; 270 | 271 | let key = if new_logic { 272 | Nonce::from_slice(logic_value.as_bytes())? 273 | .to_logic_check(LogicCheckType::Data(self.version.to_string().as_bytes())) 274 | } else { 275 | format!("{}:{}:{}", self.region, self.model, self.version) 276 | }; 277 | 278 | let digest = md5::compute(key.as_bytes()); 279 | Ok(digest.into()) 280 | } 281 | 282 | /// Split the filename into (target filename, enc extension). If the server- 283 | /// provided filename does not have an enc extension, the extension is set 284 | /// to "enc". 285 | pub fn split_filename(&self) -> (String, String) { 286 | let p = Path::new(&self.filename); 287 | let stem = p.file_stem(); 288 | let ext = p.extension(); 289 | 290 | if let (Some(s), Some(e)) = (stem, ext) { 291 | // Cannot panic 292 | let e_str = e.to_str().unwrap(); 293 | if e_str.starts_with("enc") { 294 | // Cannot panic 295 | let s_str = s.to_str().unwrap(); 296 | return (s_str.to_owned(), e_str.to_owned()); 297 | } 298 | } 299 | 300 | (self.filename.clone(), "enc".to_owned()) 301 | } 302 | } 303 | 304 | /// Builder type for creating FUS clients with non-default behavior. 305 | #[derive(Clone)] 306 | pub struct FusClientBuilder { 307 | keys: FusKeys, 308 | ignore_tls_validation: bool, 309 | } 310 | 311 | impl FusClientBuilder { 312 | pub fn new(keys: FusKeys) -> Self { 313 | Self { 314 | keys, 315 | ignore_tls_validation: false, 316 | } 317 | } 318 | 319 | /// Ignore TLS certificate validation when performing HTTPS requests. By 320 | /// default, TLS certificate validation is enabled. 321 | pub fn ignore_tls_validation(mut self, value: bool) -> Self { 322 | self.ignore_tls_validation = value; 323 | self 324 | } 325 | 326 | /// Build the FUS client with the current options. This function fails if 327 | /// the TLS backend fails to initialize. 328 | pub fn build(&self) -> Result { 329 | FusClient::with_options(self) 330 | } 331 | } 332 | 333 | /// Type for interacting with the FUS service. 334 | pub struct FusClient { 335 | client: reqwest::Client, 336 | keys: FusKeys, 337 | nonce: Option, 338 | } 339 | 340 | impl FusClient { 341 | /// Build a new FUS client object with the options from the specified 342 | /// builder. 343 | fn with_options(options: &FusClientBuilder) -> Result { 344 | debug!("TLS validation enabled: {}", !options.ignore_tls_validation); 345 | 346 | let client = reqwest::ClientBuilder::new() 347 | .danger_accept_invalid_certs(options.ignore_tls_validation) 348 | .cookie_store(true) 349 | .referer(false) 350 | .build()?; 351 | 352 | Ok(Self { 353 | client, 354 | keys: options.keys.clone(), 355 | nonce: None, 356 | }) 357 | } 358 | 359 | /// Get the latest available firmware version for a given model number and 360 | /// CSC region code. 361 | pub async fn get_latest_version(&self, model: &str, region: &str) -> Result { 362 | let url = format!("{FOTA_BASE_URL}/firmware/{region}/{model}/version.xml"); 363 | debug!("FOTA URL: {url}"); 364 | 365 | let r = self.client.get(&url).send().await?; 366 | match r.error_for_status_ref() { 367 | Ok(_) => {} 368 | Err(e) => { 369 | // The FOTA server returns 403 when the page is not found 370 | return if e.status() == Some(reqwest::StatusCode::FORBIDDEN) { 371 | Err(FusError::FirmwareNotFound) 372 | } else { 373 | Err(e.into()) 374 | } 375 | } 376 | } 377 | 378 | let data = r.bytes().await?; 379 | debug!("FOTA response: {:?}", to_utf8_or_error_string(&data)); 380 | 381 | let root = Element::parse(data.as_ref())?; 382 | let version = Self::get_elem_text(&root, &["firmware", "version", "latest"]) 383 | .ok_or(FusError::FirmwareNotFound)?; 384 | 385 | Ok(version.parse()?) 386 | } 387 | 388 | /// Return an error if the FUS response did not return HTTP 200. If a NONCE 389 | /// header exists, regardless of the status code, then it is saved for use 390 | /// with the next request. 391 | fn check_fus_response(&mut self, response: &Response) -> Result<(), FusError> { 392 | self.nonce = response.headers().get("NONCE") 393 | .and_then(|x| Nonce::from_encrypted(&self.keys, x.as_bytes()).ok()); 394 | 395 | response.error_for_status_ref()?; 396 | Ok(()) 397 | } 398 | 399 | /// Generate nonce to use for authentication in further requests. The same 400 | /// nonce will be returned until it is consumed by a FUS request. 401 | async fn ensure_nonce(&mut self) -> Result { 402 | if let Some(nonce) = self.nonce { 403 | return Ok(nonce); 404 | } 405 | 406 | let url = format!("{FUS_BASE_URL}/NF_DownloadGenerateNonce.do"); 407 | debug!("Requesting nonce from: {url}"); 408 | 409 | let r = self.client.post(&url) 410 | .header(AUTHORIZATION, Authorization::new().to_string()) 411 | .header(CONTENT_LENGTH, 0) 412 | .send() 413 | .await?; 414 | self.check_fus_response(&r)?; 415 | self.nonce.ok_or(FusError::NonceNotFound) 416 | } 417 | 418 | /// Perform FUS HTTP request, automatically handling the insertion of the 419 | /// Authorization header and the persisting of the NONCE response header. 420 | async fn execute_fus_request( 421 | &mut self, 422 | request: RequestBuilder, 423 | auth_include_nonce: bool, 424 | ) -> Result { 425 | let nonce = self.ensure_nonce().await?; 426 | 427 | let mut auth = nonce.to_authorization(&self.keys); 428 | if auth_include_nonce { 429 | auth.nonce = nonce.to_encrypted(&self.keys); 430 | } 431 | 432 | let r = request 433 | .header(AUTHORIZATION, auth.to_string()) 434 | .send() 435 | .await?; 436 | self.check_fus_response(&r)?; 437 | 438 | Ok(r) 439 | } 440 | 441 | /// Perform FUS HTTP request, parsing the response body as XML and 442 | /// interpreting the FUS status code. 443 | async fn execute_fus_xml_request( 444 | &mut self, 445 | url: &str, 446 | body: &Element, 447 | auth_include_nonce: bool, 448 | ) -> Result { 449 | debug!("FUS URL: {url}"); 450 | 451 | let mut buf = vec![]; 452 | body.write(&mut buf)?; 453 | 454 | debug!("FUS request: {:?}", to_utf8_or_error_string(&buf)); 455 | 456 | let request = self.client.post(url).body(buf); 457 | let r = self.execute_fus_request(request, auth_include_nonce).await?; 458 | let data = r.bytes().await?; 459 | 460 | debug!("FUS response: {:?}", to_utf8_or_error_string(&data)); 461 | 462 | let root = Element::parse(data.as_ref())?; 463 | 464 | // HTTP 200, but there might still be a FUS error 465 | let status = Self::get_elem_text(&root, &["FUSBody", "Results", "Status"]) 466 | .ok_or_else(|| FusError::FusBadResponse("Missing FUS status field".to_owned()))?; 467 | 468 | if status != "200" { 469 | return Err(FusError::FusBadResponse(status.to_string())); 470 | } 471 | 472 | Ok(root) 473 | } 474 | 475 | /// Get information about a firmware version for a given model and region. 476 | pub async fn get_firmware_info( 477 | &mut self, 478 | model: &str, 479 | region: &str, 480 | version: &FwVersion, 481 | imei_serial: &str, 482 | factory: bool, 483 | ) -> Result { 484 | let nonce = self.ensure_nonce().await?; 485 | let req_root = Self::create_binary_inform_elem( 486 | model, region, version, imei_serial, nonce, factory); 487 | 488 | let url = format!("{FUS_BASE_URL}/NF_DownloadBinaryInform.do"); 489 | let resp_root = self.execute_fus_xml_request(&url, &req_root, false).await?; 490 | 491 | macro_rules! get_value { 492 | ($var:expr, $name:expr) => { 493 | Self::get_fus_field($var, $name) 494 | .ok_or(FusError::FusMissingField($name.to_owned()))? 495 | } 496 | } 497 | macro_rules! get_string { 498 | ($var:expr, $name:expr) => { 499 | get_value!($var, $name).to_string() 500 | } 501 | } 502 | macro_rules! get_parsed { 503 | ($var:expr, $name:expr) => { 504 | { 505 | let value = get_value!($var, $name); 506 | value.parse().map_err(|_| FusError::FusBadField( 507 | $name.to_owned(), value.to_string()))? 508 | } 509 | } 510 | } 511 | 512 | let binary_name = get_string!(&resp_root, "BINARY_NAME"); 513 | let filename = Path::new(&binary_name) 514 | .file_name() 515 | .ok_or_else(|| FusError::FusBadField("BINARY_NAME".to_owned(), binary_name.clone()))? 516 | .to_str() 517 | .unwrap() // Cannot panic 518 | .to_owned(); 519 | 520 | Ok(FirmwareInfo { 521 | version: get_parsed!(&resp_root, "CURRENT_DISPLAY_VERSION"), 522 | version_name: get_string!(&resp_root, "CURRENT_OS_VERSION"), 523 | platform: get_string!(&resp_root, "DEVICE_PLATFORM"), 524 | model: get_string!(&resp_root, "DEVICE_MODEL_NAME"), 525 | model_name: get_string!(&resp_root, "DEVICE_MODEL_DISPLAYNAME"), 526 | model_type: get_parsed!(&resp_root, "DEVICE_MODEL_TYPE"), 527 | region: get_string!(&resp_root, "DEVICE_LOCAL_CODE"), 528 | path: get_string!(&resp_root, "MODEL_PATH"), 529 | filename, 530 | size: get_parsed!(&resp_root, "BINARY_BYTE_SIZE"), 531 | crc: get_parsed!(&resp_root, "BINARY_CRC"), 532 | last_modified: get_string!(&resp_root, "LAST_MODIFIED"), // TODO (20200226162005) 533 | logic_option_home: get_value!(&resp_root, "LOGIC_OPTION_HOME") == "1", 534 | logic_option_factory: get_value!(&resp_root, "LOGIC_OPTION_FACTORY") == "1", 535 | logic_value_home: get_string!(&resp_root, "LOGIC_VALUE_HOME"), 536 | logic_value_factory: get_string!(&resp_root, "LOGIC_VALUE_FACTORY"), 537 | binary_nature: get_value!(&resp_root, "BINARY_NATURE") == "1", 538 | }) 539 | } 540 | 541 | /// Create an async byte stream for downloading the specified firmware with 542 | /// the specified byte range. 543 | pub async fn download( 544 | &mut self, 545 | info: &FirmwareInfo, 546 | range: Range, 547 | ) -> Result>, FusError> { 548 | // It is necessary to inform the service of the intention to download 549 | let nonce = self.ensure_nonce().await?; 550 | let req_root = Self::create_binary_init_elem(info, nonce); 551 | 552 | let url = format!("{FUS_BASE_URL}/NF_DownloadBinaryInitForMass.do"); 553 | self.execute_fus_xml_request(&url, &req_root, false).await?; 554 | 555 | // Download binary. This intentionally does not use RequestBuilder.query() because FUS has 556 | // been updated to return HTTP 405 if the requested filename is URL-encoded. 557 | let url = format!( 558 | "{}/NF_DownloadBinaryForMass.do?file={}{}", 559 | DOWNLOAD_BASE_URL, 560 | info.path, 561 | info.filename, 562 | ); 563 | 564 | debug!("Requesting bytes {}-{} from: {url}", range.start, range.end); 565 | 566 | let r = self.execute_fus_request( 567 | self.client.get(&url) 568 | .header(RANGE, format!("bytes={}-{}", range.start, range.end)), 569 | true, 570 | ).await?; 571 | let status = r.status(); 572 | 573 | if status != StatusCode::PARTIAL_CONTENT { 574 | return Err(FusError::BadHttpResponse(StatusCode::PARTIAL_CONTENT, status)); 575 | } 576 | 577 | Ok(r.bytes_stream()) 578 | } 579 | 580 | fn create_text_node(name: &str, text: &str) -> XMLNode { 581 | let mut elem = Element::new(name); 582 | elem.children.push(XMLNode::Text(text.to_owned())); 583 | XMLNode::Element(elem) 584 | } 585 | 586 | fn create_data_node(name: &str, value: &str) -> XMLNode { 587 | let mut elem = Element::new(name); 588 | elem.children.push(Self::create_text_node("Data", value)); 589 | XMLNode::Element(elem) 590 | } 591 | 592 | fn create_fus_hdr_node() -> XMLNode { 593 | let mut elem = Element::new("FUSHdr"); 594 | elem.children.push(Self::create_text_node("ProtoVer", "1.0")); 595 | elem.children.push(Self::create_text_node("SessionID", "0")); 596 | elem.children.push(Self::create_text_node("MsgID", "1")); 597 | XMLNode::Element(elem) 598 | } 599 | 600 | fn create_binary_inform_elem( 601 | model: &str, 602 | region: &str, 603 | version: &FwVersion, 604 | imei_serial: &str, 605 | nonce: Nonce, 606 | binary_nature: bool, 607 | ) -> Element { 608 | use LogicCheckType::Data; 609 | 610 | let mut fus_body = Element::new("FUSBody"); 611 | 612 | let mut put = Element::new("Put"); 613 | put.children.push(Self::create_text_node("CmdID", "1")); 614 | put.children.push(Self::create_data_node("ACCESS_MODE", "2")); 615 | put.children.push(Self::create_data_node("BINARY_NATURE", 616 | if binary_nature { "1" } else { "0" })); 617 | // Must exist, but can have any value. 618 | put.children.push(Self::create_data_node("CLIENT_PRODUCT", "Smart Switch")); 619 | // Must exist and be non-empty. 620 | put.children.push(Self::create_data_node("CLIENT_VERSION", "4.3.23123_1")); 621 | put.children.push(Self::create_data_node("DEVICE_IMEI_PUSH", imei_serial)); 622 | put.children.push(Self::create_data_node("DEVICE_MODEL_NAME", model)); 623 | put.children.push(Self::create_data_node("DEVICE_LOCAL_CODE", region)); 624 | put.children.push(Self::create_data_node("DEVICE_FW_VERSION", &version.to_string())); 625 | put.children.push(Self::create_data_node("DEVICE_VER_COUNT", "4")); 626 | put.children.push(Self::create_data_node("DEVICE_PDA_CODE1_VERSION", &version.pda)); 627 | put.children.push(Self::create_data_node("DEVICE_CSC_CODE2_VERSION", &version.csc)); 628 | put.children.push(Self::create_data_node("DEVICE_PHONE_FONT_VERSION", &version.phone)); 629 | put.children.push(Self::create_data_node("DEVICE_CONTENTS_DATA_VERSION", &version.data)); 630 | put.children.push(Self::create_data_node("LOGIC_CHECK", 631 | &nonce.to_logic_check(Data(version.to_string().as_bytes())))); 632 | fus_body.children.push(XMLNode::Element(put)); 633 | 634 | let mut get = Element::new("Get"); 635 | get.children.push(Self::create_text_node("CmdID", "2")); 636 | get.children.push(Self::create_text_node("LATEST_FW_VERSION", "")); 637 | fus_body.children.push(XMLNode::Element(get)); 638 | 639 | let mut fus_msg = Element::new("FUSMsg"); 640 | fus_msg.children.push(Self::create_fus_hdr_node()); 641 | fus_msg.children.push(XMLNode::Element(fus_body)); 642 | 643 | fus_msg 644 | } 645 | 646 | fn create_binary_init_elem(info: &FirmwareInfo, nonce: Nonce) -> Element { 647 | use LogicCheckType::Filename; 648 | 649 | let mut fus_body = Element::new("FUSBody"); 650 | 651 | let mut put = Element::new("Put"); 652 | put.children.push(Self::create_text_node("CmdID", "1")); 653 | put.children.push(Self::create_data_node("DEVICE_MODEL_TYPE", 654 | &info.model_type.to_string())); 655 | put.children.push(Self::create_data_node("BINARY_NATURE", 656 | if info.binary_nature { "1" } else { "0" })); 657 | put.children.push(Self::create_data_node("DEVICE_LOCAL_CODE", &info.region)); 658 | put.children.push(Self::create_data_node("BINARY_VERSION", 659 | &info.version.to_string())); 660 | put.children.push(Self::create_data_node("BINARY_FILE_NAME", &info.filename)); 661 | put.children.push(Self::create_data_node("LOGIC_CHECK", 662 | &nonce.to_logic_check(Filename(&info.filename)))); 663 | fus_body.children.push(XMLNode::Element(put)); 664 | 665 | let mut get = Element::new("Get"); 666 | get.children.push(Self::create_text_node("CmdID", "2")); 667 | get.children.push(Self::create_text_node("BINARY_EMERGENCY_OTP_SEND", "")); 668 | fus_body.children.push(XMLNode::Element(get)); 669 | 670 | let mut fus_msg = Element::new("FUSMsg"); 671 | fus_msg.children.push(Self::create_fus_hdr_node()); 672 | fus_msg.children.push(XMLNode::Element(fus_body)); 673 | 674 | fus_msg 675 | } 676 | 677 | fn get_elem_text<'a>(elem: &'a Element, path: &[&str]) -> Option> { 678 | let mut result = Some(elem); 679 | 680 | for p in path { 681 | result = result.and_then(|e| e.get_child(*p)); 682 | } 683 | 684 | result.map(|e| e.get_text().unwrap_or(Cow::Borrowed(""))) 685 | } 686 | 687 | fn get_fus_field<'a>(elem: &'a Element, field: &str) -> Option> { 688 | Self::get_elem_text(elem, &["FUSBody", "Put", field, "Data"]) 689 | } 690 | } 691 | 692 | #[cfg(test)] 693 | mod tests { 694 | use assert_matches::assert_matches; 695 | 696 | use super::*; 697 | 698 | #[test] 699 | fn test_authorization() { 700 | assert_eq!(Authorization::new().to_string(), 701 | r#"FUS nonce="", signature="", nc="", type="", realm="", newauth="1""#); 702 | 703 | assert_eq!(Authorization::with_signature("abc").to_string(), 704 | r#"FUS nonce="", signature="abc", nc="", type="", realm="", newauth="1""#); 705 | } 706 | 707 | #[test] 708 | fn test_nonce() { 709 | let keys = FusKeys::new( 710 | b"testing_testing_testing_testing_", 711 | b"testing_testing_", 712 | ).unwrap(); 713 | 714 | assert_matches!(Nonce::from_slice(b"testing_testing_"), Ok(_)); 715 | assert_matches!(Nonce::from_slice(b"testing_testing"), 716 | Err(FusError::NonceInvalidSize)); 717 | assert_matches!(Nonce::from_slice(b"testing_testing_t"), 718 | Err(FusError::NonceInvalidSize)); 719 | 720 | assert_eq!(Nonce::from_slice(b"testing_testing_").unwrap().to_string(), 721 | "testing_testing_"); 722 | assert_eq!(Nonce::from_slice(b"\xffesting_testing_").unwrap().to_string(), 723 | "[Non-UTF-8 data]"); 724 | 725 | assert_eq!(Nonce::from_slice(b"testing_testing_").unwrap().to_encrypted(&keys), 726 | "yrJiFOygpIxnq4nbWdT2NLk1Odu8m5+zcFKQL4PzV0A="); 727 | 728 | assert_matches!(Nonce::from_encrypted(&keys, b"yrJiFOygpIxnq4nbWdT2NLk1Odu8m5+zcFKQL4PzV0A="), 729 | Ok(x) if x == Nonce::from_slice(b"testing_testing_").unwrap()); 730 | } 731 | 732 | #[test] 733 | fn test_nonce_signature() { 734 | let keys = FusKeys::new( 735 | b"testing_testing_testing_testing_", 736 | b"testing_testing_", 737 | ).unwrap(); 738 | 739 | assert_eq!(Nonce::from_slice(b"testing_testing_").unwrap().to_signature(&keys), 740 | "9J2R5S8AAXs40SYA92cLHQfWDv/6w5cAeZkPOEDIFGw="); 741 | } 742 | 743 | #[test] 744 | fn test_logic_check() { 745 | use LogicCheckType::*; 746 | 747 | let nonce = Nonce::from_slice(b"testing_testing_").unwrap(); 748 | 749 | assert_eq!(nonce.to_logic_check(Data(b"abc")), "bcabacbabcabacba"); 750 | assert_eq!(nonce.to_logic_check(Data(b"testing_testing_")), "intieg__intieg__"); 751 | 752 | assert_eq!(nonce.to_logic_check(Filename("abc")), "bcabacbabcabacba"); 753 | assert_eq!(nonce.to_logic_check(Filename("testing_testing_.enc4")), "intieg__intieg__"); 754 | assert_eq!(nonce.to_logic_check(Filename("testing_testing_testing_.enc4")), "intieg__intieg__"); 755 | } 756 | } 757 | -------------------------------------------------------------------------------- /samfuslib/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod crypto; 2 | pub mod fus; 3 | pub mod range; 4 | pub mod version; 5 | -------------------------------------------------------------------------------- /samfuslib/src/range.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | cmp, 3 | ops::Range, 4 | }; 5 | 6 | pub fn split_range( 7 | range: Range, 8 | n: u64, 9 | min_chunk_size: Option 10 | ) -> Vec> { 11 | debug_assert!(n > 0 && min_chunk_size != Some(0)); 12 | 13 | let size = range.end - range.start; 14 | let chunk_size = cmp::max(min_chunk_size.unwrap_or(1), size / n); 15 | let n = cmp::min(n, size / chunk_size); 16 | let remainder = size - n * chunk_size; 17 | 18 | (0..n).map(|i| { 19 | let extra = if i == n - 1 { remainder } else { 0 }; 20 | Range { 21 | start: range.start + i * chunk_size, 22 | end: range.start + (i + 1) * chunk_size + extra, 23 | } 24 | }).collect() 25 | } 26 | 27 | #[cfg(test)] 28 | mod tests { 29 | use super::*; 30 | 31 | #[test] 32 | fn test_split_range() { 33 | // Empty range should not be split into anything 34 | assert_eq!(split_range(0..0, 1, None), &[]); 35 | assert_eq!(split_range(1..1, 2, None), &[]); 36 | 37 | // Even splits (or close enough given integer division) 38 | assert_eq!(split_range(0..5, 1, None), &[0..5]); 39 | assert_eq!(split_range(0..5, 2, None), &[0..2, 2..5]); 40 | assert_eq!(split_range(0..5, 3, None), &[0..1, 1..2, 2..5]); 41 | assert_eq!(split_range(0..5, 4, None), &[0..1, 1..2, 2..3, 3..5]); 42 | assert_eq!(split_range(0..5, 5, None), &[0..1, 1..2, 2..3, 3..4, 4..5]); 43 | assert_eq!(split_range(0..5, 6, None), &[0..1, 1..2, 2..3, 3..4, 4..5]); 44 | 45 | // Minimum chunk size 46 | assert_eq!(split_range(0..10, 1, Some(3)), &[0..10]); 47 | assert_eq!(split_range(0..10, 2, Some(3)), &[0..5, 5..10]); 48 | assert_eq!(split_range(0..10, 3, Some(3)), &[0..3, 3..6, 6..10]); 49 | assert_eq!(split_range(0..10, 4, Some(3)), &[0..3, 3..6, 6..10]); 50 | assert_eq!(split_range(0..10, 5, Some(3)), &[0..3, 3..6, 6..10]); 51 | assert_eq!(split_range(0..10, 6, Some(3)), &[0..3, 3..6, 6..10]); 52 | assert_eq!(split_range(0..10, 7, Some(3)), &[0..3, 3..6, 6..10]); 53 | assert_eq!(split_range(0..10, 8, Some(3)), &[0..3, 3..6, 6..10]); 54 | assert_eq!(split_range(0..10, 9, Some(3)), &[0..3, 3..6, 6..10]); 55 | assert_eq!(split_range(0..10, 10, Some(3)), &[0..3, 3..6, 6..10]); 56 | assert_eq!(split_range(0..10, 11, Some(3)), &[0..3, 3..6, 6..10]); 57 | 58 | // Non-zero starting point 59 | assert_eq!(split_range(1000..2000, 2, None), &[1000..1500, 1500..2000]); 60 | } 61 | } -------------------------------------------------------------------------------- /samfuslib/src/version.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fmt, 3 | str::FromStr, 4 | }; 5 | 6 | use thiserror::Error; 7 | 8 | /// A type representing the `///` version string used by 9 | /// the FUS protocol (eg. in the `DEVICE_FW_VERSION` field) 10 | #[derive(Clone, Debug, Eq, PartialEq)] 11 | pub struct FwVersion { 12 | /// Primary firmware version (`DEVICE_PDA_CODE1_VERSION`) 13 | pub pda: String, 14 | /// Carrier services version (`DEVICE_CSC_CODE2_VERSION`) 15 | pub csc: String, 16 | /// [Unknown] `phone` version (`DEVICE_PHONE_FONT_VERSION`) 17 | pub phone: String, 18 | /// [Unknown] `data` version (`DEVICE_CONTENTS_DATA_VERSION`) 19 | pub data: String, 20 | } 21 | 22 | impl FwVersion { 23 | pub fn new(pda: &str, csc: &str, phone: Option<&str>, data: Option<&str>) 24 | -> Self { 25 | Self { 26 | pda: pda.to_owned(), 27 | csc: csc.to_owned(), 28 | phone: phone.map_or_else(|| pda.to_owned(), |s| s.to_owned()), 29 | data: data.map_or_else(|| pda.to_owned(), |s| s.to_owned()), 30 | } 31 | } 32 | } 33 | 34 | impl fmt::Display for FwVersion { 35 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 36 | write!(f, "{}/{}/{}/{}", self.pda, self.csc, self.phone, self.data) 37 | } 38 | } 39 | 40 | impl FromStr for FwVersion { 41 | type Err = ParseFwVersionError; 42 | 43 | fn from_str(s: &str) -> Result { 44 | let pieces: Vec<&str> = s.split('/').collect(); 45 | 46 | if pieces.len() < 2 { 47 | return Err(ParseFwVersionError::TooFewFields); 48 | } else if pieces.len() > 4 { 49 | return Err(ParseFwVersionError::TooManyFields); 50 | } 51 | 52 | fn none_if_empty(s: &str) -> Option<&str> { 53 | if s.is_empty() { 54 | None 55 | } else { 56 | Some(s) 57 | } 58 | } 59 | 60 | Ok(Self::new( 61 | pieces[0], 62 | pieces[1], 63 | pieces.get(2).and_then(|s| none_if_empty(s)), 64 | pieces.get(3).and_then(|s| none_if_empty(s)), 65 | )) 66 | } 67 | } 68 | 69 | #[derive(Debug, Error)] 70 | pub enum ParseFwVersionError { 71 | #[error("Too few fields (<2) in version string")] 72 | TooFewFields, 73 | #[error("Too many fields (>4) in version string")] 74 | TooManyFields, 75 | } 76 | 77 | #[cfg(test)] 78 | mod tests { 79 | use assert_matches::assert_matches; 80 | 81 | use super::*; 82 | 83 | #[test] 84 | fn test_display() { 85 | let version = FwVersion::new("a", "b", None, None); 86 | assert_eq!(version.to_string(), "a/b/a/a"); 87 | 88 | let version = FwVersion::new("a", "b", Some("c"), None); 89 | assert_eq!(version.to_string(), "a/b/c/a"); 90 | 91 | let version = FwVersion::new("a", "b", None, Some("d")); 92 | assert_eq!(version.to_string(), "a/b/a/d"); 93 | 94 | let version = FwVersion::new("a", "b", Some("c"), Some("d")); 95 | assert_eq!(version.to_string(), "a/b/c/d"); 96 | } 97 | 98 | #[test] 99 | fn test_parse() { 100 | let result: Result = "a/b".parse(); 101 | assert_matches!(result, Ok(x) if x == FwVersion::new("a", "b", None, None)); 102 | 103 | let result: Result = "a/b/c".parse(); 104 | assert_matches!(result, Ok(x) if x == FwVersion::new("a", "b", Some("c"), None)); 105 | 106 | let result: Result = "a/b/c/d".parse(); 107 | assert_matches!(result, Ok(x) if x == FwVersion::new("a", "b", Some("c"), Some("d"))); 108 | 109 | let result: Result = "a".parse(); 110 | assert_matches!(result, Err(ParseFwVersionError::TooFewFields)); 111 | 112 | let result: Result = "a/b/c/d/e".parse(); 113 | assert_matches!(result, Err(ParseFwVersionError::TooManyFields)); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/file.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fs::File, 3 | io, 4 | path::Path, 5 | }; 6 | 7 | use log::trace; 8 | 9 | /// Read data from offset. The file position *will* be changed. 10 | #[cfg(windows)] 11 | pub fn read_at(file: &mut File, buf: &mut [u8], offset: u64) -> io::Result { 12 | use std::os::windows::fs::FileExt; 13 | file.seek_read(buf, offset) 14 | } 15 | 16 | /// Read data from offset. The file position will *not* be changed. 17 | #[cfg(unix)] 18 | pub fn read_at(file: &mut File, buf: &mut [u8], offset: u64) -> io::Result { 19 | use std::os::unix::fs::FileExt; 20 | file.read_at(buf, offset) 21 | } 22 | 23 | /// Read a byte slice of the given size at the specified offset. The file 24 | /// position may be changed depending on the OS. The EOF is reached before the 25 | /// reads are complete, [`std::io::ErrorKind::UnexpectedEof`] is returned. 26 | pub fn read_all_at(file: &mut File, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> { 27 | trace!("Reading {} bytes at offset {offset}", buf.len()); 28 | 29 | while !buf.is_empty() { 30 | let n = read_at(file, buf, offset)?; 31 | if n == 0 { 32 | return Err(io::ErrorKind::UnexpectedEof.into()); 33 | } 34 | 35 | buf = &mut buf[n..]; 36 | offset += n as u64; 37 | } 38 | 39 | Ok(()) 40 | } 41 | 42 | /// Write data to offset. The file position *will* be changed. 43 | #[cfg(windows)] 44 | pub fn write_at(file: &mut File, buf: &[u8], offset: u64) -> io::Result { 45 | use std::os::windows::fs::FileExt; 46 | file.seek_write(buf, offset) 47 | } 48 | 49 | /// Write data to offset. The file position will *not* be changed. 50 | #[cfg(unix)] 51 | pub fn write_at(file: &mut File, buf: &[u8], offset: u64) -> io::Result { 52 | use std::os::unix::fs::FileExt; 53 | file.write_at(buf, offset) 54 | } 55 | 56 | /// Write all of the specified data to the specified offset. The file position 57 | /// may be changed depending on the OS. The EOF is reached before the writes are 58 | /// complete, [`std::io::ErrorKind::UnexpectedEof`] is returned. 59 | pub fn write_all_at(file: &mut File, mut buf: &[u8], mut offset: u64) -> io::Result<()> { 60 | trace!("Writing {} bytes at offset {offset}", buf.len()); 61 | 62 | while !buf.is_empty() { 63 | let n = write_at(file, buf, offset)?; 64 | if n == 0 { 65 | return Err(io::ErrorKind::UnexpectedEof.into()); 66 | } 67 | 68 | buf = &buf[n..]; 69 | offset += n as u64; 70 | } 71 | 72 | Ok(()) 73 | } 74 | 75 | /// Rename a file with POSIX semantics (atomic and overwrites destination if it 76 | /// exists). This uses `FILE_RENAME_FLAG_POSIX_SEMANTICS` and requires Windows 77 | /// 10 1607 or newer. 78 | #[cfg(windows)] 79 | pub fn rename_atomic(src: &Path, dest: &Path) -> io::Result<()> { 80 | use std::{ 81 | fs::OpenOptions, 82 | iter, 83 | mem, 84 | os::windows::{ 85 | ffi::OsStrExt, 86 | fs::OpenOptionsExt, 87 | io::AsRawHandle, 88 | }, 89 | ptr, 90 | }; 91 | use memoffset::offset_of; 92 | use winapi::{ 93 | shared::minwindef::{BOOL, DWORD}, 94 | um::{ 95 | fileapi::{FILE_RENAME_INFO, SetFileInformationByHandle}, 96 | minwinbase::FileRenameInfoEx, 97 | winnt::DELETE, 98 | }, 99 | }; 100 | 101 | // The winapi crate doesn't have these constants 102 | const FILE_RENAME_FLAG_REPLACE_IF_EXISTS: DWORD = 0x00000001; 103 | const FILE_RENAME_FLAG_POSIX_SEMANTICS: DWORD = 0x00000002; 104 | 105 | let file = OpenOptions::new() 106 | .access_mode(DELETE) 107 | .open(src)?; 108 | 109 | let struct_size_wchars = mem::size_of::() / 2; 110 | let base_size_wchars = offset_of!(FILE_RENAME_INFO, FileName) / 2; 111 | let mut buf: Vec = iter::repeat(0u16) 112 | .take(base_size_wchars) 113 | .chain(dest.as_os_str().encode_wide()) 114 | .chain(iter::once(0)) 115 | .collect(); 116 | 117 | // Make sure the filename contains no embedded \u0000 118 | if buf[base_size_wchars..buf.len() - 1].contains(&0) { 119 | return Err(io::Error::new(io::ErrorKind::InvalidInput, 120 | "Destination filename contains \\u{0000}")); 121 | } 122 | 123 | // No NULL-terminator 124 | let filename_wchars = buf.len() - base_size_wchars - 1; 125 | 126 | // If the filename is short, buf might be smaller than 127 | // sizeof(FILE_RENAME_INFO) 128 | if buf.len() < struct_size_wchars { 129 | buf.resize(struct_size_wchars, 0); 130 | } 131 | 132 | unsafe { 133 | let info = buf.as_mut_ptr().cast::(); 134 | // Actually is a union with 'flags' field. 'flags' is used with 135 | // FileRenameInfoEx 136 | (*info).ReplaceIfExists = (FILE_RENAME_FLAG_REPLACE_IF_EXISTS 137 | | FILE_RENAME_FLAG_POSIX_SEMANTICS) as BOOL; 138 | (*info).RootDirectory = ptr::null_mut(); 139 | // This appears to be unused. SetFileInformationByHandle reads the 140 | // FileName field until it hits a NULL-terminator. 141 | (*info).FileNameLength = filename_wchars as DWORD; 142 | 143 | let ret = SetFileInformationByHandle( 144 | file.as_raw_handle(), 145 | FileRenameInfoEx, 146 | buf.as_mut_ptr().cast(), 147 | buf.len() as DWORD * 2, // byte size 148 | ); 149 | 150 | if ret == 0 { 151 | Err(io::Error::last_os_error()) 152 | } else { 153 | Ok(()) 154 | } 155 | } 156 | } 157 | 158 | /// Rename a file with POSIX semantics (atomic and overwrites destination if it 159 | /// exists). This just calls [`std::fs::rename`] on Unix-like platforms. 160 | #[cfg(unix)] 161 | pub fn rename_atomic(src: &Path, dest: &Path) -> io::Result<()> { 162 | std::fs::rename(src, dest) 163 | } 164 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod file; 2 | mod state; 3 | 4 | use std::{ 5 | cmp, 6 | env, 7 | fmt, 8 | fs::{self, File, OpenOptions}, 9 | io::{self, stderr, Read, Seek, SeekFrom, Stderr, Write}, 10 | ops::Range, 11 | path::{Path, PathBuf}, 12 | str::FromStr, 13 | sync::Arc, 14 | time::{Duration, Instant}, 15 | }; 16 | 17 | use anyhow::{anyhow, Context, Result}; 18 | use clap::{Parser, ValueEnum}; 19 | use crc32fast::Hasher; 20 | use log::{debug, Level, log_enabled, trace}; 21 | use serde::{Deserialize, Serialize}; 22 | use tokio::{ 23 | signal::ctrl_c, 24 | sync::{mpsc, oneshot}, 25 | task::{self, JoinSet}, 26 | }; 27 | use tokio_stream::StreamExt; 28 | 29 | use progresslib::{ProgressBar, ProgressDrawMode}; 30 | use samfuslib::{ 31 | crypto::{FusFileAes128, FusKeys}, 32 | fus::{FirmwareInfo, FusClientBuilder}, 33 | range::split_range, 34 | version::FwVersion, 35 | }; 36 | 37 | use file::{rename_atomic, write_all_at}; 38 | use state::{MAX_RANGES, StateFile}; 39 | 40 | const PKG_NAME: &str = env!("CARGO_PKG_NAME"); 41 | const DOWNLOAD_EXT: &str = concat!(env!("CARGO_PKG_NAME"), "_download"); 42 | const TEMP_EXT: &str = concat!(env!("CARGO_PKG_NAME"), "_temp"); 43 | 44 | /// Minimum download chunk size per thread 45 | const MIN_CHUNK_SIZE: u64 = 1024 * 1024; 46 | 47 | /// Interval for writing state block 48 | const STATE_WRITE_INTERVAL: Duration = Duration::from_secs(5); 49 | 50 | #[derive(Clone, Copy, Debug)] 51 | struct TaskId(usize); 52 | 53 | impl fmt::Display for TaskId { 54 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 55 | write!(f, "Task#{}", self.0) 56 | } 57 | } 58 | 59 | #[derive(Debug)] 60 | struct ProgressMessage { 61 | task_id: TaskId, 62 | bytes: u64, 63 | // Controller replies with new ending offset 64 | resp: oneshot::Sender, 65 | } 66 | 67 | /// Download a byte range of a firmware file. The number of bytes downloaded per 68 | /// loop iteration will be sent to the specified channel via a `ProgressMessage`. 69 | /// The receiver of the message must reply with the new ending offset for this 70 | /// download via the oneshot channel in the `resp` field. An appropriate error 71 | /// will be returned if the full range (subject to modification) cannot be fully 72 | /// downloaded (eg. premature EOF is an error). 73 | async fn download_range( 74 | task_id: TaskId, 75 | client_builder: FusClientBuilder, 76 | mut file: File, 77 | info: Arc, 78 | initial_range: Range, 79 | channel: mpsc::Sender, 80 | ) -> Result<()> { 81 | debug!("[{task_id}] Starting download with initial range: {initial_range:?}"); 82 | 83 | let mut client = client_builder.build() 84 | .context("Could not initialize FUS client")?; 85 | let mut stream = client.download(&info, initial_range.clone()).await 86 | .context("Could not start download")?; 87 | let mut range = initial_range.clone(); 88 | 89 | while range.start < range.end { 90 | let data = if let Some(x) = stream.next().await { 91 | x? 92 | } else { 93 | debug!("[{task_id}] Received unexpected EOF from server"); 94 | return Err(anyhow!("Unexpected EOF from server")); 95 | }; 96 | trace!("[{task_id}] Received {} bytes", data.len()); 97 | 98 | // This may overlap with another task's write when a range split occurs, 99 | // but the same data will be written anyway, so it's not a huge deal. 100 | task::block_in_place(|| { 101 | // tokio::fs doesn't implement FileExt, so use the std::fs blocking 102 | // calls instead 103 | write_all_at(&mut file, &data, range.start) 104 | }).with_context(|| format!( 105 | "Failed to write {} bytes to output file at offset {}", 106 | data.len(), range.start, 107 | ))?; 108 | 109 | let consumed = cmp::min(range.end - range.start, data.len() as u64); 110 | range.start += consumed; 111 | 112 | // Report progress to controller. 113 | let (tx, rx) = oneshot::channel(); 114 | let msg = ProgressMessage { 115 | task_id, 116 | bytes: consumed, 117 | resp: tx, 118 | }; 119 | channel.send(msg).await?; 120 | 121 | // Get new ending offset from controller. 122 | let new_end = rx.await?; 123 | if new_end != range.end { 124 | debug!("[{task_id}] Ending offset changed to {new_end:?}"); 125 | debug_assert!(new_end <= range.end); 126 | range.end = new_end; 127 | } 128 | } 129 | 130 | Ok(()) 131 | } 132 | 133 | /// Create download task for a byte range. This just calls `download_range`() 134 | /// and returns a tuple containing the task ID and the result. 135 | async fn download_task( 136 | task_id: TaskId, 137 | client_builder: FusClientBuilder, 138 | file: File, 139 | info: Arc, 140 | initial_range: Range, 141 | channel: mpsc::Sender, 142 | ) -> (TaskId, Result<()>) { 143 | (task_id, download_range(task_id, client_builder, file, info, initial_range, channel).await) 144 | } 145 | 146 | /// Download a set of file chunks in parallel. Expected or recoverable errors 147 | /// are printed to stderr. Unrecoverable errors are returned as an Err. Download 148 | /// progress is reported via the specified progress bar. Unless an unrecoverable 149 | /// error occurs, the return value indicates whether the download completed 150 | /// successfully. If `false` is returned, the user interrupted the download or 151 | /// the number of recoverable errors exceeded the maximum attempts. 152 | async fn download_chunks( 153 | client_builder: FusClientBuilder, 154 | mut file: File, 155 | mut state_file: StateFile, 156 | info: Arc, 157 | chunks: &[Range], 158 | max_errors: u8, 159 | ) -> Result { 160 | let mut bar = create_progress_bar(info.size); 161 | let remaining: u64 = chunks.iter() 162 | .map(|r| r.end - r.start) 163 | .sum(); 164 | bar.set_position(info.size - remaining)?; 165 | 166 | let mut task_ranges = chunks.to_vec(); 167 | let mut tasks = JoinSet::new(); 168 | let mut last_state_write = Instant::now(); 169 | let mut error_count = 0u8; 170 | let (tx, mut rx) = mpsc::channel(task_ranges.len()); 171 | 172 | // Write initial state 173 | state_file.write_state(&task_ranges) 174 | .context("Could not write download state")?; 175 | 176 | // Start downloading evenly split chunks. 177 | for (i, task_range) in task_ranges.iter().enumerate() { 178 | tasks.spawn(download_task( 179 | TaskId(i), 180 | client_builder.clone(), 181 | file.try_clone().context("Could not duplicate file handle")?, 182 | info.clone(), 183 | task_range.clone(), 184 | tx.clone(), 185 | )); 186 | } 187 | 188 | loop { 189 | tokio::select! { 190 | // User hit ctrl c 191 | c = ctrl_c() => { 192 | c?; 193 | 194 | // The parent will take the remaining chunks and write it to a 195 | // state file. 196 | break; 197 | } 198 | 199 | // Received progress notification. 200 | p = rx.recv() => { 201 | // This channel never ends because tx is never dropped in this 202 | // function. 203 | let p = p.unwrap(); 204 | 205 | bar.advance(p.bytes)?; 206 | 207 | let task_range = &mut task_ranges[p.task_id.0]; 208 | task_range.start += p.bytes; 209 | 210 | p.resp.send(task_range.end).unwrap(); 211 | 212 | // Write the current state. 213 | if last_state_write.elapsed() > STATE_WRITE_INTERVAL { 214 | task::block_in_place(|| -> Result<()> { 215 | file.flush().context("Could not flush writes")?; 216 | 217 | state_file.write_state(&task_ranges) 218 | .context("Could not write download state")?; 219 | 220 | Ok(()) 221 | })?; 222 | 223 | last_state_write = Instant::now(); 224 | } 225 | } 226 | 227 | // Received completion message. 228 | r = tasks.join_next() => { 229 | match r { 230 | // All tasks exited 231 | None => { 232 | debug!("All download tasks have exited"); 233 | break; 234 | }, 235 | 236 | // Download task panicked 237 | Some(Err(e)) => { 238 | return Err(e).context("Unexpected panic in download task"); 239 | } 240 | 241 | // Task completed successfully 242 | Some(Ok((task_id, Ok(_)))) => { 243 | debug!("[{task_id}] Completed download"); 244 | 245 | if error_count >= max_errors { 246 | debug!("Exceeded max error count: {max_errors}"); 247 | continue; 248 | } 249 | 250 | // Otherwise, the task completed successfully. Find the 251 | // largest in-progress chunk, split it into two, and 252 | // start downloading the second half. This reduces the 253 | // effect of one slow stream slowing down the entire 254 | // download. 255 | let largest_range = task_ranges.iter_mut() 256 | .max_by_key(|s| s.end - s.start) 257 | .unwrap(); 258 | if largest_range.start == largest_range.end { 259 | debug!("Largest range is empty; download is complete"); 260 | continue; 261 | } 262 | 263 | debug!("Candidate for range splitting: {largest_range:?}"); 264 | 265 | let ranges = split_range(largest_range.clone(), 2, Some(MIN_CHUNK_SIZE)); 266 | if ranges.len() < 2 { 267 | debug!("Range is too small to be worth splitting"); 268 | continue; 269 | } 270 | 271 | largest_range.end = ranges[0].end; 272 | let new_range = ranges[1].clone(); 273 | 274 | debug!("[{task_id}] Downloading newly split range {new_range:?}"); 275 | task_ranges[task_id.0] = new_range.clone(); 276 | 277 | tasks.spawn(download_task( 278 | task_id, 279 | client_builder.clone(), 280 | file.try_clone().context("Could not duplicate file handle")?, 281 | info.clone(), 282 | new_range, 283 | tx.clone(), 284 | )); 285 | } 286 | 287 | // Task failed 288 | Some(Ok((task_id, Err(e)))) => { 289 | bar.println(format!("{:?}", e.context("Error encountered during download")))?; 290 | error_count += 1; 291 | 292 | if error_count >= max_errors { 293 | debug!("Exceeded max error count: {max_errors}"); 294 | continue; 295 | } 296 | 297 | bar.println(format!("Retrying (attempt {error_count}/{max_errors}) ..."))?; 298 | debug!("[{task_id}] Retrying incomplete range {:?}", task_ranges[task_id.0]); 299 | 300 | tasks.spawn(download_task( 301 | task_id, 302 | client_builder.clone(), 303 | file.try_clone().context("Could not duplicate file handle")?, 304 | info.clone(), 305 | task_ranges[task_id.0].clone(), 306 | tx.clone(), 307 | )); 308 | } 309 | } 310 | } 311 | } 312 | } 313 | 314 | // Write final state 315 | let incomplete: Vec<_> = task_ranges.into_iter() 316 | .filter(|r| r.end - r.start > 0) 317 | .collect(); 318 | state_file.write_state(&incomplete) 319 | .context("Could not write download state")?; 320 | 321 | Ok(incomplete.is_empty()) 322 | } 323 | 324 | /// Query FUS for information about the specified firmware. If no version is 325 | /// provided, the latest available version will be used. 326 | async fn get_firmware_info( 327 | client_builder: FusClientBuilder, 328 | model: &str, 329 | region: &str, 330 | version: Option, 331 | imei_serial: &str, 332 | factory: bool, 333 | ) -> Result { 334 | let mut client = client_builder.build() 335 | .context("Could not initialize FUS client")?; 336 | let fw_version = match version { 337 | Some(v) => v, 338 | None => client.get_latest_version(model, region).await?, 339 | }; 340 | let info = client.get_firmware_info( 341 | model, region, &fw_version, imei_serial, factory).await?; 342 | 343 | Ok(info) 344 | } 345 | 346 | /// Decrypt file and compute the CRC32 checksum of the input file along the way. 347 | fn crc32_and_decrypt( 348 | mut input_file: File, 349 | mut output_file: File, 350 | key: &[u8], 351 | ) -> Result { 352 | let mut size = input_file.seek(SeekFrom::End(0)) 353 | .context("Failed to get input file size")?; 354 | input_file.rewind() 355 | .context("Failed to seek input file")?; 356 | output_file.rewind() 357 | .context("Failed to seek output file")?; 358 | 359 | let mut bar = create_progress_bar(size); 360 | let mut buf = [0u8; 1024 * 1024]; 361 | let mut hasher = Hasher::new(); 362 | let cipher = FusFileAes128::new(key); 363 | 364 | // Intentionally don't handle files that grow during reads 365 | while size > 0 { 366 | let to_read = cmp::min(size, buf.len() as u64); 367 | let read_buf = &mut buf[..to_read as usize]; 368 | input_file.read_exact(read_buf) 369 | .context("Failed to read input file")?; 370 | 371 | hasher.update(read_buf); 372 | 373 | cipher.clone().decrypt_in_place(read_buf) 374 | .context("Failed to decrypt file")?; 375 | 376 | output_file.write_all(read_buf) 377 | .context("Failed to write output file")?; 378 | 379 | size -= to_read; 380 | bar.advance(to_read)?; 381 | } 382 | 383 | Ok(hasher.finalize()) 384 | } 385 | 386 | /// Validate that the file's checksum matches the expected value from the 387 | /// firmware info and decrypt the firmware. 388 | async fn decrypt_firmware( 389 | input_file: File, 390 | output_file: File, 391 | info: Arc, 392 | ) -> Result<()> { 393 | let key = info.encryption_key() 394 | .context("Failed to compute encryption key")?; 395 | 396 | debug!("Firmware encryption key: {key:?}"); 397 | 398 | let crc32 = task::spawn_blocking(move || crc32_and_decrypt( 399 | input_file, 400 | output_file, 401 | &key, 402 | )).await??; 403 | 404 | if crc32 != info.crc { 405 | return Err(anyhow!( 406 | "Firmware's checksum ({:08X}) does not match expected checksum ({:08X})", 407 | crc32, 408 | info.crc, 409 | )); 410 | } 411 | 412 | Ok(()) 413 | } 414 | 415 | /// Create a new progress bar with the specified length. The progress bar is not 416 | /// immediately rendered. 417 | fn create_progress_bar(len: u64) -> ProgressBar { 418 | let mut bar = ProgressBar::new(stderr(), len); 419 | if log_enabled!(Level::Debug) { 420 | // The escape sequences for the interactive progress bar would clobber 421 | // log messages. 422 | bar.set_mode(Some(ProgressDrawMode::Append)); 423 | } 424 | 425 | bar 426 | } 427 | 428 | /// Open an existing file or create a new file at another path. Useful when an 429 | /// existing file should be opened and eg. a new temp file should be created if 430 | /// if doesn't exist. Returns the file handle and whether `open_path` existed. 431 | fn open_or_create( 432 | options: &OpenOptions, 433 | open_path: &Path, 434 | create_path: &Path, 435 | ) -> Result<(File, bool)> { 436 | match options.open(open_path) { 437 | Ok(f) => Ok((f, true)), 438 | Err(e) => { 439 | let (r, p) = if e.kind() == io::ErrorKind::NotFound { 440 | (options.clone().create(true).open(create_path), create_path) 441 | } else { 442 | (Err(e), open_path) 443 | }; 444 | 445 | Ok((r.context(format!("Could not open file: {p:?}"))?, false)) 446 | } 447 | } 448 | } 449 | 450 | /// Delete a file, but don't error out if the path doesn't exist. 451 | fn delete_if_exists(path: &Path) -> Result<()> { 452 | if let Err(e) = fs::remove_file(path) { 453 | if e.kind() != io::ErrorKind::NotFound { 454 | return Err(e).context(format!("Failed to delete file: {path:?}")); 455 | } 456 | } 457 | 458 | Ok(()) 459 | } 460 | 461 | /// Add an extension to a file path. 462 | fn add_extension(path: &Path, ext: &str) -> PathBuf { 463 | let mut s = path.as_os_str().to_owned(); 464 | s.push("."); 465 | s.push(ext); 466 | PathBuf::from(s) 467 | } 468 | 469 | /// Load FUS keys from the following list in order: 470 | /// * User-supplied command line arguments 471 | /// * Environment variables 472 | /// * Config file 473 | fn load_keys(opts: &Opts, config: &Option) -> Result { 474 | let fixed_key = opts.fus_fixed_key 475 | .as_ref() 476 | .or_else(|| config.as_ref().and_then(|c| c.fus_fixed_key.as_ref())) 477 | .ok_or_else(|| anyhow!("No FUS fixed key argument or variable specified"))? 478 | .as_bytes(); 479 | let flexible_key_suffix = opts.fus_flexible_key_suffix 480 | .as_ref() 481 | .or_else(|| config.as_ref().and_then(|c| c.fus_flexible_key_suffix.as_ref())) 482 | .ok_or_else(|| anyhow!("No FUS flexible key suffix argument or variable specified"))? 483 | .as_bytes(); 484 | 485 | Ok(FusKeys::new(fixed_key, flexible_key_suffix)?) 486 | } 487 | 488 | #[derive(Clone, Copy, Debug, Eq, Parser, PartialEq, ValueEnum)] 489 | enum FirmwareType { 490 | Home, 491 | Factory, 492 | } 493 | 494 | impl Default for FirmwareType { 495 | fn default() -> Self { 496 | Self::Home 497 | } 498 | } 499 | 500 | impl fmt::Display for FirmwareType { 501 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 502 | match self { 503 | Self::Home => f.write_str("home"), 504 | Self::Factory => f.write_str("factory"), 505 | } 506 | } 507 | } 508 | 509 | #[derive(Clone, Copy, Debug, Parser, ValueEnum)] 510 | enum LogLevel { 511 | Debug, 512 | Trace, 513 | } 514 | 515 | impl fmt::Display for LogLevel { 516 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 517 | match self { 518 | Self::Debug => f.write_str("debug"), 519 | Self::Trace => f.write_str("trace"), 520 | } 521 | } 522 | } 523 | 524 | #[derive(Clone, Copy, Debug)] 525 | struct NumChunks(u64); 526 | 527 | impl FromStr for NumChunks { 528 | type Err = anyhow::Error; 529 | 530 | fn from_str(s: &str) -> Result { 531 | let n: u64 = s.parse()?; 532 | if n == 0 { 533 | return Err(anyhow!("value cannot be 0")); 534 | } else if n > MAX_RANGES as u64 { 535 | // Same limit as aria2 to avoid unintentional DoS 536 | return Err(anyhow!("too many chunks (>{MAX_RANGES})")); 537 | } 538 | 539 | Ok(Self(n)) 540 | } 541 | } 542 | 543 | #[derive(Debug, Deserialize, Serialize)] 544 | struct Config { 545 | fus_fixed_key: Option, 546 | fus_flexible_key_suffix: Option, 547 | } 548 | 549 | fn default_config_path() -> Option { 550 | dirs::config_dir().map(|mut p| { 551 | p.push(format!("{PKG_NAME}.conf")); 552 | p 553 | }) 554 | } 555 | 556 | fn load_config_file(user_path: Option<&Path>) -> Result> { 557 | let default_path = default_config_path(); 558 | let path = user_path.or(default_path.as_deref()); 559 | 560 | match path { 561 | Some(p) => { 562 | let file = match File::open(p) { 563 | Ok(f) => f, 564 | Err(e) => { 565 | return if e.kind() == io::ErrorKind::NotFound { 566 | Ok(None) 567 | } else { 568 | Err(e).context(format!("Could not open file: {p:?}")) 569 | }; 570 | } 571 | }; 572 | 573 | let config = serde_json::from_reader(file) 574 | .context(format!("Could not parse config file: {p:?}"))?; 575 | 576 | Ok(Some(config)) 577 | } 578 | None => Ok(None), 579 | } 580 | } 581 | 582 | /// A simple tool for quickly downloading official firmware files from FUS. 583 | #[derive(Debug, Parser)] 584 | #[clap(author, version)] 585 | struct Opts { 586 | /// Device's model number (eg. SM-N986U) 587 | #[clap(short, long)] 588 | model: String, 589 | /// Region/CSC code (eg. TMB) 590 | #[clap(short, long)] 591 | region: String, 592 | /// Version number (latest if unspecified) 593 | /// 594 | /// This is the version number of the firmware to download. The format is: 595 | /// "/[//]". If or are omitted, then 596 | /// they're set to the same value as . If no version is specified, then 597 | /// the latest available version is queried from the FOTA server. 598 | #[clap(short, long)] 599 | version: Option, 600 | /// IMEI/serial number 601 | /// 602 | /// This is required by FUS, which now only serves firmware that matches the 603 | /// specified IMEI/serial number. A serial number is accepted only if the 604 | /// device has no modem. 605 | #[clap(short, long)] 606 | imei_serial: String, 607 | /// Firmware type to download (home or factory) 608 | /// 609 | /// This option allows the firmware type (also known as "binary nature") to 610 | /// be selected. By default, the "home" firmware is downloaded. 611 | #[clap(short = 't', default_value_t, value_enum)] 612 | firmware_type: FirmwareType, 613 | /// Print out the firmware information only 614 | /// 615 | /// The firmware will not actually be downloaded. 616 | #[clap(long)] 617 | print_only: bool, 618 | /// Output path for decrypted firmware 619 | /// 620 | /// By default, the output path is the filename returned by the server. This 621 | /// does not present a security issue because all path components are 622 | /// ignored. 623 | #[clap(short, long, value_parser)] 624 | output: Option, 625 | /// Allow overwriting the output file if it exists 626 | /// 627 | /// By default, the output file is not overwritten if it already exists. 628 | /// Passing this option causes the check to be skipped. Note that this does 629 | /// not change how the intermediate (encrypted) file handled. If the 630 | /// intermediate file already exists, it will not be redownloaded (as usual). 631 | #[clap(short, long)] 632 | force: bool, 633 | /// Set logging verbosity 634 | /// 635 | /// By default, no log messages are printed out. If set to 'debug', log 636 | /// messages of the implementation details (such as how the parallel 637 | /// download ranges are split) are printed out. If set to 'trace', I/O read 638 | /// and write messages are also printed out, which can be extremely verbose. 639 | /// This option overrides the RUST_LOG environment variable, which would 640 | /// otherwise be respected if this option was not passed. 641 | #[clap(long, value_enum)] 642 | loglevel: Option, 643 | /// Number of chunks to download in parallel 644 | /// 645 | /// If a chunk downloads quickly and completes first, another in-progress 646 | /// chunk will be split in half, with both parts downloaded in parallel. 647 | /// This ensures that there's always chunks downloading in parallel 648 | /// until the chunks are too small to be worth splitting (1MiB). This also 649 | /// prevents one slow connection from slowing down the entire download. The 650 | /// maximum number of chunks allowed is 16. 651 | #[clap(short, long, default_value = "4")] 652 | chunks: NumChunks, 653 | /// Maximum retries during download 654 | /// 655 | /// This only affects errors that occur during the download process. Note 656 | /// that the download does not immediately stop if the maximum number of 657 | /// retries are exceeded. New chunks (for parallel downloads) will not begin 658 | /// downloading, but the remaining in-progress chunks will download to 659 | /// completion (unless they also error out). 660 | #[clap(long, default_value = "3")] 661 | retries: u8, 662 | /// Keep the downloaded intermediate (encrypted) file 663 | /// 664 | /// By default, the encrypted download file is deleted if CRC32 validation 665 | /// and decryption succeed. 666 | #[clap(long)] 667 | keep_encrypted: bool, 668 | /// Ignore TLS validation for HTTPS connections 669 | /// 670 | /// By default, all HTTPS connections (eg. to FUS) will validate the TLS 671 | /// certificate against the system's CA trust store. 672 | #[clap(long)] 673 | ignore_tls_validation: bool, 674 | /// FUS fixed key 675 | /// 676 | /// If unspecified, the key is loaded from the `FUS_FIXED_KEY` environment 677 | /// variable, followed by the `fus_fixed_key` config file variable. 678 | #[clap(long, env = "FUS_FIXED_KEY")] 679 | fus_fixed_key: Option, 680 | /// FUS flexible key suffix 681 | /// 682 | /// If unspecified, the key is loaded from the `FUS_FLEXIBLE_KEY_SUFFIX` 683 | /// environment variable, followed by the `fux_flexible_key_suffix` config 684 | /// file variable. 685 | #[clap(long, env = "FUS_FLEXIBLE_KEY_SUFFIX")] 686 | fus_flexible_key_suffix: Option, 687 | /// Config file path 688 | /// 689 | /// If unspecified, the default config file path is used. The config file 690 | /// can store the FUS keys to avoid needing to set environment variables or 691 | /// pass them as command-line arguments. 692 | #[clap(long, value_parser)] 693 | config: Option, 694 | } 695 | 696 | #[tokio::main] 697 | async fn main() -> Result<()> { 698 | let opts = Opts::parse(); 699 | 700 | if let Some(l) = opts.loglevel { 701 | std::env::set_var("RUST_LOG", format!("{PKG_NAME}={l},samfuslib={l}")); 702 | } 703 | 704 | env_logger::init(); 705 | let log_keys_var = format!("{}_LOG_KEYS", PKG_NAME.to_uppercase()); 706 | let log_keys = matches!(env::var(log_keys_var), Ok(v) if v == "true"); 707 | 708 | debug!("Arguments: {opts:#?}"); 709 | 710 | let config = load_config_file(opts.config.as_deref())?; 711 | if log_keys { 712 | debug!("Config: {config:#?}"); 713 | } 714 | 715 | let keys = load_keys(&opts, &config)?; 716 | if log_keys { 717 | debug!("Keys: {keys:?}"); 718 | } 719 | 720 | let client_builder = FusClientBuilder::new(keys) 721 | .ignore_tls_validation(opts.ignore_tls_validation); 722 | 723 | debug!("Querying FUS for firmware information"); 724 | 725 | let info = Arc::new(get_firmware_info( 726 | client_builder.clone(), 727 | &opts.model, 728 | &opts.region, 729 | opts.version, 730 | &opts.imei_serial, 731 | opts.firmware_type == FirmwareType::Factory, 732 | ).await.context("Failed to query firmware information")?); 733 | 734 | debug!("Full firmware info: {info:#?}"); 735 | 736 | println!("Firmware info:"); 737 | println!("- Model: {} ({})", info.model, info.model_name); 738 | println!("- Region: {}", info.region); 739 | println!("- Version: {}", info.version); 740 | println!("- OS: {} {}", info.platform, info.version_name); 741 | println!("- Type: {}", if info.binary_nature { "Factory" } else { "Home" }); 742 | println!("- File: {}{}", info.path, info.filename); 743 | println!("- Size: {} bytes", info.size); 744 | println!("- CRC32: {:08X}", info.crc); 745 | println!("- Date: {}", info.last_modified); 746 | 747 | if opts.print_only { 748 | return Ok(()); 749 | } 750 | 751 | let (default_filename, ext) = info.split_filename(); 752 | let output_path = opts.output.unwrap_or_else(|| Path::new(&default_filename).to_owned()); 753 | let output_path_temp = add_extension(&output_path, TEMP_EXT); 754 | let download_path = add_extension(&output_path, &ext); 755 | let download_path_temp = add_extension(&download_path, DOWNLOAD_EXT); 756 | 757 | debug!("Output path (final): {output_path:?}"); 758 | debug!("Output path (temp): {output_path_temp:?}"); 759 | debug!("Download path (final): {download_path:?}"); 760 | debug!("Download path (temp): {download_path_temp:?}"); 761 | 762 | if output_path.exists() && !opts.force { 763 | eprintln!("{output_path:?} already exists. Use -f/--force to overwrite."); 764 | return Ok(()); 765 | } 766 | 767 | let (file, completed_download) = open_or_create( 768 | OpenOptions::new().read(true).write(true), 769 | &download_path, 770 | &download_path_temp, 771 | )?; 772 | 773 | if !completed_download { 774 | let mut state_file = StateFile::new( 775 | file.try_clone().context("Could not duplicate file handle")?, 776 | info.size, 777 | ).context("Could not load download state")?; 778 | 779 | // Try to read the existing state or split into evenly sized chunks 780 | let chunks = if state_file.is_valid() { 781 | debug!("Have existing state data"); 782 | debug!("Command-line chunks option ({}) will be ignored", opts.chunks.0); 783 | 784 | match state_file.read_state() { 785 | Ok(c) => c, 786 | Err(e) if e.kind() == io::ErrorKind::InvalidData => { 787 | return Err(anyhow!( 788 | "Download file is corrupted. Delete to download from scratch: {:?}", 789 | download_path_temp, 790 | )); 791 | } 792 | Err(e) => return Err(e).context("Could not load download state"), 793 | } 794 | } else { 795 | debug!("No existing state available"); 796 | 797 | split_range( 798 | 0..info.size, 799 | opts.chunks.0, 800 | Some(MIN_CHUNK_SIZE), 801 | ) 802 | }; 803 | 804 | debug!("Download ranges: {chunks:#?}"); 805 | 806 | let complete = download_chunks( 807 | client_builder.clone(), 808 | file.try_clone().context("Could not duplicate file handle")?, 809 | state_file, 810 | info.clone(), 811 | &chunks, 812 | opts.retries, 813 | ).await?; 814 | 815 | if !complete { 816 | return Err(anyhow!("Download was interrupted. To resume, rerun the current command.")); 817 | } 818 | 819 | rename_atomic(&download_path_temp, &download_path) 820 | .context(format!("Could not move {download_path_temp:?} to {download_path:?}"))?; 821 | } 822 | 823 | debug!("Truncating to {} bytes to strip state block", info.size); 824 | file.set_len(info.size).context("Could not set file size")?; 825 | 826 | let decrypted_file = File::create(&output_path_temp) 827 | .context(format!("Could not open file: {output_path_temp:?}"))?; 828 | 829 | debug!("Decrypting firmware and validating CRC32"); 830 | 831 | decrypt_firmware(file, decrypted_file, info.clone()).await?; 832 | 833 | if !opts.keep_encrypted { 834 | delete_if_exists(&download_path)?; 835 | } 836 | 837 | rename_atomic(&output_path_temp, &output_path) 838 | .context(format!("Could not move {output_path_temp:?} to {output_path:?}"))?; 839 | 840 | Ok(()) 841 | } 842 | -------------------------------------------------------------------------------- /src/state.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | convert::TryInto, 3 | fs::File, 4 | io::{self, Write}, 5 | mem, 6 | ops::Range, 7 | u64, 8 | }; 9 | 10 | use log::debug; 11 | 12 | use crate::file::{read_all_at, write_all_at}; 13 | 14 | // The state file format is a 516-byte block as described below. It stores two 15 | // fixed-size arrays containing the list of remaining ranges to be downloaded. 16 | // Each write of the current state will flip between the two arrays. 17 | // 18 | // State block: 19 | // | Offset | Size | Description | 20 | // |--------|------|-----------------------------| 21 | // | 0 | 1 | Version field (currently 1) | 22 | // | 1 | 1 | Parity | 23 | // | 2 | 257 | Ranges block 1 (parity 0) | 24 | // | 259 | 257 | Ranges block 2 (parity 1) | 25 | // 26 | // Ranges block: 27 | // | Offset | Size | Description | 28 | // |--------|------|------------------------------------------| 29 | // | 0 | 1 | Number of range pair slots used (max 16) | 30 | // | 1 | 8 | Range 1 beginning (big endian) | 31 | // | 9 | 8 | Range 1 end (big endian) | 32 | // | ... | ... | ... | 33 | // | 241 | 8 | Range 16 beginning (big endian) | 34 | // | 249 | 8 | Range 16 end (big endian) | 35 | 36 | /// Maximum number of download ranges that can be stored in the state file. 37 | pub const MAX_RANGES: usize = 16; 38 | 39 | const CURRENT_VERSION: u8 = 1; 40 | 41 | const RANGES_BLOCK_SIZE: u64 = 42 | mem::size_of::() as u64 // Number of elements used 43 | + MAX_RANGES as u64 // Max elements 44 | * 2 // (start, end) pair 45 | * mem::size_of::() as u64; 46 | 47 | const VERSION_OFFSET: u64 = 0; 48 | const VERSION_SIZE: u64 = mem::size_of::() as u64; 49 | 50 | const PARITY_OFFSET: u64 = VERSION_OFFSET + VERSION_SIZE; 51 | const PARITY_SIZE: u64 = mem::size_of::() as u64; 52 | 53 | const STATE1_OFFSET: u64 = PARITY_OFFSET + PARITY_SIZE; 54 | const STATE1_SIZE: u64 = RANGES_BLOCK_SIZE; 55 | 56 | const STATE2_OFFSET: u64 = STATE1_OFFSET + STATE1_SIZE; 57 | const STATE2_SIZE: u64 = RANGES_BLOCK_SIZE; 58 | 59 | const STATE_BLOCK_SIZE: u64 = STATE2_OFFSET + STATE2_SIZE; 60 | 61 | pub struct StateFile { 62 | file: File, 63 | offset: u64, 64 | parity_bit: bool, 65 | invalid: bool, 66 | } 67 | 68 | impl StateFile { 69 | /// Create a new state file handle for the given file and offset. If there 70 | /// is currently no state state block at the offset, an invalid state block 71 | /// will be written. 72 | pub fn new(file: File, offset: u64) -> io::Result { 73 | let mut s = Self { 74 | file, 75 | offset, 76 | parity_bit: true, // Write to ranges block 1 by default 77 | invalid: false, 78 | }; 79 | 80 | s.initialize()?; 81 | 82 | Ok(s) 83 | } 84 | 85 | /// Initialize the state block. If there is no state block, then an invalid 86 | /// one consisting of all 0xff bytes is written. 87 | fn initialize(&mut self) -> io::Result<()> { 88 | let mut buf = [0xffu8; STATE_BLOCK_SIZE as usize]; 89 | 90 | match read_all_at(&mut self.file, &mut buf, self.offset) { 91 | Ok(_) => { 92 | if buf[VERSION_OFFSET as usize] == 0xff { 93 | debug!("Initial state block is invalid"); 94 | self.invalid = true; 95 | } 96 | } 97 | Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => { 98 | debug!("Writing invalid initial state block"); 99 | 100 | write_all_at(&mut self.file, &buf, self.offset)?; 101 | self.file.flush()?; 102 | 103 | self.invalid = true; 104 | } 105 | Err(e) => return Err(e), 106 | } 107 | 108 | Ok(()) 109 | } 110 | 111 | /// Return whether the state block is valid. A state block is valid for 112 | /// a file where [`write_state`] has successfully run once in the past. 113 | pub fn is_valid(&self) -> bool { 114 | !self.invalid 115 | } 116 | 117 | /// Read the ranges block at the specified relative offset. 118 | fn read_ranges_block(&mut self, block_offset: u64) -> io::Result>> { 119 | let mut buf = [0u8; RANGES_BLOCK_SIZE as usize]; 120 | let mut pos = 0; 121 | 122 | read_all_at(&mut self.file, &mut buf, self.offset + block_offset)?; 123 | 124 | let size = buf[pos] as usize; 125 | pos += 1; 126 | 127 | if size > MAX_RANGES { 128 | return Err(io::Error::new(io::ErrorKind::InvalidData, 129 | format!("Too many ranges: {size}"))); 130 | } 131 | 132 | let mut result = Vec::new(); 133 | 134 | for _ in 0..size { 135 | let start = u64::from_be_bytes(buf[pos..pos + 8].try_into().unwrap()); 136 | pos += 8; 137 | let end = u64::from_be_bytes(buf[pos..pos + 8].try_into().unwrap()); 138 | pos += 8; 139 | 140 | result.push(start..end); 141 | } 142 | 143 | debug!("Validating ranges block data: {result:?}"); 144 | 145 | result.sort_by_key(|r| r.start); 146 | result.retain(|r| r.end - r.start > 0); 147 | 148 | let is_increasing = |w: &[Range]| { 149 | w[0].start <= w[0].end 150 | && w[0].end <= w[1].start 151 | && w[1].start <= w[1].end 152 | && w[1].end <= self.offset 153 | }; 154 | 155 | if !result.windows(2).all(is_increasing) { 156 | debug!("Ranges overlap or are not increasing: {result:?}"); 157 | 158 | return Err(io::Error::new(io::ErrorKind::InvalidData, 159 | "Ranges overlap or are not increasing")); 160 | } 161 | 162 | Ok(result) 163 | } 164 | 165 | /// Write the specified ranges to the ranges block at the specified relative 166 | /// offset. 167 | fn write_ranges_block(&mut self, ranges: &[Range], block_offset: u64) -> io::Result<()> { 168 | assert!(ranges.len() <= MAX_RANGES); 169 | 170 | let mut input = ranges.to_owned(); 171 | input.sort_by_key(|r| r.start); 172 | input.retain(|r| r.end - r.start > 0); 173 | 174 | let mut buf = [0u8; RANGES_BLOCK_SIZE as usize]; 175 | let mut pos = 0; 176 | buf[pos] = input.len() as u8; 177 | pos += 1; 178 | 179 | for r in input { 180 | buf[pos..pos + 8].copy_from_slice(&r.start.to_be_bytes()); 181 | pos += 8; 182 | buf[pos..pos + 8].copy_from_slice(&r.end.to_be_bytes()); 183 | pos += 8; 184 | } 185 | 186 | write_all_at(&mut self.file, &buf, self.offset + block_offset) 187 | } 188 | 189 | /// Read the current state from the file. This will read one of the two 190 | /// states based on the last successfully written parity. 191 | pub fn read_state(&mut self) -> io::Result>> { 192 | let mut version = [0u8; 1]; 193 | read_all_at( 194 | &mut self.file, 195 | &mut version, 196 | self.offset + VERSION_OFFSET, 197 | )?; 198 | 199 | if version[0] != CURRENT_VERSION { 200 | return Err(io::Error::new(io::ErrorKind::InvalidData, 201 | format!("Unrecognized state version: {}", version[0]))); 202 | } 203 | 204 | let mut parity = [0u8; 1]; 205 | read_all_at( 206 | &mut self.file, 207 | &mut parity, 208 | self.offset + PARITY_OFFSET, 209 | )?; 210 | 211 | let new_parity = parity[0] != 0; 212 | 213 | let block_offset = if new_parity { STATE2_OFFSET } else { STATE1_OFFSET }; 214 | let ranges = self.read_ranges_block(block_offset)?; 215 | 216 | debug!("Read ranges for parity {}: {ranges:?}", u8::from(new_parity)); 217 | 218 | self.parity_bit = new_parity; 219 | self.invalid = false; 220 | 221 | Ok(ranges) 222 | } 223 | 224 | /// Write the given state to the file. This will write the new state to the 225 | /// opposite parity block of the previous state. The previous state block is 226 | /// never overwritten to reduce the chance of an unclean shutdown corrupting 227 | /// the file. 228 | pub fn write_state(&mut self, ranges: &[Range]) -> io::Result<()> { 229 | let new_parity = !self.parity_bit; 230 | 231 | debug!("Writing ranges for parity {}: {ranges:?}", u8::from(new_parity)); 232 | 233 | write_all_at( 234 | &mut self.file, 235 | &[CURRENT_VERSION], 236 | self.offset + VERSION_OFFSET, 237 | )?; 238 | self.file.flush()?; 239 | 240 | let block_offset = if new_parity { STATE2_OFFSET } else { STATE1_OFFSET }; 241 | self.write_ranges_block(ranges, block_offset)?; 242 | self.file.flush()?; 243 | 244 | write_all_at( 245 | &mut self.file, 246 | &[u8::from(new_parity)], 247 | self.offset + PARITY_OFFSET, 248 | )?; 249 | self.file.flush()?; 250 | 251 | self.parity_bit = new_parity; 252 | self.invalid = false; 253 | 254 | Ok(()) 255 | } 256 | } 257 | --------------------------------------------------------------------------------