diff --git a/.cargo/config.toml b/.cargo/config.toml index 71480e92d..a88db5f38 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -3,3 +3,23 @@ cov = "llvm-cov" cov-lcov = "llvm-cov --lcov --output-path=./.coverage/lcov.info" cov-html = "llvm-cov --html" time = "build --timings --all-targets" + +[build] +rustflags = [ + "-D", + "warnings", + "-D", + "future-incompatible", + "-D", + "let-underscore", + "-D", + "nonstandard-style", + "-D", + "rust-2018-compatibility", + "-D", + "rust-2018-idioms", + "-D", + "rust-2021-compatibility", + "-D", + "unused", +] diff --git a/.dockerignore b/.dockerignore index 3d8a25cce..f42859922 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,16 +1,16 @@ -.git -.git-blame-ignore -.github -.gitignore -.vscode -bin/ -config.toml -config.toml.local -cSpell.json -data.db -docker/ -NOTICE -README.md -rustfmt.toml -storage/ -target/ +/.git +/.git-blame-ignore +/.github +/.gitignore +/.vscode +/bin/ +/tracker.* +/cSpell.json +/data.db +/docker/bin/ +/NOTICE +/README.md +/rustfmt.toml +/storage/ +/target/ +/etc/ diff --git a/.env.local b/.env.local deleted file mode 100644 index fefed56c4..000000000 --- a/.env.local +++ /dev/null @@ -1 +0,0 @@ -TORRUST_TRACKER_USER_UID=1000 \ No newline at end of file diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..2ae8963e3 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +/.github/**/* @torrust/maintainers diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml deleted file mode 100644 index 05551bafc..000000000 --- a/.github/workflows/codecov.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: Upload code coverage - -on: - push: - pull_request: - -env: - CARGO_TERM_COLOR: always - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: nightly - components: rustfmt, llvm-tools-preview - - name: Build - run: cargo build --release - env: - CARGO_INCREMENTAL: "0" - RUSTFLAGS: "-Cinstrument-coverage" - RUSTDOCFLAGS: "-Cinstrument-coverage" - - name: Test - run: cargo test --all-features --no-fail-fast - env: - CARGO_INCREMENTAL: "0" - RUSTFLAGS: "-Cinstrument-coverage" - RUSTDOCFLAGS: "-Cinstrument-coverage" - - name: Install grcov - run: if [[ ! -e ~/.cargo/bin/grcov ]]; then cargo install grcov; fi - - name: Run grcov - run: grcov . --binary-path target/debug/deps/ -s . -t lcov --branch --ignore-not-existing --ignore '../**' --ignore '/*' -o coverage.lcov - - uses: codecov/codecov-action@v3 - with: - files: ./coverage.lcov - flags: rust - fail_ci_if_error: true # optional (default = false) diff --git a/.github/workflows/container.yaml b/.github/workflows/container.yaml new file mode 100644 index 000000000..884a15843 --- /dev/null +++ b/.github/workflows/container.yaml @@ -0,0 +1,178 @@ +name: Container + +on: + push: + branches: + - "develop" + - "main" + - "releases/**/*" + pull_request: + branches: + - "develop" + - "main" + +env: + CARGO_TERM_COLOR: always + +jobs: + test: + name: Test (Docker) + runs-on: ubuntu-latest + + strategy: + matrix: + target: [debug, release] + + steps: + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v3 + + - id: build + name: Build + uses: docker/build-push-action@v5 + with: + file: ./Containerfile + push: false + load: true + target: ${{ matrix.target }} + tags: torrust-tracker:local + cache-from: type=gha + cache-to: type=gha + + - id: inspect + name: Inspect + run: docker image inspect torrust-tracker:local + + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + + - id: compose + name: Compose + run: docker compose build + + context: + name: Context + needs: test + runs-on: ubuntu-latest + + outputs: + continue: ${{ steps.check.outputs.continue }} + type: ${{ steps.check.outputs.type }} + version: ${{ steps.check.outputs.version }} + + steps: + - id: check + name: Check Context + run: | + if [[ "${{ github.repository }}" == "torrust/torrust-tracker" ]]; then + if [[ "${{ github.event_name }}" == "push" ]]; then + if [[ "${{ github.ref }}" == "refs/heads/main" ]]; then + + echo "type=development" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + echo "On \`main\` Branch, Type: \`development\`" + + elif [[ "${{ github.ref }}" == "refs/heads/develop" ]]; then + + echo "type=development" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + echo "On \`develop\` Branch, Type: \`development\`" + + elif [[ $(echo "${{ github.ref }}" | grep -P '^(refs\/heads\/releases\/)(v)(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$') ]]; then + + version=$(echo "${{ github.ref }}" | sed -n -E 's/^(refs\/heads\/releases\/)//p') + echo "version=$version" >> $GITHUB_OUTPUT + echo "type=release" >> $GITHUB_OUTPUT + echo "continue=true" >> $GITHUB_OUTPUT + echo "In \`releases/$version\` Branch, Type: \`release\`" + + else + echo "Not Correct Branch. Will Not Continue" + fi + else + echo "Not a Push Event. Will Not Continue" + fi + else + echo "On a Forked Repository. Will Not Continue" + fi + + publish_development: + name: Publish (Development) + environment: dockerhub-torrust + needs: context + if: needs.context.outputs.continue == 'true' && needs.context.outputs.type == 'development' + runs-on: ubuntu-latest + + steps: + - id: meta + name: Docker Meta + uses: docker/metadata-action@v5 + with: + images: | + "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" + tags: | + type=ref,event=branch + + - id: login + name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} + + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v3 + + - name: Build and push + uses: docker/build-push-action@v5 + with: + file: ./Containerfile + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha + + publish_release: + name: Publish (Release) + environment: dockerhub-torrust + needs: context + if: needs.context.outputs.continue == 'true' && needs.context.outputs.type == 'release' + runs-on: ubuntu-latest + + steps: + - id: meta + name: Docker Meta + uses: docker/metadata-action@v5 + with: + images: | + "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" + tags: | + type=semver,value=${{ needs.context.outputs.version }},pattern={{raw}} + type=semver,value=${{ needs.context.outputs.version }},pattern={{version}} + type=semver,value=${{ needs.context.outputs.version }},pattern=v{{major}} + type=semver,value=${{ needs.context.outputs.version }},pattern={{major}}.{{minor}} + + - id: login + name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_HUB_USERNAME }} + password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} + + - id: setup + name: Setup Toolchain + uses: docker/setup-buildx-action@v3 + + - name: Build and push + uses: docker/build-push-action@v5 + with: + file: ./Containerfile + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml new file mode 100644 index 000000000..1e7dace66 --- /dev/null +++ b/.github/workflows/coverage.yaml @@ -0,0 +1,73 @@ +name: Coverage + +on: + push: + branches: + - develop + pull_request_target: + branches: + - develop + +env: + CARGO_TERM_COLOR: always + +jobs: + report: + name: Report + environment: coverage + runs-on: ubuntu-latest + env: + CARGO_INCREMENTAL: "0" + RUSTFLAGS: "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" + RUSTDOCFLAGS: "-Z profile -C codegen-units=1 -C inline-threshold=0 -C link-dead-code -C overflow-checks=off -C panic=abort -Z panic_abort_tests" + + steps: + - id: checkout_push + if: github.event_name == 'push' + name: Checkout Repository (Push) + uses: actions/checkout@v4 + + - id: checkout_pull_request_target + if: github.event_name == 'pull_request_target' + name: Checkout Repository (Pull Request Target) + uses: actions/checkout@v4 + with: + ref: "refs/pull/${{ github.event.pull_request.number }}/head" + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: nightly + components: llvm-tools-preview + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: grcov + + - id: check + name: Run Build Checks + run: cargo check --workspace --all-targets --all-features + + - id: test + name: Run Unit Tests + run: cargo test --workspace --all-targets --all-features + + - id: coverage + name: Generate Coverage Report + uses: alekitto/grcov@v0.2 + + - id: upload + name: Upload Coverage Report + uses: codecov/codecov-action@v3 + with: + token: ${{ secrets.CODECOV_TOKEN }} + files: ${{ steps.coverage.outputs.report }} + verbose: true + fail_ci_if_error: true diff --git a/.github/workflows/deployment.yaml b/.github/workflows/deployment.yaml new file mode 100644 index 000000000..5df50a4b0 --- /dev/null +++ b/.github/workflows/deployment.yaml @@ -0,0 +1,59 @@ +name: Deployment + +on: + push: + branches: + - "releases/**/*" + +jobs: + test: + name: Test + runs-on: ubuntu-latest + + strategy: + matrix: + toolchain: [stable, nightly] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + + - id: test + name: Run Unit Tests + run: cargo test --tests --benches --examples --workspace --all-targets --all-features + + publish: + name: Publish + environment: deployment + needs: test + runs-on: ubuntu-latest + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: stable + + - id: publish + name: Publish Crates + env: + CARGO_REGISTRY_TOKEN: "${{ secrets.TORRUST_UPDATE_CARGO_REGISTRY_TOKEN }}" + run: | + cargo publish -p torrust-tracker-contrib-bencode + cargo publish -p torrust-tracker-located-error + cargo publish -p torrust-tracker-primitives + cargo publish -p torrust-tracker-configuration + cargo publish -p torrust-tracker-test-helpers + cargo publish -p torrust-tracker diff --git a/.github/workflows/publish_crate.yml b/.github/workflows/publish_crate.yml deleted file mode 100644 index 4d5d0772e..000000000 --- a/.github/workflows/publish_crate.yml +++ /dev/null @@ -1,57 +0,0 @@ -name: Publish crate - -on: - push: - tags: - - "v*" - -jobs: - check-secret: - runs-on: ubuntu-latest - environment: crates-io-torrust - outputs: - publish: ${{ steps.check.outputs.publish }} - steps: - - id: check - env: - CRATES_TOKEN: "${{ secrets.CRATES_TOKEN }}" - if: "${{ env.CRATES_TOKEN != '' }}" - run: echo "publish=true" >> $GITHUB_OUTPUT - - test: - needs: check-secret - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Run Tests - run: cargo test - - publish: - needs: test - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - environment: crates-io-torrust - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Install stable toolchain - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - - - name: Publish workspace packages - run: | - cargo publish -p torrust-tracker-located-error - cargo publish -p torrust-tracker-primitives - cargo publish -p torrust-tracker-configuration - cargo publish -p torrust-tracker-test-helpers - cargo publish -p torrust-tracker - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_TOKEN }} diff --git a/.github/workflows/publish_docker_image.yml b/.github/workflows/publish_docker_image.yml deleted file mode 100644 index 1dd65e3a7..000000000 --- a/.github/workflows/publish_docker_image.yml +++ /dev/null @@ -1,86 +0,0 @@ -name: Publish docker image - -on: - push: - branches: - - "main" - - "develop" - tags: - - "v*" - -env: - # Azure file share volume mount requires the Linux container run as root - # https://learn.microsoft.com/en-us/azure/container-instances/container-instances-volume-azure-files#limitations - # TORRUST_TRACKER_RUN_AS_USER: root - TORRUST_TRACKER_RUN_AS_USER: appuser - -jobs: - check-secret: - runs-on: ubuntu-latest - environment: dockerhub-torrust - outputs: - publish: ${{ steps.check.outputs.publish }} - steps: - - id: check - env: - DOCKER_HUB_USERNAME: "${{ secrets.DOCKER_HUB_USERNAME }}" - if: "${{ env.DOCKER_HUB_USERNAME != '' }}" - run: echo "publish=true" >> $GITHUB_OUTPUT - - test: - needs: check-secret - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Run Tests - run: cargo test - - dockerhub: - needs: test - if: needs.check-secret.outputs.publish == 'true' - runs-on: ubuntu-latest - environment: dockerhub-torrust - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Docker meta - id: meta - uses: docker/metadata-action@v4 - with: - images: | - # For example: torrust/tracker - "${{ secrets.DOCKER_HUB_USERNAME }}/${{secrets.DOCKER_HUB_REPOSITORY_NAME }}" - tags: | - type=ref,event=branch - type=ref,event=pr - type=semver,pattern={{version}} - type=semver,pattern={{major}}.{{minor}} - - - name: Login to Docker Hub - uses: docker/login-action@v2 - with: - username: ${{ secrets.DOCKER_HUB_USERNAME }} - password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }} - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Build and push - uses: docker/build-push-action@v4 - with: - context: . - file: ./Dockerfile - build-args: | - RUN_AS_USER=${{ env.TORRUST_TRACKER_RUN_AS_USER }} - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha - cache-to: type=gha,mode=max diff --git a/.github/workflows/test_build_release.yml b/.github/workflows/test_build_release.yml deleted file mode 100644 index 88234b97a..000000000 --- a/.github/workflows/test_build_release.yml +++ /dev/null @@ -1,81 +0,0 @@ -name: CI - -# Only trigger, when the test workflow succeeded -on: [push, pull_request] - -jobs: - format: - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: nightly - components: rustfmt, clippy - - uses: Swatinem/rust-cache@v2 - - name: Check Rust Formatting - run: cargo fmt --check - - test: - needs: format - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - components: llvm-tools-preview - - uses: Swatinem/rust-cache@v2 - - name: Check Rust Code - run: cargo check --all-targets - - name: Clippy Rust Code - run: cargo clippy --all-targets -- -D clippy::pedantic - - name: Test Documentation - run: cargo test --doc - - name: Run Tests - run: cargo test --workspace - - uses: taiki-e/install-action@cargo-llvm-cov - - uses: taiki-e/install-action@nextest - - name: Show coverage - run: cargo llvm-cov nextest - - build: - needs: test - if: | - github.event_name == 'push' && - github.event.base_ref == 'refs/heads/main' && - startsWith(github.ref, 'refs/tags/v') - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@v3 - - uses: dtolnay/rust-toolchain@stable - with: - toolchain: stable - - uses: Swatinem/rust-cache@v2 - - name: Build Torrust Tracker - run: cargo build --release - - name: Upload Build Artifact - uses: actions/upload-artifact@v3 - with: - name: torrust-tracker - path: ./target/release/torrust-tracker - - release: - needs: build - runs-on: ubuntu-latest - steps: - - name: Download Build Artifact - uses: actions/download-artifact@v3 - with: - name: torrust-tracker - - name: Release - uses: softprops/action-gh-release@v1 -# with: -# files: | -# torrust-tracker diff --git a/.github/workflows/test_docker.yml b/.github/workflows/test_docker.yml deleted file mode 100644 index 0c3fc36d8..000000000 --- a/.github/workflows/test_docker.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Test docker build - -on: - push: - pull_request: - -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Build docker image - uses: docker/build-push-action@v3 - with: - context: . - file: ./Dockerfile - push: false - cache-from: type=gha - cache-to: type=gha,mode=max - - - name: Build docker-compose images - run: docker compose build diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml new file mode 100644 index 000000000..21c47665f --- /dev/null +++ b/.github/workflows/testing.yaml @@ -0,0 +1,110 @@ +name: Testing + +on: + push: + pull_request: + +env: + CARGO_TERM_COLOR: always + +jobs: + format: + name: Formatting + runs-on: ubuntu-latest + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: nightly + components: rustfmt + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: format + name: Run Formatting-Checks + run: cargo fmt --check + + check: + name: Static Analysis + runs-on: ubuntu-latest + needs: format + + strategy: + matrix: + toolchain: [stable, nightly] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + components: clippy + + - id: cache + name: Enable Workflow Cache + uses: Swatinem/rust-cache@v2 + + - id: check + name: Run Build Checks + run: cargo check --tests --benches --examples --workspace --all-targets --all-features + + - id: lint + name: Run Lint Checks + run: cargo clippy --tests --benches --examples --workspace --all-targets --all-features -- -D clippy::correctness -D clippy::suspicious -D clippy::complexity -D clippy::perf -D clippy::style -D clippy::pedantic + + - id: doc + name: Run Documentation Checks + run: cargo test --doc + + unit: + name: Units + runs-on: ubuntu-latest + needs: check + + strategy: + matrix: + toolchain: [stable, nightly] + + steps: + - id: checkout + name: Checkout Repository + uses: actions/checkout@v4 + + - id: setup + name: Setup Toolchain + uses: dtolnay/rust-toolchain@stable + with: + toolchain: ${{ matrix.toolchain }} + components: llvm-tools-preview + + - id: cache + name: Enable Job Cache + uses: Swatinem/rust-cache@v2 + + - id: tools + name: Install Tools + uses: taiki-e/install-action@v2 + with: + tool: cargo-llvm-cov, cargo-nextest + + - id: test + name: Run Unit Tests + run: cargo test --tests --benches --examples --workspace --all-targets --all-features + + # Temporary Disable https://github.com/time-rs/time/issues/618 + # - id: coverage + # name: Generate Coverage Report + # run: cargo llvm-cov nextest --tests --benches --examples --workspace --all-targets --all-features diff --git a/.gitignore b/.gitignore index 6b58dcb45..2d8d0b8bd 100644 --- a/.gitignore +++ b/.gitignore @@ -3,9 +3,10 @@ /.coverage/ /.idea/ /.vscode/launch.json -/config.toml +/tracker.toml /data.db /database.db /database.json.bz2 /storage/ /target +/tracker.* diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 11d11a5c5..934a43eb8 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,6 +1,7 @@ { "recommendations": [ "streetsidesoftware.code-spell-checker", - "rust-lang.rust-analyzer" + "rust-lang.rust-analyzer", + "tamasfe.even-better-toml" ] } \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 94f199bd6..661243fbe 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,8 +1,28 @@ { - "[rust]": { - "editor.formatOnSave": true - }, - "rust-analyzer.checkOnSave.command": "clippy", - "rust-analyzer.checkOnSave.allTargets": true, - "rust-analyzer.checkOnSave.extraArgs": ["--","-W","clippy::pedantic"], + "[rust]": { + "editor.formatOnSave": true + }, + "rust-analyzer.checkOnSave": true, + "rust-analyzer.check.command": "clippy", + "rust-analyzer.check.allTargets": true, + "rust-analyzer.check.extraArgs": [ + "--", + "-D", + "clippy::correctness", + "-D", + "clippy::suspicious", + "-W", + "clippy::complexity", + "-W", + "clippy::perf", + "-W", + "clippy::style", + "-W", + "clippy::pedantic", + ], + "evenBetterToml.formatter.allowedBlankLines": 1, + "evenBetterToml.formatter.columnWidth": 130, + "evenBetterToml.formatter.trailingNewline": true, + "evenBetterToml.formatter.reorderKeys": true, + "evenBetterToml.formatter.reorderArrays": true, } \ No newline at end of file diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100644 index 000000000..6eef820ec --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,11 @@ +Copyright 2023 in the Torrust-Tracker project are retained by their contributors. No +copyright assignment is required to contribute to the Torrust-Tracker project. + +Some files include explicit copyright notices and/or license notices. + +Except as otherwise noted (below and/or in individual files), Torrust-Tracker is +licensed under the GNU Affero General Public License, Version 3.0 . This license applies to all files in the Torrust-Tracker project, except as noted below. + +Except as otherwise noted (below and/or in individual files), Torrust-Tracker is licensed under the MIT-0 license for all commits made after 5 years of merging. This license applies to the version of the files merged into the Torrust-Tracker project at the time of merging, and does not apply to subsequent updates or revisions to those files. + +The contributors to the Torrust-Tracker project disclaim all liability for any damages or losses that may arise from the use of the project. diff --git a/Cargo.lock b/Cargo.lock index 899e8855f..b6b9370f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.19.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a76fd60b23679b7d19bd066031410fb7e458ccc5e958eb5c325888ce4baedc97" +checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" dependencies = [ "gimli", ] @@ -41,13 +41,40 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "0.7.20" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" +checksum = "0c378d78423fdad8089616f827526ee33c19f2fddbd5de1629152c9593ba4783" dependencies = [ "memchr", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "allocator-api2" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + [[package]] name = "android_system_properties" version = "0.1.5" @@ -57,6 +84,18 @@ dependencies = [ "libc", ] +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstyle" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b84bf0a05bbb2a83e5eb6fa36bb6e87baa08193c35ff52bbf6b38d8af2890e46" + [[package]] name = "aquatic_udp_protocol" version = "0.8.0" @@ -75,19 +114,35 @@ checksum = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6" [[package]] name = "arrayvec" -version = "0.7.2" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" + +[[package]] +name = "async-compression" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" +checksum = "bb42b2197bf15ccb092b62c74515dbd8b86d0effd934795f6687c93b6e679a2c" +dependencies = [ + "brotli", + "flate2", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "zstd", + "zstd-safe", +] [[package]] name = "async-trait" -version = "0.1.68" +version = "0.1.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" +checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] @@ -98,13 +153,13 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "axum" -version = "0.6.15" +version = "0.6.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b32c5ea3aabaf4deb5f5ced2d688ec0844c881c9e6c696a8b769a05fc691e62" +checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf" dependencies = [ "async-trait", "axum-core", - "bitflags", + "bitflags 1.3.2", "bytes", "futures-util", "http", @@ -130,9 +185,9 @@ dependencies = [ [[package]] name = "axum-client-ip" -version = "0.4.0" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d719fabd6813392bbc10e1fe67f2977fad52791a836e51236f7e02f2482e017" +checksum = "1ef117890a418b7832678d9ea1e1c08456dd7b2fd1dadb9676cd6f0fe7eb4b21" dependencies = [ "axum", "forwarded-header-value", @@ -158,9 +213,9 @@ dependencies = [ [[package]] name = "axum-server" -version = "0.4.7" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bace45b270e36e3c27a190c65883de6dfc9f1d18c829907c127464815dc67b24" +checksum = "447f28c85900215cc1bea282f32d4a2f22d55c5a300afdfbc661c8d6a632e063" dependencies = [ "arc-swap", "bytes", @@ -178,9 +233,9 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.67" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "233d376d6d185f2a3093e58f283f60f880315b6c60075b01f36b3b85154564ca" +checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" dependencies = [ "addr2line", "cc", @@ -199,15 +254,15 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.0" +version = "0.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a" +checksum = "9ba43ea6f343b788c8764558649e08df62f86c6ef251fdaeb1ffd010a9ae50a2" [[package]] name = "bigdecimal" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aaf33151a6429fe9211d1b276eafdf70cdff28b071e76c0b0e1503221ea3744" +checksum = "a6773ddc0eafc0e509fb60e48dff7f450f8e674a0686ae8605e8d9901bd5eefa" dependencies = [ "num-bigint", "num-integer", @@ -222,11 +277,11 @@ checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" [[package]] name = "bindgen" -version = "0.59.2" +version = "0.68.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bd2a9a458e8f4304c52c43ebb0cfbd520289f8379a52e329a38afda99bf8eb8" +checksum = "726e4313eb6ec35d2730258ad4e15b547ee75d6afaa1361a922e78e59b7d8078" dependencies = [ - "bitflags", + "bitflags 2.4.0", "cexpr", "clang-sys", "lazy_static", @@ -237,22 +292,20 @@ dependencies = [ "regex", "rustc-hash", "shlex", + "syn 2.0.35", ] [[package]] -name = "bip_bencode" -version = "0.4.4" +name = "bitflags" +version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6048cc5d9680544a5098a290d2845df7dae292c97687b9896b70365bad0ea416" -dependencies = [ - "error-chain", -] +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "1.3.2" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" +checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" [[package]] name = "bitvec" @@ -293,7 +346,7 @@ checksum = "0754613691538d51f329cce9af41d7b7ca150bc973056f1156611489475f54f7" dependencies = [ "borsh-derive-internal", "borsh-schema-derive-internal", - "proc-macro-crate", + "proc-macro-crate 0.1.5", "proc-macro2", "syn 1.0.109", ] @@ -320,6 +373,27 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "brotli" +version = "3.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a0b1dbcc8ae29329621f8d4f0d835787c1c38bb1401979b49d13b0b305ff68" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "2.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b6561fd3f895a11e8f72af2cb7d22e08366bebc2b6b57f7744c4bda27034744" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bufstream" version = "0.1.4" @@ -328,15 +402,15 @@ checksum = "40e38929add23cdf8a366df9b0e088953150724bcbe5fc330b0d8eb3b328eec8" [[package]] name = "bumpalo" -version = "3.12.0" +version = "3.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535" +checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" [[package]] name = "bytecheck" -version = "0.6.10" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13fe11640a23eb24562225322cd3e452b93a3d4091d62fab69c70542fcd17d1f" +checksum = "8b6372023ac861f6e6dc89c8344a8f398fb42aaba2b5dbc649ca0c0e9dbcb627" dependencies = [ "bytecheck_derive", "ptr_meta", @@ -345,9 +419,9 @@ dependencies = [ [[package]] name = "bytecheck_derive" -version = "0.6.10" +version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31225543cb46f81a7e224762764f4a6a0f097b1db0b175f69e8065efaa42de5" +checksum = "a7ec4c6f261935ad534c0c22dbef2201b45918860eb1c574b972bd213a76af61" dependencies = [ "proc-macro2", "quote", @@ -362,15 +436,25 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "bytes" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" +checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" + +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.0.79" +version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" +checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" +dependencies = [ + "jobserver", + "libc", +] [[package]] name = "cexpr" @@ -389,18 +473,42 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.24" +version = "0.4.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e3c5919066adf22df73762e50cffcde3a758f2a848b113b586d1f86728b673b" +checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" dependencies = [ + "android-tzdata", "iana-time-zone", - "js-sys", - "num-integer", "num-traits", "serde", - "time 0.1.45", - "wasm-bindgen", - "winapi", + "windows-targets", +] + +[[package]] +name = "ciborium" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "effd91f6c78e5a4ace8a5d3c0b6bfaec9e2baaef55f3efc00e45fb2e477ee926" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdf919175532b369853f5d5e20b26b43112613fd6fe7aee757e35f7a44642656" + +[[package]] +name = "ciborium-ll" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "defaa24ecc093c77630e6c15e17c51f5e187bf35ee514f4e2d67baaa96dae22b" +dependencies = [ + "ciborium-io", + "half", ] [[package]] @@ -415,22 +523,37 @@ dependencies = [ ] [[package]] -name = "cmake" -version = "0.1.50" +name = "clap" +version = "4.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31c789563b815f77f4250caee12365734369f942439b7defd71e18a48197130" +checksum = "84ed82781cea27b43c9b106a979fe450a13a31aab0500595fb3fc06616de08e6" dependencies = [ - "cc", + "clap_builder", ] [[package]] -name = "codespan-reporting" -version = "0.11.1" +name = "clap_builder" +version = "4.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +checksum = "2bb9faaa7c2ef94b2743a21f5a29e6f0010dff4caa69ac8e9d6cf8b6fa74da08" dependencies = [ - "termcolor", - "unicode-width", + "anstyle", + "clap_lex", +] + +[[package]] +name = "clap_lex" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961" + +[[package]] +name = "cmake" +version = "0.1.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31c789563b815f77f4250caee12365734369f942439b7defd71e18a48197130" +dependencies = [ + "cc", ] [[package]] @@ -476,9 +599,9 @@ checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" [[package]] name = "cpufeatures" -version = "0.2.6" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "280a9f2d8b3a38871a3c8a46fb80db65e5e5ed97da80c4d08bf27fb63e35e181" +checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" dependencies = [ "libc", ] @@ -492,6 +615,42 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "criterion" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "is-terminal", + "itertools", + "num-traits", + "once_cell", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_derive", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" +dependencies = [ + "cast", + "itertools", +] + [[package]] name = "crossbeam" version = "0.8.2" @@ -529,9 +688,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.14" +version = "0.9.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46bd5f3f85273295a9d14aedfb86f6aadbff6d8f5295c4a9edb08e819dcf5695" +checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7" dependencies = [ "autocfg", "cfg-if", @@ -552,9 +711,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.15" +version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b" +checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" dependencies = [ "cfg-if", ] @@ -569,55 +728,11 @@ dependencies = [ "typenum", ] -[[package]] -name = "cxx" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f61f1b6389c3fe1c316bf8a4dccc90a38208354b330925bce1f74a6c4756eb93" -dependencies = [ - "cc", - "cxxbridge-flags", - "cxxbridge-macro", - "link-cplusplus", -] - -[[package]] -name = "cxx-build" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cee708e8962df2aeb38f594aae5d827c022b6460ac71a7a3e2c3c2aae5a07b" -dependencies = [ - "cc", - "codespan-reporting", - "once_cell", - "proc-macro2", - "quote", - "scratch", - "syn 2.0.14", -] - -[[package]] -name = "cxxbridge-flags" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7944172ae7e4068c533afbb984114a56c46e9ccddda550499caa222902c7f7bb" - -[[package]] -name = "cxxbridge-macro" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2345488264226bf682893e25de0769f3360aac9957980ec49361b083ddaa5bc5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.14", -] - [[package]] name = "darling" -version = "0.14.4" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" +checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e" dependencies = [ "darling_core", "darling_macro", @@ -625,27 +740,36 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.14.4" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" +checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", "strsim", - "syn 1.0.109", + "syn 2.0.35", ] [[package]] name = "darling_macro" -version = "0.14.4" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" +checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ "darling_core", "quote", - "syn 1.0.109", + "syn 2.0.35", +] + +[[package]] +name = "deranged" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2696e8a945f658fd14dc3b87242e6b80cd0f36ff04ea560fa39082368847946" +dependencies = [ + "serde", ] [[package]] @@ -663,13 +787,13 @@ dependencies = [ [[package]] name = "derive_utils" -version = "0.13.0" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff8f6a793f528719e1ad4425a52a213ac1214ac7158c5fb97a7f50a64bfc96d" +checksum = "9abcad25e9720609ccb3dcdb795d845e37d8ce34183330a9f48b03a1a71c8e21" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] @@ -680,9 +804,9 @@ checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" [[package]] name = "digest" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", @@ -702,28 +826,34 @@ checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "either" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" +checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" [[package]] name = "encoding_rs" -version = "0.8.32" +version = "0.8.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394" +checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1" dependencies = [ "cfg-if", ] +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + [[package]] name = "errno" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" +checksum = "136526188508e25c6fef639d7927dfb3e0e3084488bf202267829cf7fc23dbdd" dependencies = [ "errno-dragonfly", "libc", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -738,11 +868,12 @@ dependencies = [ [[package]] name = "error-chain" -version = "0.11.0" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff511d5dc435d703f4971bc399647c9bc38e20cb41452e3b9feb4765419ed3f3" +checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" dependencies = [ "backtrace", + "version_check", ] [[package]] @@ -759,12 +890,9 @@ checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" [[package]] name = "fastrand" -version = "1.9.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" -dependencies = [ - "instant", -] +checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" [[package]] name = "fern" @@ -777,9 +905,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.25" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841" +checksum = "c6c98ee8095e9d1dcbf2fcc6d95acccb90d1c81db1e44725c6a984b1dbdfb010" dependencies = [ "crc32fast", "libz-sys", @@ -818,9 +946,9 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "form_urlencoded" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" +checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" dependencies = [ "percent-encoding", ] @@ -843,9 +971,9 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "frunk" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89c703bf50009f383a0873845357cc400a95fc535f836feddfe015d7df6e1e0" +checksum = "11a351b59e12f97b4176ee78497dff72e4276fb1ceb13e19056aca7fa0206287" dependencies = [ "frunk_core", "frunk_derives", @@ -854,55 +982,43 @@ dependencies = [ [[package]] name = "frunk_core" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a446d01a558301dca28ef43222864a9fa2bd9a2e71370f769d5d5d5ec9f3537" +checksum = "af2469fab0bd07e64ccf0ad57a1438f63160c69b2e57f04a439653d68eb558d6" [[package]] name = "frunk_derives" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173" +checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 1.0.109", + "syn 2.0.35", ] [[package]] name = "frunk_proc_macro_helpers" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "015425591bbeb0f5b8a75593340f1789af428e9f887a4f1e36c0c471f067ef50" +checksum = "35b54add839292b743aeda6ebedbd8b11e93404f902c56223e51b9ec18a13d2c" dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.35", ] [[package]] name = "frunk_proc_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea01524f285deab48affffb342b97f186e657b119c3f1821ac531780e0fbfae0" -dependencies = [ - "frunk_core", - "frunk_proc_macros_impl", - "proc-macro-hack", -] - -[[package]] -name = "frunk_proc_macros_impl" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a802d974cc18ee7fe1a7868fc9ce31086294fd96ba62f8da64ecb44e92a2653" +checksum = "71b85a1d4a9a6b300b41c05e8e13ef2feca03e0334127f29eca9506a7fe13a93" dependencies = [ "frunk_core", "frunk_proc_macro_helpers", - "proc-macro-hack", "quote", - "syn 1.0.109", + "syn 2.0.35", ] [[package]] @@ -967,7 +1083,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] @@ -1012,20 +1128,20 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4" +checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" dependencies = [ "cfg-if", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi", ] [[package]] name = "gimli" -version = "0.27.2" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad0a93d233ebf96623465aad4046a8d3aa4da22d4f4beba5388838c8a434bbb4" +checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" [[package]] name = "glob" @@ -1035,9 +1151,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.16" +version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5be7b54589b581f624f566bf5d8eb2bab1db736c51528720b6bd36b96b55924d" +checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833" dependencies = [ "bytes", "fnv", @@ -1045,13 +1161,19 @@ dependencies = [ "futures-sink", "futures-util", "http", - "indexmap", + "indexmap 1.9.3", "slab", "tokio", "tokio-util", "tracing", ] +[[package]] +name = "half" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" + [[package]] name = "hashbrown" version = "0.12.3" @@ -1071,28 +1193,35 @@ dependencies = [ ] [[package]] -name = "hashlink" -version = "0.8.1" +name = "hashbrown" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69fe1fcf8b4278d860ad0548329f892a3631fb63f82574df68275f34cdbe0ffa" +checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a" dependencies = [ - "hashbrown 0.12.3", + "ahash 0.8.3", + "allocator-api2", ] [[package]] -name = "hermit-abi" -version = "0.2.6" +name = "hashlink" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" +checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" dependencies = [ - "libc", + "hashbrown 0.14.0", ] +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + [[package]] name = "hermit-abi" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" +checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" [[package]] name = "hex" @@ -1122,6 +1251,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-range-header" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" + [[package]] name = "httparse" version = "1.8.0" @@ -1130,15 +1265,15 @@ checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" [[package]] name = "httpdate" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "0.14.25" +version = "0.14.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc5e554ff619822309ffd57d8734d77cd5ce6238bc956f037ea06c58238c9899" +checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" dependencies = [ "bytes", "futures-channel", @@ -1151,7 +1286,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "socket2", + "socket2 0.4.9", "tokio", "tower-service", "tracing", @@ -1173,9 +1308,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.56" +version = "0.1.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0722cd7114b7de04316e7ea5456a0bbb20e4adb46fd27a3697adb812cff0f37c" +checksum = "2fad5b825842d2b38bd206f3e81d6957625fd7f0a361e345c30e01a0ae2dd613" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -1187,12 +1322,11 @@ dependencies = [ [[package]] name = "iana-time-zone-haiku" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" dependencies = [ - "cxx", - "cxx-build", + "cc", ] [[package]] @@ -1203,9 +1337,9 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "idna" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" +checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" dependencies = [ "unicode-bidi", "unicode-normalization", @@ -1223,40 +1357,42 @@ dependencies = [ ] [[package]] -name = "instant" -version = "0.1.12" +name = "indexmap" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" dependencies = [ - "cfg-if", + "equivalent", + "hashbrown 0.14.0", + "serde", ] [[package]] name = "io-enum" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01c662c349c9c9f542e7bfd9134143beb27da4b20dfbc3b3ef5b2a5b507dafbd" +checksum = "5305557fa27b460072ae15ce07617e999f5879f14d376c8449f0bfb9f9d8e91e" dependencies = [ "derive_utils", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] -name = "io-lifetimes" -version = "1.0.10" +name = "ipnet" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c66c74d2ae7e79a5a8f7ac924adbe38ee42a859c6539ad869eb51f0b52dc220" -dependencies = [ - "hermit-abi 0.3.1", - "libc", - "windows-sys 0.48.0", -] +checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" [[package]] -name = "ipnet" -version = "2.7.2" +name = "is-terminal" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" +checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +dependencies = [ + "hermit-abi", + "rustix", + "windows-sys", +] [[package]] name = "itertools" @@ -1269,15 +1405,24 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.6" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" +checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" + +[[package]] +name = "jobserver" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "936cfd212a0155903bcbc060e316fb6cc7cbf2e1907329391ebadc1fe0ce77c2" +dependencies = [ + "libc", +] [[package]] name = "js-sys" -version = "0.3.61" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445dde2150c55e483f3d8416706b97ec8e8237c307e5b7b4b8dd15e6af2a0730" +checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" dependencies = [ "wasm-bindgen", ] @@ -1380,9 +1525,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.141" +version = "0.2.148" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3304a64d199bb964be99741b7a14d26972741915b3649639149b2479bb46f4b5" +checksum = "9cdc71e17332e86d2e1d38c1f99edcb6288ee11b815fb1a4b049eaa2114d369b" [[package]] name = "libloading" @@ -1396,9 +1541,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.25.2" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29f835d03d717946d28b1d1ed632eb6f0e24a299388ee623d0c23118d3e8a7fa" +checksum = "afc22eff61b133b115c6e8c74e818c628d6d5e7a502afea6f64dee076dd94326" dependencies = [ "cc", "pkg-config", @@ -1407,24 +1552,15 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.8" +version = "1.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf" +checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b" dependencies = [ "cc", "pkg-config", "vcpkg", ] -[[package]] -name = "link-cplusplus" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" -dependencies = [ - "cc", -] - [[package]] name = "linked-hash-map" version = "0.5.6" @@ -1433,27 +1569,27 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.3.1" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d59d8c75012853d2e872fb56bc8a2e53718e2cafe1a4c823143141c6d90c322f" +checksum = "1a9bad9f94746442c783ca431b22403b519cd7fbeed0533fdd6328b2f2212128" [[package]] name = "local-ip-address" -version = "0.5.1" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faa9d02443a1741e9f51dafdfcbffb3863b2a89c457d762b40337d6c5153ef81" +checksum = "3fefe707432eb6bd4704b3dacfc87aab269d56667ad05dcd6869534e8890e767" dependencies = [ "libc", "neli", "thiserror", - "windows-sys 0.42.0", + "windows-sys", ] [[package]] name = "lock_api" -version = "0.4.9" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" +checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" dependencies = [ "autocfg", "scopeguard", @@ -1461,39 +1597,36 @@ dependencies = [ [[package]] name = "log" -version = "0.4.17" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" -dependencies = [ - "cfg-if", -] +checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" [[package]] name = "lru" -version = "0.8.1" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6e8aaa3f231bb4bd57b84b2d5dc3ae7f350265df8aa96492e0bc394a1571909" +checksum = "718e8fae447df0c7e1ba7f5189829e63fd536945c8988d61444c19039f16b670" dependencies = [ - "hashbrown 0.12.3", + "hashbrown 0.13.2", ] [[package]] name = "matchit" -version = "0.7.0" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b87248edafb776e59e6ee64a79086f65890d3510f2c656c000bf2a7e8a0aea40" +checksum = "ed1202b2a6f884ae56f04cff409ab315c5ce26b5e58d7412e484f01fd52f52ef" [[package]] name = "memchr" -version = "2.5.0" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +checksum = "8f232d6ef707e1956a43342693d2a31e72989554d58299d7a88738cc95b0d35c" [[package]] name = "memoffset" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1" +checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" dependencies = [ "autocfg", ] @@ -1512,23 +1645,22 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.6.2" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" +checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" dependencies = [ "adler", ] [[package]] name = "mio" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9" +checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" dependencies = [ "libc", - "log", - "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.45.0", + "wasi", + "windows-sys", ] [[package]] @@ -1569,9 +1701,9 @@ dependencies = [ [[package]] name = "mysql" -version = "23.0.1" +version = "24.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f11339ca5c251941805d51362a07823605a80586ced92914ab7de84fba813f" +checksum = "cfe2babc5f5b354eab9c0a0e40da3e69c4d77421c8b9b6ee03f97acc75bd7955" dependencies = [ "bufstream", "bytes", @@ -1588,21 +1720,39 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "socket2", + "socket2 0.5.4", "twox-hash", "url", ] +[[package]] +name = "mysql-common-derive" +version = "0.30.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56b0d8a0db9bf6d2213e11f2c701cb91387b0614361625ab7b9743b41aa4938f" +dependencies = [ + "darling", + "heck", + "num-bigint", + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.35", + "termcolor", + "thiserror", +] + [[package]] name = "mysql_common" -version = "0.29.2" +version = "0.30.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9006c95034ccf7b903d955f210469119f6c3477fc9c9e7a7845ce38a3e665c2a" +checksum = "57349d5a326b437989b6ee4dc8f2f34b0cc131202748414712a8e7d98952fc8c" dependencies = [ - "base64 0.13.1", + "base64 0.21.4", "bigdecimal", "bindgen", - "bitflags", + "bitflags 2.4.0", "bitvec", "byteorder", "bytes", @@ -1613,6 +1763,7 @@ dependencies = [ "frunk", "lazy_static", "lexical", + "mysql-common-derive", "num-bigint", "num-traits", "rand", @@ -1626,7 +1777,7 @@ dependencies = [ "smallvec", "subprocess", "thiserror", - "time 0.3.20", + "time", "uuid", ] @@ -1659,12 +1810,27 @@ dependencies = [ [[package]] name = "neli" -version = "0.5.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9053554eb5dcb7e10d9cdab1206965bde870eed5d0d341532ca035e3ba221508" +checksum = "1100229e06604150b3becd61a4965d5c70f3be1759544ea7274166f4be41ef43" dependencies = [ "byteorder", "libc", + "log", + "neli-proc-macros", +] + +[[package]] +name = "neli-proc-macros" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c168194d373b1e134786274020dae7fc5513d565ea2ebb9bc9ff17ffb69106d4" +dependencies = [ + "either", + "proc-macro2", + "quote", + "serde", + "syn 1.0.109", ] [[package]] @@ -1691,9 +1857,9 @@ checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" [[package]] name = "num-bigint" -version = "0.4.3" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" +checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0" dependencies = [ "autocfg", "num-integer", @@ -1712,45 +1878,51 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" dependencies = [ "autocfg", ] [[package]] name = "num_cpus" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi 0.2.6", + "hermit-abi", "libc", ] [[package]] name = "object" -version = "0.30.3" +version = "0.32.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea86265d3d3dcb6a27fc51bd29a4bf387fae9d2986b823079d4986af253eb439" +checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" dependencies = [ "memchr", ] [[package]] name = "once_cell" -version = "1.17.1" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" +checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" + +[[package]] +name = "oorandom" +version = "11.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" [[package]] name = "openssl" -version = "0.10.50" +version = "0.10.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e30d8bc91859781f0a943411186324d580f2bbeb71b452fe91ae344806af3f1" +checksum = "bac25ee399abb46215765b1cb35bc0212377e58a061560d8b29b024fd0430e7c" dependencies = [ - "bitflags", + "bitflags 2.4.0", "cfg-if", "foreign-types", "libc", @@ -1767,7 +1939,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] @@ -1778,18 +1950,18 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-src" -version = "111.25.2+1.1.1t" +version = "300.1.3+3.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320708a054ad9b3bf314688b5db87cf4d6683d64cfc835e2337924ae62bf4431" +checksum = "cd2c101a165fff9935e34def4669595ab1c7847943c42be86e21503e482be107" dependencies = [ "cc", ] [[package]] name = "openssl-sys" -version = "0.9.85" +version = "0.9.93" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d3d193fb1488ad46ffe3aaabc912cc931d02ee8518fe2959aea8ef52718b0c0" +checksum = "db4d56a4c0478783083cfafcc42493dd4a981d41669da64b4572a2a089b51b1d" dependencies = [ "cc", "libc", @@ -1820,15 +1992,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.7" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" +checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.2.16", + "redox_syscall", "smallvec", - "windows-sys 0.45.0", + "windows-targets", ] [[package]] @@ -1845,34 +2017,36 @@ checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" [[package]] name = "pem" -version = "1.1.1" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8835c273a76a90455d7344889b0964598e3316e2a79ede8e36f16bdcf2228b8" +checksum = "6b13fe415cdf3c8e44518e18a7c95a13431d9bdf6d15367d82b23c377fdd441a" dependencies = [ - "base64 0.13.1", + "base64 0.21.4", + "serde", ] [[package]] name = "percent-encoding" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" +checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" [[package]] name = "pest" -version = "2.5.7" +version = "2.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b1403e8401ad5dedea73c626b99758535b342502f8d1e361f4a2dd952749122" +checksum = "d7a4d085fd991ac8d5b05a147b437791b4260b76326baf0fc60cf7c9c27ecd33" dependencies = [ + "memchr", "thiserror", "ucd-trie", ] [[package]] name = "pest_derive" -version = "2.5.7" +version = "2.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be99c4c1d2fc2769b1d00239431d711d08f6efedcecb8b6e30707160aee99c15" +checksum = "a2bee7be22ce7918f641a33f08e3f43388c7656772244e2bbb2477f44cc9021a" dependencies = [ "pest", "pest_generator", @@ -1880,22 +2054,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.5.7" +version = "2.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e56094789873daa36164de2e822b3888c6ae4b4f9da555a1103587658c805b1e" +checksum = "d1511785c5e98d79a05e8a6bc34b4ac2168a0e3e92161862030ad84daa223141" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] name = "pest_meta" -version = "2.5.7" +version = "2.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6733073c7cff3d8459fda0e42f13a047870242aed8b509fe98000928975f359e" +checksum = "b42f0394d3123e33353ca5e1e89092e533d2cc490389f2bd6131c43c634ebc5f" dependencies = [ "once_cell", "pest", @@ -1904,29 +2078,29 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.0.12" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc" +checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.0.12" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" +checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.35", ] [[package]] name = "pin-project-lite" -version = "0.2.9" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" +checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" [[package]] name = "pin-utils" @@ -1936,9 +2110,37 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pkg-config" -version = "0.3.26" +version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160" +checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" + +[[package]] +name = "plotters" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c224ba00d7cadd4d5c660deaf2098e5e80e07846537c51f9cfa4be50c1fd45" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e76628b4d3a7581389a35d5b6e2139607ad7c75b17aed325f210aa91f4a9609" + +[[package]] +name = "plotters-svg" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38f6d39893cca0701371e3c27294f09797214b86f1fb951b89ade8ec04e2abab" +dependencies = [ + "plotters-backend", +] [[package]] name = "ppv-lite86" @@ -1986,16 +2188,44 @@ dependencies = [ ] [[package]] -name = "proc-macro-hack" -version = "0.5.20+deprecated" +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] [[package]] name = "proc-macro2" -version = "1.0.56" +version = "1.0.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" +checksum = "3d433d9f1a3e8c1263d9456598b16fec66f4acc9a74dacffd35c7bb09b3a1328" dependencies = [ "unicode-ident", ] @@ -2022,9 +2252,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.26" +version = "1.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" +checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" dependencies = [ "proc-macro2", ] @@ -2042,9 +2272,9 @@ dependencies = [ [[package]] name = "r2d2_mysql" -version = "23.0.0" +version = "24.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9733d738ce65959a744f387bae69aa690a867e18d48e5486b171c47bc7b0c575" +checksum = "3fe5127e6c21971cdb9580f2f54cbe6d9c2226eb861036c3ca6d390c25f52574" dependencies = [ "mysql", "r2d2", @@ -2052,12 +2282,13 @@ dependencies = [ [[package]] name = "r2d2_sqlite" -version = "0.21.0" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4f5d0337e99cd5cacd91ffc326c6cc9d8078def459df560c4f9bf9ba4a51034" +checksum = "99f31323d6161385f385046738df520e0e8694fa74852d35891fc0be08348ddc" dependencies = [ "r2d2", "rusqlite", + "uuid", ] [[package]] @@ -2097,12 +2328,25 @@ dependencies = [ ] [[package]] -name = "redox_syscall" -version = "0.2.16" +name = "rayon" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" dependencies = [ - "bitflags", + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", ] [[package]] @@ -2111,14 +2355,26 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ - "bitflags", + "bitflags 1.3.2", ] [[package]] name = "regex" -version = "1.7.3" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b1f693b24f6ac912f4893ef08244d70b6067480d2f1a46e950c9691e6749d1d" +checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795" dependencies = [ "aho-corasick", "memchr", @@ -2127,9 +2383,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.6.29" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" +checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" [[package]] name = "rend" @@ -2142,11 +2398,11 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.11.16" +version = "0.11.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b71749df584b7f4cac2c426c127a7c785a5106cc98f7a8feb044115f0fa254" +checksum = "3e9ad3fe7488d7e34558a2033d45a0c90b72d97b4f80705666fea71472e2e6a1" dependencies = [ - "base64 0.21.0", + "base64 0.21.4", "bytes", "encoding_rs", "futures-core", @@ -2194,23 +2450,26 @@ dependencies = [ [[package]] name = "rkyv" -version = "0.7.41" +version = "0.7.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21499ed91807f07ae081880aabb2ccc0235e9d88011867d984525e9a4c3cfa3e" +checksum = "0200c8230b013893c0b2d6213d6ec64ed2b9be2e0e016682b7224ff82cff5c58" dependencies = [ + "bitvec", "bytecheck", "hashbrown 0.12.3", "ptr_meta", "rend", "rkyv_derive", "seahash", + "tinyvec", + "uuid", ] [[package]] name = "rkyv_derive" -version = "0.7.41" +version = "0.7.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac1c672430eb41556291981f45ca900a0239ad007242d1cb4b4167af842db666" +checksum = "b2e06b915b5c230a17d7a736d1e2e63ee753c256a8614ef3f5147b13a4f5541d" dependencies = [ "proc-macro2", "quote", @@ -2224,17 +2483,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "88073939a61e5b7680558e6be56b419e208420c2adb92be54921fa6b72283f1a" dependencies = [ "base64 0.13.1", - "bitflags", + "bitflags 1.3.2", "serde", ] [[package]] name = "rusqlite" -version = "0.28.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01e213bc3ecb39ac32e81e51ebe31fd888a940515173e3a18a35f8c6e896422a" +checksum = "549b9d036d571d42e6e85d1c1425e2ac83491075078ca9a15be021c56b1641f2" dependencies = [ - "bitflags", + "bitflags 2.4.0", "fallible-iterator", "fallible-streaming-iterator", "hashlink", @@ -2254,14 +2513,12 @@ dependencies = [ [[package]] name = "rust_decimal" -version = "1.29.1" +version = "1.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26bd36b60561ee1fb5ec2817f198b6fd09fa571c897a5e86d1487cfc2b096dfc" +checksum = "a4c4216490d5a413bc6d10fa4742bd7d4955941d062c0ef873141d6b0e7b30fd" dependencies = [ "arrayvec", "borsh", - "bytecheck", - "byteorder", "bytes", "num-traits", "rand", @@ -2272,9 +2529,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4a36c42d1873f9a77c53bde094f9664d9891bc604a45b4798fd2c389ed12e5b" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" [[package]] name = "rustc-hash" @@ -2293,50 +2550,68 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.11" +version = "0.38.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85597d61f83914ddeba6a47b3b8ffe7365107221c2e557ed94426489fefb5f77" +checksum = "d7db8590df6dfcd144d22afd1b83b36c21a18d7cbc1dc4bb5295a8712e9eb662" dependencies = [ - "bitflags", + "bitflags 2.4.0", "errno", - "io-lifetimes", "libc", "linux-raw-sys", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] name = "rustls" -version = "0.20.8" +version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f" +checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8" dependencies = [ "log", "ring", + "rustls-webpki", "sct", - "webpki", ] [[package]] name = "rustls-pemfile" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b" +checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" dependencies = [ - "base64 0.21.0", + "base64 0.21.4", +] + +[[package]] +name = "rustls-webpki" +version = "0.101.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45a27e3b59326c16e23d30aeb7a36a24cc0d29e71d68ff611cdfb4a01d013bed" +dependencies = [ + "ring", + "untrusted", ] [[package]] name = "rustversion" -version = "1.0.12" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ryu" -version = "1.0.13" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" +checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] [[package]] name = "saturating" @@ -2346,11 +2621,11 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.21" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" dependencies = [ - "windows-sys 0.42.0", + "windows-sys", ] [[package]] @@ -2364,15 +2639,9 @@ dependencies = [ [[package]] name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "scratch" -version = "1.0.5" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sct" @@ -2392,11 +2661,11 @@ checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" [[package]] name = "security-framework" -version = "2.8.2" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a332be01508d814fed64bf28f798a146d73792121129962fdf335bb3c49a4254" +checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" dependencies = [ - "bitflags", + "bitflags 1.3.2", "core-foundation", "core-foundation-sys", "libc", @@ -2405,9 +2674,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.8.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c9bb296072e961fcbd8853511dd39c2d8be2deb1e17c6860b1d30732b323b4" +checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" dependencies = [ "core-foundation-sys", "libc", @@ -2415,15 +2684,15 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" +checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" [[package]] name = "serde" -version = "1.0.160" +version = "1.0.188" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb2f3770c8bce3bcda7e149193a069a0f4365bda1fa5cd88e03bca26afc1216c" +checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" dependencies = [ "serde_derive", ] @@ -2440,29 +2709,29 @@ dependencies = [ [[package]] name = "serde_bytes" -version = "0.11.9" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "416bda436f9aab92e02c8e10d49a15ddd339cea90b6e340fe51ed97abb548294" +checksum = "ab33ec92f677585af6d88c65593ae2375adde54efdbf16d597f2cbc7a6d368ff" dependencies = [ "serde", ] [[package]] name = "serde_derive" -version = "1.0.160" +version = "1.0.188" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291a097c63d8497e00160b166a967a4a79c64f3facdd01cbd7502231688d77df" +checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] name = "serde_json" -version = "1.0.96" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" +checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65" dependencies = [ "itoa", "ryu", @@ -2471,29 +2740,30 @@ dependencies = [ [[package]] name = "serde_path_to_error" -version = "0.1.11" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7f05c1d5476066defcdfacce1f52fc3cae3af1d3089727100c02ae92e5abbe0" +checksum = "4beec8bce849d58d06238cb50db2e1c417cfeafa4c63f692b15c82b7c80f8335" dependencies = [ + "itoa", "serde", ] [[package]] name = "serde_repr" -version = "0.1.12" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" +checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] name = "serde_spanned" -version = "0.6.1" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4" +checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186" dependencies = [ "serde", ] @@ -2512,30 +2782,31 @@ dependencies = [ [[package]] name = "serde_with" -version = "2.3.2" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "331bb8c3bf9b92457ab7abecf07078c13f7d270ba490103e84e8b014490cd0b0" +checksum = "1ca3b16a3d82c4088f343b7480a93550b3eabe1a358569c2dfe38bbcead07237" dependencies = [ - "base64 0.13.1", + "base64 0.21.4", "chrono", "hex", - "indexmap", + "indexmap 1.9.3", + "indexmap 2.0.0", "serde", "serde_json", "serde_with_macros", - "time 0.3.20", + "time", ] [[package]] name = "serde_with_macros" -version = "2.3.2" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859011bddcc11f289f07f467cc1fe01c7a941daa4d8f6c40d4d1c92eb6d9319c" +checksum = "2e6be15c453eb305019bfa438b1593c731f36a289a7853f7707ee29e870b3b3c" dependencies = [ "darling", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.35", ] [[package]] @@ -2551,9 +2822,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" +checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" dependencies = [ "cfg-if", "cpufeatures", @@ -2562,9 +2833,9 @@ dependencies = [ [[package]] name = "shlex" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43b2853a4d09f215c24cc5489c992ce46052d359b5109343cbafbf26bc62f8a3" +checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" [[package]] name = "signal-hook-registry" @@ -2583,18 +2854,18 @@ checksum = "f27f6278552951f1f2b8cf9da965d10969b2efdea95a6ec47987ab46edfe263a" [[package]] name = "slab" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" dependencies = [ "autocfg", ] [[package]] name = "smallvec" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" +checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9" [[package]] name = "socket2" @@ -2606,6 +2877,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "socket2" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4031e820eb552adee9295814c0ced9e5cf38ddf1e8b7d566d6de8e2538ea989e" +dependencies = [ + "libc", + "windows-sys", +] + [[package]] name = "spin" version = "0.5.2" @@ -2647,9 +2928,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.14" +version = "2.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcf316d5356ed6847742d036f8a39c3b8435cac10bd528a4bd461928a6ab34d5" +checksum = "59bf04c28bee9043ed9ea1e41afc0552288d3aba9c6efdd78903b802926f4879" dependencies = [ "proc-macro2", "quote", @@ -2670,15 +2951,15 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "tempfile" -version = "3.5.0" +version = "3.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9fbec84f381d5795b08656e4912bec604d162bff9291d6189a78f4c8ab87998" +checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef" dependencies = [ "cfg-if", "fastrand", - "redox_syscall 0.3.5", + "redox_syscall", "rustix", - "windows-sys 0.45.0", + "windows-sys", ] [[package]] @@ -2698,41 +2979,31 @@ checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" -version = "1.0.40" +version = "1.0.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" +checksum = "9d6d7a740b8a666a7e828dd00da9c0dc290dff53154ea77ac109281de90589b7" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.40" +version = "1.0.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" +checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] name = "time" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" -dependencies = [ - "libc", - "wasi 0.10.0+wasi-snapshot-preview1", - "winapi", -] - -[[package]] -name = "time" -version = "0.3.20" +version = "0.3.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890" +checksum = "17f6bb557fd245c28e6411aa56b6403c689ad95061f50e4be16c274e70a17e48" dependencies = [ + "deranged", "itoa", "serde", "time-core", @@ -2741,19 +3012,29 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" +checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" [[package]] name = "time-macros" -version = "0.2.8" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd80a657e71da814b8e5d60d3374fc6d35045062245d80224748ae522dd76f36" +checksum = "1a942f44339478ef67935ab2bbaec2fb0322496cf3cbe84b261e06ac3814c572" dependencies = [ "time-core", ] +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "tinyvec" version = "1.6.0" @@ -2771,31 +3052,31 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.27.0" +version = "1.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0de47a4eecbe11f498978a9b29d792f0d2692d1dd003650c24c76510e3bc001" +checksum = "17ed6077ed6cd6c74735e21f37eb16dc3935f96878b1fe961074089cc80893f9" dependencies = [ - "autocfg", + "backtrace", "bytes", "libc", "mio", "num_cpus", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.5.4", "tokio-macros", - "windows-sys 0.45.0", + "windows-sys", ] [[package]] name = "tokio-macros" -version = "2.0.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61a573bdc87985e9d6ddeed1b3d864e8a302c847e40d647746df2f1de209d1ce" +checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.14", + "syn 2.0.35", ] [[package]] @@ -2810,20 +3091,19 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.23.4" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ "rustls", "tokio", - "webpki", ] [[package]] name = "tokio-util" -version = "0.7.7" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5427d89453009325de0d8f342c9490009f76e999cb7672d77e46267448f7e6b2" +checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d" dependencies = [ "bytes", "futures-core", @@ -2844,32 +3124,43 @@ dependencies = [ [[package]] name = "toml" -version = "0.7.3" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b403acf6f2bb0859c93c7f0d967cb4a75a7ac552100f9322faf64dc047669b21" +checksum = "c226a7bba6d859b63c92c4b4fe69c5b6b72d0cb897dbc8e6012298e6154cb56e" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit", + "toml_edit 0.20.0", ] [[package]] name = "toml_datetime" -version = "0.6.1" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.19.8" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap 2.0.0", + "toml_datetime", + "winnow", +] + +[[package]] +name = "toml_edit" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "239410c8609e8125456927e6707163a3b1fdb40561e4b803bc041f466ccfdc13" +checksum = "8ff63e60a958cefbb518ae1fd6566af80d9d4be430a33f3723dfc47d1d411d95" dependencies = [ - "indexmap", + "indexmap 2.0.0", "serde", "serde_spanned", "toml_datetime", @@ -2878,7 +3169,7 @@ dependencies = [ [[package]] name = "torrust-tracker" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.10" dependencies = [ "aquatic_udp_protocol", "async-trait", @@ -2886,7 +3177,6 @@ dependencies = [ "axum-client-ip", "axum-server", "binascii", - "bip_bencode", "chrono", "config", "derive_more", @@ -2915,30 +3205,40 @@ dependencies = [ "thiserror", "tokio", "torrust-tracker-configuration", + "torrust-tracker-contrib-bencode", "torrust-tracker-located-error", "torrust-tracker-primitives", "torrust-tracker-test-helpers", + "tower-http", "uuid", ] [[package]] name = "torrust-tracker-configuration" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.10" dependencies = [ "config", "log", "serde", "serde_with", "thiserror", - "toml 0.7.3", + "toml 0.8.0", "torrust-tracker-located-error", "torrust-tracker-primitives", "uuid", ] +[[package]] +name = "torrust-tracker-contrib-bencode" +version = "3.0.0-alpha.10" +dependencies = [ + "criterion", + "error-chain", +] + [[package]] name = "torrust-tracker-located-error" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.10" dependencies = [ "log", "thiserror", @@ -2946,7 +3246,7 @@ dependencies = [ [[package]] name = "torrust-tracker-primitives" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.10" dependencies = [ "derive_more", "serde", @@ -2954,7 +3254,7 @@ dependencies = [ [[package]] name = "torrust-tracker-test-helpers" -version = "3.0.0-alpha.2" +version = "3.0.0-alpha.10" dependencies = [ "lazy_static", "rand", @@ -2978,6 +3278,27 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower-http" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" +dependencies = [ + "async-compression", + "bitflags 2.4.0", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-range-header", + "pin-project-lite", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", +] + [[package]] name = "tower-layer" version = "0.3.2" @@ -3004,9 +3325,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.30" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" dependencies = [ "once_cell", ] @@ -3030,15 +3351,15 @@ dependencies = [ [[package]] name = "typenum" -version = "1.16.0" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" [[package]] name = "ucd-trie" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" +checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" [[package]] name = "unicode-bidi" @@ -3048,9 +3369,9 @@ checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" [[package]] name = "unicode-ident" -version = "1.0.8" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-normalization" @@ -3061,12 +3382,6 @@ dependencies = [ "tinyvec", ] -[[package]] -name = "unicode-width" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" - [[package]] name = "untrusted" version = "0.7.1" @@ -3075,9 +3390,9 @@ checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" [[package]] name = "url" -version = "2.3.1" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" +checksum = "143b538f18257fac9cad154828a57c6bf5157e1aa604d4816b5995bf6de87ae5" dependencies = [ "form_urlencoded", "idna", @@ -3086,11 +3401,12 @@ dependencies = [ [[package]] name = "uuid" -version = "1.3.1" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b55a3fef2a1e3b3a00ce878640918820d3c51081576ac657d23af9fc7928fdb" +checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d" dependencies = [ "getrandom", + "rand", ] [[package]] @@ -3106,20 +3422,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] -name = "want" -version = "0.3.0" +name = "walkdir" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee" dependencies = [ - "log", - "try-lock", + "same-file", + "winapi-util", ] [[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" +name = "want" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] [[package]] name = "wasi" @@ -3129,9 +3448,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31f8dcbc21f30d9b8f2ea926ecb58f6b91192c17e9d33594b3df58b2007ca53b" +checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -3139,24 +3458,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95ce90fd5bcc06af55a641a86428ee4229e44e07033963a2290a8e241607ccb9" +checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.35", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.34" +version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f219e0d211ba40266969f6dbdd90636da12f75bee4fc9d6c23d1260dadb51454" +checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" dependencies = [ "cfg-if", "js-sys", @@ -3166,9 +3485,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c21f77c0bedc37fd5dc21f897894a5ca01e7bb159884559461862ae90c0b4c5" +checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3176,43 +3495,33 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6" +checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.35", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.84" +version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d" +checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" [[package]] name = "web-sys" -version = "0.3.61" +version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33b99f4b23ba3eec1a53ac264e35a755f00e966e0065077d6027c0f575b0b97" +checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" dependencies = [ "js-sys", "wasm-bindgen", ] -[[package]] -name = "webpki" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" -dependencies = [ - "ring", - "untrusted", -] - [[package]] name = "winapi" version = "0.3.9" @@ -3250,31 +3559,7 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" dependencies = [ - "windows-targets 0.48.0", -] - -[[package]] -name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", + "windows-targets", ] [[package]] @@ -3283,139 +3568,83 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets 0.48.0", + "windows-targets", ] [[package]] name = "windows-targets" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[package]] -name = "windows-targets" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" -dependencies = [ - "windows_aarch64_gnullvm 0.48.0", - "windows_aarch64_msvc 0.48.0", - "windows_i686_gnu 0.48.0", - "windows_i686_msvc 0.48.0", - "windows_x86_64_gnu 0.48.0", - "windows_x86_64_gnullvm 0.48.0", - "windows_x86_64_msvc 0.48.0", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - [[package]] name = "windows_aarch64_gnullvm" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_msvc" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" - -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_i686_gnu" -version = "0.48.0" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_msvc" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_x86_64_gnu" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnullvm" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_msvc" -version = "0.48.0" +version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "winnow" -version = "0.4.1" +version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae8970b36c66498d8ff1d66685dc86b91b29db0c7739899012f63a63814b4b28" +checksum = "7c2e3184b9c4e92ad5167ca73039d0c42476302ab603e2fec4487511f38ccefc" dependencies = [ "memchr", ] [[package]] name = "winreg" -version = "0.10.1" +version = "0.50.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" dependencies = [ - "winapi", + "cfg-if", + "windows-sys", ] [[package]] @@ -3435,3 +3664,33 @@ checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" dependencies = [ "linked-hash-map", ] + +[[package]] +name = "zstd" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a27595e173641171fc74a1232b7b1c7a7cb6e18222c11e9dfb9888fa424c53c" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "6.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee98ffd0b48ee95e6c5168188e44a54550b1564d9d530ee21d5f0eaed1069581" +dependencies = [ + "libc", + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.8+zstd.1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5556e6ee25d32df2586c098bbfa278803692a20d0ab9565e049480d52707ec8c" +dependencies = [ + "cc", + "libc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml index 51c191275..abd293190 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,74 +1,86 @@ [package] name = "torrust-tracker" -description = "A feature rich BitTorrent tracker." -license = "AGPL-3.0" +readme = "README.md" + authors.workspace = true +description.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +keywords.workspace = true +license-file.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true version.workspace = true [workspace.package] authors = ["Nautilus Cyberneering , Mick van Dijke "] +categories = ["network-programming", "web-programming"] +description = "A feature rich BitTorrent tracker." +documentation = "https://docs.rs/crate/torrust-tracker/" edition = "2021" +homepage = "https://torrust.com/" +keywords = ["bittorrent", "file-sharing", "peer-to-peer", "torrent", "tracker"] +license-file = "COPYRIGHT" +publish = true repository = "https://github.com/torrust/torrust-tracker" -version = "3.0.0-alpha.2" +rust-version = "1.72" +version = "3.0.0-alpha.10" [dependencies] -tokio = { version = "1.26", features = ["rt-multi-thread", "net", "sync", "macros", "signal"] } -serde = { version = "1.0", features = ["derive"] } -serde_bencode = "^0.2" -serde_json = "1.0" -serde_with = "2.0" -percent-encoding = "2.2" +aquatic_udp_protocol = "0.8" +async-trait = "0.1" +axum = "0.6" +axum-client-ip = "0.4" +axum-server = { version = "0.5", features = ["tls-rustls"] } binascii = "0.1" -lazy_static = "1.4" -openssl = { version = "0.10", features = ["vendored"] } +chrono = { version = "0.4", default-features = false, features = ["clock"] } config = "0.13" -log = { version = "0.4", features = ["release_max_level_info"] } +derive_more = "0.99" fern = "0.6" -chrono = "0.4" +futures = "0.3" +hyper = "0.14" +lazy_static = "1.4" +log = { version = "0.4", features = ["release_max_level_info"] } +multimap = "0.9" +openssl = { version = "0.10", features = ["vendored"] } +percent-encoding = "2.2" r2d2 = "0.8" -r2d2_mysql = "23.0" -r2d2_sqlite = { version = "0.21", features = ["bundled"] } +r2d2_mysql = "24.0" +r2d2_sqlite = { version = "0.22", features = ["bundled"] } rand = "0.8" -derive_more = "0.99" +serde = { version = "1.0", features = ["derive"] } +serde_bencode = "^0.2" +serde_json = "1.0" +serde_with = "3.2" thiserror = "1.0" -futures = "0.3" -async-trait = "0.1" -aquatic_udp_protocol = "0.8" +tokio = { version = "1.29", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] } +torrust-tracker-configuration = { version = "3.0.0-alpha.10", path = "packages/configuration" } +torrust-tracker-contrib-bencode = { version = "3.0.0-alpha.10", path = "contrib/bencode" } +torrust-tracker-located-error = { version = "3.0.0-alpha.10", path = "packages/located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.10", path = "packages/primitives" } +tower-http = { version = "0.4", features = ["compression-full"] } uuid = { version = "1", features = ["v4"] } -axum = "0.6.10" -axum-server = { version = "0.4", features = ["tls-rustls"] } -axum-client-ip = "0.4" -bip_bencode = "0.4" -torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "packages/primitives" } -torrust-tracker-configuration = { version = "3.0.0-alpha.2", path = "packages/configuration" } -torrust-tracker-located-error = { version = "3.0.0-alpha.2", path = "packages/located-error" } -multimap = "0.9" -hyper = "0.14" [dev-dependencies] +local-ip-address = "0.5" mockall = "0.11" -reqwest = { version = "0.11", features = ["json"] } -serde_urlencoded = "0.7" -serde_repr = "0.1" +reqwest = { version = "0.11.18", features = ["json"] } serde_bytes = "0.11" -local-ip-address = "0.5" -torrust-tracker-test-helpers = { version = "3.0.0-alpha.2", path = "packages/test-helpers" } +serde_repr = "0.1" +serde_urlencoded = "0.7" +torrust-tracker-test-helpers = { version = "3.0.0-alpha.10", path = "packages/test-helpers" } [workspace] -members = [ - "packages/configuration", - "packages/primitives", - "packages/test-helpers", - "packages/located-error", -] +members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers"] [profile.dev] debug = 1 -opt-level = 1 lto = "thin" +opt-level = 1 [profile.release] debug = 1 -opt-level = 3 lto = "fat" +opt-level = 3 diff --git a/Containerfile b/Containerfile new file mode 100644 index 000000000..be71017db --- /dev/null +++ b/Containerfile @@ -0,0 +1,140 @@ +# syntax=docker/dockerfile:latest + +# Torrust Tracker + +## Builder Image +FROM rust:bookworm as chef +WORKDIR /tmp +RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash +RUN cargo binstall --no-confirm cargo-chef cargo-nextest + +## Tester Image +FROM rust:slim-bookworm as tester +WORKDIR /tmp + +RUN apt-get update; apt-get install -y curl sqlite3; apt-get autoclean +RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash +RUN cargo binstall --no-confirm cargo-nextest + +COPY ./share/ /app/share/torrust +RUN mkdir -p /app/share/torrust/default/database/; \ + sqlite3 /app/share/torrust/default/database/tracker.sqlite3.db "VACUUM;" + +## Su Exe Compile +FROM docker.io/library/gcc:bookworm as gcc +COPY ./contrib/dev-tools/su-exec/ /usr/local/src/su-exec/ +RUN cc -Wall -Werror -g /usr/local/src/su-exec/su-exec.c -o /usr/local/bin/su-exec; chmod +x /usr/local/bin/su-exec + + +## Chef Prepare (look at project and see wat we need) +FROM chef AS recipe +WORKDIR /build/src +COPY . /build/src +RUN cargo chef prepare --recipe-path /build/recipe.json + + +## Cook (debug) +FROM chef AS dependencies_debug +WORKDIR /build/src +COPY --from=recipe /build/recipe.json /build/recipe.json +RUN cargo chef cook --tests --benches --examples --workspace --all-targets --all-features --recipe-path /build/recipe.json +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/temp.tar.zst ; rm -f /build/temp.tar.zst + +## Cook (release) +FROM chef AS dependencies +WORKDIR /build/src +COPY --from=recipe /build/recipe.json /build/recipe.json +RUN cargo chef cook --tests --benches --examples --workspace --all-targets --all-features --recipe-path /build/recipe.json --release +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/temp.tar.zst --release ; rm -f /build/temp.tar.zst + + +## Build Archive (debug) +FROM dependencies_debug AS build_debug +WORKDIR /build/src +COPY . /build/src +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-tracker-debug.tar.zst + +## Build Archive (release) +FROM dependencies AS build +WORKDIR /build/src +COPY . /build/src +RUN cargo nextest archive --tests --benches --examples --workspace --all-targets --all-features --archive-file /build/torrust-tracker.tar.zst --release + + +# Extract and Test (debug) +FROM tester as test_debug +WORKDIR /test +COPY . /test/src/ +COPY --from=build_debug \ + /build/torrust-tracker-debug.tar.zst \ + /test/torrust-tracker-debug.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-tracker-debug.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --target-dir-remap /test/src/target/ --cargo-metadata /test/src/target/nextest/cargo-metadata.json --binaries-metadata /test/src/target/nextest/binaries-metadata.json + +RUN mkdir -p /app/bin/; cp -l /test/src/target/debug/torrust-tracker /app/bin/torrust-tracker +RUN mkdir /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 +RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin + +# Extract and Test (release) +FROM tester as test +WORKDIR /test +COPY . /test/src +COPY --from=build \ + /build/torrust-tracker.tar.zst \ + /test/torrust-tracker.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --extract-to /test/src/ --no-run --archive-file /test/torrust-tracker.tar.zst +RUN cargo nextest run --workspace-remap /test/src/ --target-dir-remap /test/src/target/ --cargo-metadata /test/src/target/nextest/cargo-metadata.json --binaries-metadata /test/src/target/nextest/binaries-metadata.json + +RUN mkdir -p /app/bin/; cp -l /test/src/target/release/torrust-tracker /app/bin/torrust-tracker +RUN mkdir -p /app/lib/; cp -l $(realpath $(ldd /app/bin/torrust-tracker | grep "libz\.so\.1" | awk '{print $3}')) /app/lib/libz.so.1 +RUN chown -R root:root /app; chmod -R u=rw,go=r,a+X /app; chmod -R a+x /app/bin + + +## Runtime +FROM gcr.io/distroless/cc-debian12:debug as runtime +RUN ["/busybox/cp", "-sp", "/busybox/sh","/busybox/cat","/busybox/ls","/busybox/env", "/bin/"] +COPY --from=gcc --chmod=0555 /usr/local/bin/su-exec /bin/su-exec + +ARG TORRUST_TRACKER_PATH_CONFIG="/etc/torrust/tracker/tracker.toml" +ARG TORRUST_TRACKER_DATABASE_DRIVER="sqlite3" +ARG USER_ID=1000 +ARG UDP_PORT=6969 +ARG HTTP_PORT=7070 +ARG API_PORT=1212 + +ENV TORRUST_TRACKER_PATH_CONFIG=${TORRUST_TRACKER_PATH_CONFIG} +ENV TORRUST_TRACKER_DATABASE_DRIVER=${TORRUST_TRACKER_DATABASE_DRIVER} +ENV USER_ID=${USER_ID} +ENV UDP_PORT=${UDP_PORT} +ENV HTTP_PORT=${HTTP_PORT} +ENV API_PORT=${API_PORT} +ENV TZ=Etc/UTC + +EXPOSE ${UDP_PORT}/udp +EXPOSE ${HTTP_PORT}/tcp +EXPOSE ${API_PORT}/tcp + +RUN mkdir -p /var/lib/torrust/tracker /var/log/torrust/tracker /etc/torrust/tracker + +ENV ENV=/etc/profile +COPY --chmod=0555 ./share/container/entry_script_sh /usr/local/bin/entry.sh + +VOLUME ["/var/lib/torrust/tracker","/var/log/torrust/tracker","/etc/torrust/tracker"] + +ENV RUNTIME="runtime" +ENTRYPOINT ["/usr/local/bin/entry.sh"] + + +## Torrust-Tracker (debug) +FROM runtime as debug +ENV RUNTIME="debug" +COPY --from=test_debug /app/ /usr/ +RUN env +CMD ["sh"] + +## Torrust-Tracker (release) (default) +FROM runtime as release +ENV RUNTIME="release" +COPY --from=test /app/ /usr/ +# HEALTHCHECK CMD ["/usr/bin/wget", "--no-verbose", "--tries=1", "--spider", "localhost:${API_PORT}/version"] +CMD ["/usr/bin/torrust-tracker"] diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 96d21fa84..000000000 --- a/Dockerfile +++ /dev/null @@ -1,80 +0,0 @@ -FROM clux/muslrust:stable AS chef -WORKDIR /app -RUN cargo install cargo-chef - - -FROM chef AS planner -WORKDIR /app -COPY . . -RUN cargo chef prepare --recipe-path recipe.json - - -FROM chef as development -WORKDIR /app -ARG UID=1000 -ARG RUN_AS_USER=appuser -ARG TRACKER_UDP_PORT=6969 -ARG TRACKER_HTTP_PORT=7070 -ARG TRACKER_API_PORT=1212 -# Add the app user for development -ENV USER=appuser -ENV UID=$UID -RUN adduser --uid "${UID}" "${USER}" -# Build dependencies -COPY --from=planner /app/recipe.json recipe.json -RUN cargo chef cook --recipe-path recipe.json -# Build the application -COPY . . -RUN cargo build --bin torrust-tracker -USER $RUN_AS_USER:$RUN_AS_USER -EXPOSE $TRACKER_UDP_PORT/udp -EXPOSE $TRACKER_HTTP_PORT/tcp -EXPOSE $TRACKER_API_PORT/tcp -CMD ["cargo", "run"] - - -FROM chef AS builder -WORKDIR /app -ARG UID=1000 -# Add the app user for production -ENV USER=appuser -ENV UID=$UID -RUN adduser \ - --disabled-password \ - --gecos "" \ - --home "/nonexistent" \ - --shell "/sbin/nologin" \ - --no-create-home \ - --uid "${UID}" \ - "${USER}" -# Build dependencies -COPY --from=planner /app/recipe.json recipe.json -RUN cargo chef cook --release --target x86_64-unknown-linux-musl --recipe-path recipe.json -# Build the application -COPY . . -RUN cargo build --release --target x86_64-unknown-linux-musl --bin torrust-tracker -# Strip the binary -# More info: https://github.com/LukeMathWalker/cargo-chef/issues/149 -RUN strip /app/target/x86_64-unknown-linux-musl/release/torrust-tracker - - -FROM alpine:latest -WORKDIR /app -ARG RUN_AS_USER=appuser -ARG TRACKER_UDP_PORT=6969 -ARG TRACKER_HTTP_PORT=7070 -ARG TRACKER_API_PORT=1212 -RUN apk --no-cache add ca-certificates -ENV TZ=Etc/UTC -ENV RUN_AS_USER=$RUN_AS_USER -COPY --from=builder /etc/passwd /etc/passwd -COPY --from=builder /etc/group /etc/group -COPY --from=builder --chown=$RUN_AS_USER \ - /app/target/x86_64-unknown-linux-musl/release/torrust-tracker \ - /app/torrust-tracker -RUN chown -R $RUN_AS_USER:$RUN_AS_USER /app -USER $RUN_AS_USER:$RUN_AS_USER -EXPOSE $TRACKER_UDP_PORT/udp -EXPOSE $TRACKER_HTTP_PORT/tcp -EXPOSE $TRACKER_API_PORT/tcp -ENTRYPOINT ["/app/torrust-tracker"] \ No newline at end of file diff --git a/LICENSE-AGPL_3_0 b/LICENSE-AGPL_3_0 new file mode 100644 index 000000000..2beb9e163 --- /dev/null +++ b/LICENSE-AGPL_3_0 @@ -0,0 +1,662 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. + diff --git a/LICENSE-MIT_0 b/LICENSE-MIT_0 new file mode 100644 index 000000000..fc06cc4fe --- /dev/null +++ b/LICENSE-MIT_0 @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index c3d0a127b..ac6a05492 100644 --- a/README.md +++ b/README.md @@ -1,82 +1,197 @@ # Torrust Tracker -[![Build & Release](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/build_release.yml) [![CI](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_build_release.yml) [![Publish crate](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_crate.yml) [![Publish docker image](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/publish_docker_image.yml) [![Test](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test.yml) [![Test docker build](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/test_docker.yml) [![Upload code coverage](https://github.com/torrust/torrust-tracker/actions/workflows/codecov.yml/badge.svg)](https://github.com/torrust/torrust-tracker/actions/workflows/codecov.yml) +[![container_wf_b]][container_wf] [![coverage_wf_b]][coverage_wf] [![deployment_wf_b]][deployment_wf] [![testing_wf_b]][testing_wf] -Torrust Tracker is a lightweight but incredibly high-performance and feature-rich BitTorrent tracker written in [Rust](https://www.rust-lang.org/). +__Torrust Tracker__, is a [BitTorrent][bittorrent] Tracker (a service that matchmakes peers and collects statistics) written in [Rust Language][rust] and [axum] (a modern web application framework). ___This tracker aims to be respectful to established standards, (both [formal][BEP 00] and [otherwise][torrent_source_felid]).___ -It aims to provide a reliable and efficient solution for serving torrents to a vast number of peers while maintaining a high level of performance, robustness, extensibility, security, usability and with community-driven development. +> This is a [Torrust][torrust] project and is in active development. It is community supported as well as sponsored by [Nautilus Cyberneering][nautilus]. + +- _We have a [container guide][containers.md] for those who wish to get started with __Docker__ or __Podman___ ## Key Features -* [X] Multiple UDP server and HTTP(S) server blocks for socket binding are possible. -* [X] Full IPv4 and IPv6 support for both UDP and HTTP(S). -* [X] Private & Whitelisted mode. -* [X] Built-in API. -* [X] Torrent whitelisting. -* [X] Peer authentication using time-bound keys. -* [X] [newTrackon](https://newtrackon.com/) check is supported for both HTTP and UDP, where IPv4 and IPv6 are properly handled. -* [X] SQLite3 and MySQL persistence, loading and saving of the torrent hashes and downloads completed count. -* [X] Comprehensive documentation. -* [X] A complete suite of tests. See [code coverage](https://app.codecov.io/gh/torrust/torrust-tracker) report. - -## Implemented BEPs - -* [BEP 3](https://www.bittorrent.org/beps/bep_0003.html): The BitTorrent Protocol. -* [BEP 7](https://www.bittorrent.org/beps/bep_0007.html): IPv6 Support. -* [BEP 15](http://www.bittorrent.org/beps/bep_0015.html): UDP Tracker Protocol for BitTorrent. -* [BEP 23](http://bittorrent.org/beps/bep_0023.html): Tracker Returns Compact Peer Lists. -* [BEP 27](http://bittorrent.org/beps/bep_0027.html): Private Torrents. -* [BEP 48](http://bittorrent.org/beps/bep_0048.html): Tracker Protocol Extension: Scrape. +- [x] High Quality and Modern Rust Codebase. +- [x] [Documentation] Generated from Code Comments. +- [x] [Comprehensive Suit][coverage] of Unit and Functional Tests. +- [x] Good Performance in Busy Conditions. +- [x] Support for `UDP`, `HTTP`, and `TLS` Sockets. +- [x] Native `IPv4` and `IPv6` support. +- [x] Private & Whitelisted mode. +- [x] Tracker Management API. +- [x] Support [newTrackon][newtrackon] checks. +- [x] Persistent `SQLite3` or `MySQL` Databases. + +## Implemented BitTorrent Enhancement Proposals (BEPs) +> _[Learn more about BitTorrent Enhancement Proposals][BEP 00]_ + +- [BEP 03] : The BitTorrent Protocol. +- [BEP 07] : IPv6 Support. +- [BEP 15] : UDP Tracker Protocol for BitTorrent. +- [BEP 23] : Tracker Returns Compact Peer Lists. +- [BEP 27] : Private Torrents. +- [BEP 48] : Tracker Protocol Extension: Scrape. + ## Getting Started -Requirements: +### Container Version + +The Torrust Tracker is [deployed to DockerHub][dockerhub_torrust_tracker], you can run a demo immediately with the following commands: + +#### Docker: + +```sh +docker run -it torrust/tracker:develop +``` +> Please read our [container guide][containers.md] for more information. + +#### Podman: + +```sh +podman run -it torrust/tracker:develop +``` +> Please read our [container guide][containers.md] for more information. + +### Development Version + +- Please assure you have the ___[latest stable (or nightly) version of rust][rust]___. +- Please assure that you computer has enough ram. ___Recommended 16GB.___ + +#### Checkout, Test and Run: + +```sh +# Checkout repository into a new folder: +git clone https://github.com/torrust/torrust-tracker.git + +# Change into directory and create a empty database file: +cd torrust-tracker +mkdir -p ./storage/tracker/lib/database/ +touch ./storage/tracker/lib/database/sqlite3.db + +# Check all tests in application: +cargo test --tests --benches --examples --workspace --all-targets --all-features + +# Run the tracker: +cargo run +``` +#### Customization: + +```sh +# Copy the default configuration into the standard location: +mkdir -p ./storage/tracker/etc/ +cp ./share/default/config/tracker.development.sqlite3.toml ./storage/tracker/etc/tracker.toml -* Rust Stable `1.68` -* You might have problems compiling with a machine or docker container with low resources. It has been tested with docker containers with 6 CPUs, 7.5 GM of memory and 2GB of swap. +# Customize the tracker configuration (for example): +vim ./storage/tracker/etc/tracker.toml -You can follow the [documentation](https://docs.rs/torrust-tracker/) to install and use Torrust Tracker in different ways, but if you want to give it a quick try, you can use the following commands: +# Run the tracker with the updated configuration: +TORRUST_TRACKER_PATH_CONFIG="./storage/tracker/etc/tracker.toml" cargo run +``` + +_Optionally, you may choose to supply the entire configuration as an environmental variable:_ + +```sh +# Use a configuration supplied on an environmental variable: +TORRUST_TRACKER_CONFIG=$(cat "./storage/tracker/etc/tracker.toml") cargo run +``` + +_For deployment you __should__ override the `api_admin_token` by using an environmental variable:_ -```s -git clone https://github.com/torrust/torrust-tracker.git \ - && cd torrust-tracker \ - && cargo build --release \ - && mkdir -p ./storage/database \ - && mkdir -p ./storage/ssl_certificates +```sh +# Generate a Secret Token: +gpg --armor --gen-random 1 10 | tee ./storage/tracker/lib/tracker_api_admin_token.secret +chmod go-rwx ./storage/tracker/lib/tracker_api_admin_token.secret + +# Override secret in configuration using an environmental variable: +TORRUST_TRACKER_CONFIG=$(cat "./storage/tracker/etc/tracker.toml") \ + TORRUST_TRACKER_API_ADMIN_TOKEN=$(cat "./storage/tracker/lib/tracker_api_admin_token.secret") \ + cargo run ``` -And then run `cargo run` twice. The first time to generate the `config.toml` file and the second time to run the tracker with the default configuration. +> Please view our [crate documentation][documentation] for more detailed instructions. + +### Services +The following services are provided by the default configuration: -After running the tracker these services will be available: +- UDP _(tracker)_ + - `udp://127.0.0.1:6969/announce`. +- HTTP _(tracker)_ + - `http://127.0.0.1:6969/announce`. +- API _(management)_ + - `http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken`. -* UDP tracker: `udp://127.0.0.1:6969/announce`. -* HTTP tracker: `http://127.0.0.1:6969/announce`. -* API: `http://127.0.0.1:1212/api/v1/stats?token=MyAccessToken`. ## Documentation -* [Crate documentation](https://docs.rs/torrust-tracker/). -* [API `v1`](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/apis/v1). -* [HTTP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/http). -* [UDP Tracker](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/udp). +- [Management API (Version 1)][api] +- [Tracker (HTTP/TLS)][http] +- [Tracker (UDP)][udp] ## Contributing +This is an open-source community supported project.
We welcome contributions from the community! -How can you contribute? +__How can you contribute?__ -* Bug reports and feature requests. -* Code contributions. You can start by looking at the issues labeled ["good first issues"](https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). -* Documentation improvements. Check the [documentation](https://docs.rs/torrust-tracker/) and [API documentation](https://docs.rs/torrust-tracker/3.0.0-alpha.2/torrust_tracker/servers/apis/v1) for typos, errors, or missing information. -* Participation in the community. You can help by answering questions in the [discussions](https://github.com/torrust/torrust-tracker/discussions). +- Bug reports and feature requests. +- Code contributions. You can start by looking at the issues labeled "[good first issues]". +- Documentation improvements. Check the [documentation] and [API documentation] for typos, errors, or missing information. +- Participation in the community. You can help by answering questions in the [discussions]. ## License -The project is licensed under the terms of the [GNU AFFERO GENERAL PUBLIC LICENSE](./LICENSE). - -There is an ongoing discussion about the license of the project. You can follow the discussion [here](https://github.com/torrust/torrust-tracker/pull/251). +The project is licensed under a dual license. See [COPYRIGHT]. ## Acknowledgments -This project was a joint effort by [Nautilus Cyberneering GmbH](https://nautilus-cyberneering.de/) and [Dutch Bits](https://dutchbits.nl). Also thanks to [Naim A.](https://github.com/naim94a/udpt) and [greatest-ape](https://github.com/greatest-ape/aquatic) for some parts of the code. Further added features and functions thanks to [Power2All](https://github.com/power2all). +This project was a joint effort by [Nautilus Cyberneering GmbH][nautilus] and [Dutch Bits]. Also thanks to [Naim A.] and [greatest-ape] for some parts of the code. Further added features and functions thanks to [Power2All]. + + + +[container_wf]: ../../actions/workflows/container.yaml +[container_wf_b]: ../../actions/workflows/container.yaml/badge.svg +[coverage_wf]: ../../actions/workflows/coverage.yaml +[coverage_wf_b]: ../../actions/workflows/coverage.yaml/badge.svg +[deployment_wf]: ../../actions/workflows/deployment.yaml +[deployment_wf_b]: ../../actions/workflows/deployment.yaml/badge.svg +[testing_wf]: ../../actions/workflows/testing.yaml +[testing_wf_b]: ../../actions/workflows/testing.yaml/badge.svg + +[bittorrent]: http://bittorrent.org/ +[rust]: https://www.rust-lang.org/ +[axum]: https://github.com/tokio-rs/axum +[newtrackon]: https://newtrackon.com/ +[coverage]: https://app.codecov.io/gh/torrust/torrust-tracker +[torrust]: https://torrust.com/ + +[dockerhub_torrust_tracker]: https://hub.docker.com/r/torrust/tracker/tags + +[torrent_source_felid]: https://github.com/qbittorrent/qBittorrent/discussions/19406 + +[BEP 00]: https://www.bittorrent.org/beps/bep_0000.html +[BEP 03]: https://www.bittorrent.org/beps/bep_0003.html +[BEP 07]: https://www.bittorrent.org/beps/bep_0007.html +[BEP 15]: https://www.bittorrent.org/beps/bep_0015.html +[BEP 23]: https://www.bittorrent.org/beps/bep_0023.html +[BEP 27]: https://www.bittorrent.org/beps/bep_0027.html +[BEP 48]: https://www.bittorrent.org/beps/bep_0048.html + +[containers.md]: ./docs/containers.md + +[api]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/apis/v1 +[http]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/http +[udp]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/udp + +[good first issues]: https://github.com/torrust/torrust-tracker/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22 +[documentation]: https://docs.rs/torrust-tracker/ +[API documentation]: https://docs.rs/torrust-tracker/3.0.0-alpha.10/torrust_tracker/servers/apis/v1 +[discussions]: https://github.com/torrust/torrust-tracker/discussions + +[COPYRIGHT]: ./COPYRIGHT + +[nautilus]: https://github.com/orgs/Nautilus-Cyberneering/ +[Dutch Bits]: https://dutchbits.nl +[Naim A.]: https://github.com/naim94a/udpt +[greatest-ape]: https://github.com/greatest-ape/aquatic +[Power2All]: https://github.com/power2all diff --git a/bin/install.sh b/bin/install.sh deleted file mode 100755 index d4314ce93..000000000 --- a/bin/install.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -# Generate the default settings file if it does not exist -if ! [ -f "./config.toml" ]; then - cp ./config.toml.local ./config.toml -fi - -# Generate the sqlite database if it does not exist -if ! [ -f "./storage/database/data.db" ]; then - # todo: it should get the path from config.toml and only do it when we use sqlite - touch ./storage/database/data.db - echo ";" | sqlite3 ./storage/database/data.db -fi diff --git a/cSpell.json b/cSpell.json index 2fa80b58a..c9b547c90 100644 --- a/cSpell.json +++ b/cSpell.json @@ -1,7 +1,10 @@ { "words": [ + "adduser", + "alekitto", "appuser", "Arvid", + "autoclean", "AUTOINCREMENT", "automock", "Avicora", @@ -11,6 +14,7 @@ "bencoded", "beps", "binascii", + "binstall", "Bitflu", "bools", "bufs", @@ -21,26 +25,46 @@ "certbot", "chrono", "clippy", + "codecov", + "codegen", "completei", "connectionless", + "Containerfile", + "curr", + "Cyberneering", + "datetime", + "Dijke", + "distroless", "dockerhub", "downloadedi", + "dtolnay", + "elif", "filesd", "Freebox", + "gecos", + "Grcov", "hasher", "hexlify", "hlocalhost", "Hydranode", + "Icelake", + "imdl", "incompletei", "infohash", "infohashes", "infoschema", + "Intermodal", "intervali", + "keyout", "lcov", "leecher", "leechers", + "libsqlite", "libtorrent", + "libz", + "LOGNAME", "Lphant", + "matchmakes", "metainfo", "middlewares", "mockall", @@ -48,16 +72,21 @@ "myacicontext", "Naim", "nanos", + "newkey", "nextest", "nocapture", + "nologin", + "nonroot", "Norberg", "numwant", "oneshot", "ostr", "Pando", "proot", + "proto", "Quickstart", "Rasterbar", + "realpath", "reannounce", "repr", "reqwest", @@ -65,17 +94,23 @@ "rngs", "routable", "rusqlite", + "RUSTDOCFLAGS", + "RUSTFLAGS", "rustfmt", "Rustls", "Seedable", + "serde", "Shareaza", "sharktorrent", + "SHLVL", "socketaddr", "sqllite", "subsec", "Swatinem", "Swiftbit", + "taiki", "thiserror", + "tlsv", "Torrentstorm", "torrust", "torrustracker", @@ -87,11 +122,18 @@ "uroot", "Vagaa", "Vuze", + "Werror", "whitespaces", "XBTT", + "Xeon", "Xtorrent", "Xunlei", "xxxxxxxxxxxxxxxxxxxxd", "yyyyyyyyyyyyyyyyyyyyd" + ], + "enableFiletypes": [ + "dockerfile", + "shellscript", + "toml" ] } diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 000000000..f0878195b --- /dev/null +++ b/codecov.yml @@ -0,0 +1,6 @@ +coverage: + status: + project: + default: + target: auto + threshold: 0.5% diff --git a/compose.yaml b/compose.yaml index 49f3055a8..672ca6d0f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,12 +1,11 @@ name: torrust services: - tracker: - build: - context: . - target: development - user: ${TORRUST_TRACKER_USER_UID:-1000}:${TORRUST_TRACKER_USER_UID:-1000} + image: torrust-tracker:release tty: true + environment: + - TORRUST_TRACKER_DATABASE_DRIVER=${TORRUST_TRACKER_DATABASE_DRIVER:-mysql} + - TORRUST_TRACKER_API_ADMIN_TOKEN=${TORRUST_TRACKER_API_ADMIN_TOKEN:-MyAccessToken} networks: - server_side ports: @@ -14,19 +13,24 @@ services: - 7070:7070 - 1212:1212 volumes: - - ./:/app - - ~/.cargo:/home/appuser/.cargo + - ./storage/tracker/lib:/var/lib/torrust/tracker:Z + - ./storage/tracker/log:/var/log/torrust/tracker:Z + - ./storage/tracker/etc:/etc/torrust/tracker:Z depends_on: - mysql mysql: image: mysql:8.0 - command: '--default-authentication-plugin=mysql_native_password' + command: "--default-authentication-plugin=mysql_native_password" healthcheck: - test: ['CMD-SHELL', 'mysqladmin ping -h 127.0.0.1 --password="$$(cat /run/secrets/db-password)" --silent'] + test: + [ + "CMD-SHELL", + 'mysqladmin ping -h 127.0.0.1 --password="$$(cat /run/secrets/db-password)" --silent', + ] interval: 3s retries: 5 - start_period: 30s + start_period: 30s environment: - MYSQL_ROOT_HOST=% - MYSQL_ROOT_PASSWORD=root_secret_password @@ -44,4 +48,4 @@ networks: server_side: {} volumes: - mysql_data: {} \ No newline at end of file + mysql_data: {} diff --git a/contrib/bencode/Cargo.toml b/contrib/bencode/Cargo.toml new file mode 100644 index 000000000..3918aa6ba --- /dev/null +++ b/contrib/bencode/Cargo.toml @@ -0,0 +1,30 @@ +[package] +description = "(contrib) Efficient decoding and encoding for bencode." +keywords = ["bencode", "contrib", "library"] +name = "torrust-tracker-contrib-bencode" +readme = "README.md" + +authors = ["Nautilus Cyberneering , Andrew "] +license = "Apache-2.0" +repository = "https://github.com/torrust/bittorrent-infrastructure-project" + +documentation.workspace = true +edition.workspace = true +homepage.workspace = true +publish.workspace = true +rust-version.workspace = true +version.workspace = true + +[dependencies] +error-chain = "0.12" + +[dev-dependencies] +criterion = "0.5" + +[[test]] +name = "test" +path = "test/mod.rs" + +[[bench]] +harness = false +name = "bencode_benchmark" diff --git a/contrib/bencode/README.md b/contrib/bencode/README.md new file mode 100644 index 000000000..7a203082b --- /dev/null +++ b/contrib/bencode/README.md @@ -0,0 +1,4 @@ +# Bencode +This library allows for the creation and parsing of bencode encodings. + +Bencode is the binary encoding used throughout bittorrent technologies from metainfo files to DHT messages. Bencode types include integers, byte arrays, lists, and dictionaries, of which the last two can hold any bencode type (they could be recursively constructed). \ No newline at end of file diff --git a/contrib/bencode/benches/bencode_benchmark.rs b/contrib/bencode/benches/bencode_benchmark.rs new file mode 100644 index 000000000..b79bb0999 --- /dev/null +++ b/contrib/bencode/benches/bencode_benchmark.rs @@ -0,0 +1,27 @@ +use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use torrust_tracker_contrib_bencode::{BDecodeOpt, BencodeRef}; + +const B_NESTED_LISTS: &[u8; 100] = + b"lllllllllllllllllllllllllllllllllllllllllllllllllleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; // cspell:disable-line +const MULTI_KB_BENCODE: &[u8; 30004] = include_bytes!("multi_kb.bencode"); + +fn bench_nested_lists(bencode: &[u8]) { + BencodeRef::decode(bencode, BDecodeOpt::new(50, true, true)).unwrap(); +} + +fn bench_multi_kb_bencode(bencode: &[u8]) { + BencodeRef::decode(bencode, BDecodeOpt::default()).unwrap(); +} + +fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("bencode nested lists", |b| { + b.iter(|| bench_nested_lists(black_box(B_NESTED_LISTS))); + }); + + c.bench_function("bencode multi kb", |b| { + b.iter(|| bench_multi_kb_bencode(black_box(MULTI_KB_BENCODE))); + }); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/contrib/bencode/benches/multi_kb.bencode b/contrib/bencode/benches/multi_kb.bencode new file mode 100644 index 000000000..b86f2846e --- /dev/null +++ b/contrib/bencode/benches/multi_kb.bencode @@ -0,0 +1 @@ +d7:comment17:Just Some Comment10:created by12:bip_metainfo13:creation datei1496618058e4:infod5:filesld6:lengthi1024e4:pathl1:b11:small_1.txteed6:lengthi1024e4:pathl1:b12:small_10.txteed6:lengthi1024e4:pathl1:b13:small_100.txteed6:lengthi1024e4:pathl1:b12:small_11.txteed6:lengthi1024e4:pathl1:b12:small_12.txteed6:lengthi1024e4:pathl1:b12:small_13.txteed6:lengthi1024e4:pathl1:b12:small_14.txteed6:lengthi1024e4:pathl1:b12:small_15.txteed6:lengthi1024e4:pathl1:b12:small_16.txteed6:lengthi1024e4:pathl1:b12:small_17.txteed6:lengthi1024e4:pathl1:b12:small_18.txteed6:lengthi1024e4:pathl1:b12:small_19.txteed6:lengthi1024e4:pathl1:b11:small_2.txteed6:lengthi1024e4:pathl1:b12:small_20.txteed6:lengthi1024e4:pathl1:b12:small_21.txteed6:lengthi1024e4:pathl1:b12:small_22.txteed6:lengthi1024e4:pathl1:b12:small_23.txteed6:lengthi1024e4:pathl1:b12:small_24.txteed6:lengthi1024e4:pathl1:b12:small_25.txteed6:lengthi1024e4:pathl1:b12:small_26.txteed6:lengthi1024e4:pathl1:b12:small_27.txteed6:lengthi1024e4:pathl1:b12:small_28.txteed6:lengthi1024e4:pathl1:b12:small_29.txteed6:lengthi1024e4:pathl1:b11:small_3.txteed6:lengthi1024e4:pathl1:b12:small_30.txteed6:lengthi1024e4:pathl1:b12:small_31.txteed6:lengthi1024e4:pathl1:b12:small_32.txteed6:lengthi1024e4:pathl1:b12:small_33.txteed6:lengthi1024e4:pathl1:b12:small_34.txteed6:lengthi1024e4:pathl1:b12:small_35.txteed6:lengthi1024e4:pathl1:b12:small_36.txteed6:lengthi1024e4:pathl1:b12:small_37.txteed6:lengthi1024e4:pathl1:b12:small_38.txteed6:lengthi1024e4:pathl1:b12:small_39.txteed6:lengthi1024e4:pathl1:b11:small_4.txteed6:lengthi1024e4:pathl1:b12:small_40.txteed6:lengthi1024e4:pathl1:b12:small_41.txteed6:lengthi1024e4:pathl1:b12:small_42.txteed6:lengthi1024e4:pathl1:b12:small_43.txteed6:lengthi1024e4:pathl1:b12:small_44.txteed6:lengthi1024e4:pathl1:b12:small_45.txteed6:lengthi1024e4:pathl1:b12:small_46.txteed6:lengthi1024e4:pathl1:b12:small_47.txteed6:lengthi1024e4:pathl1:b12:small_48.txteed6:lengthi1024e4:pathl1:b12:small_49.txteed6:lengthi1024e4:pathl1:b11:small_5.txteed6:lengthi1024e4:pathl1:b12:small_50.txteed6:lengthi1024e4:pathl1:b12:small_51.txteed6:lengthi1024e4:pathl1:b12:small_52.txteed6:lengthi1024e4:pathl1:b12:small_53.txteed6:lengthi1024e4:pathl1:b12:small_54.txteed6:lengthi1024e4:pathl1:b12:small_55.txteed6:lengthi1024e4:pathl1:b12:small_56.txteed6:lengthi1024e4:pathl1:b12:small_57.txteed6:lengthi1024e4:pathl1:b12:small_58.txteed6:lengthi1024e4:pathl1:b12:small_59.txteed6:lengthi1024e4:pathl1:b11:small_6.txteed6:lengthi1024e4:pathl1:b12:small_60.txteed6:lengthi1024e4:pathl1:b12:small_61.txteed6:lengthi1024e4:pathl1:b12:small_62.txteed6:lengthi1024e4:pathl1:b12:small_63.txteed6:lengthi1024e4:pathl1:b12:small_64.txteed6:lengthi1024e4:pathl1:b12:small_65.txteed6:lengthi1024e4:pathl1:b12:small_66.txteed6:lengthi1024e4:pathl1:b12:small_67.txteed6:lengthi1024e4:pathl1:b12:small_68.txteed6:lengthi1024e4:pathl1:b12:small_69.txteed6:lengthi1024e4:pathl1:b11:small_7.txteed6:lengthi1024e4:pathl1:b12:small_70.txteed6:lengthi1024e4:pathl1:b12:small_71.txteed6:lengthi1024e4:pathl1:b12:small_72.txteed6:lengthi1024e4:pathl1:b12:small_73.txteed6:lengthi1024e4:pathl1:b12:small_74.txteed6:lengthi1024e4:pathl1:b12:small_75.txteed6:lengthi1024e4:pathl1:b12:small_76.txteed6:lengthi1024e4:pathl1:b12:small_77.txteed6:lengthi1024e4:pathl1:b12:small_78.txteed6:lengthi1024e4:pathl1:b12:small_79.txteed6:lengthi1024e4:pathl1:b11:small_8.txteed6:lengthi1024e4:pathl1:b12:small_80.txteed6:lengthi1024e4:pathl1:b12:small_81.txteed6:lengthi1024e4:pathl1:b12:small_82.txteed6:lengthi1024e4:pathl1:b12:small_83.txteed6:lengthi1024e4:pathl1:b12:small_84.txteed6:lengthi1024e4:pathl1:b12:small_85.txteed6:lengthi1024e4:pathl1:b12:small_86.txteed6:lengthi1024e4:pathl1:b12:small_87.txteed6:lengthi1024e4:pathl1:b12:small_88.txteed6:lengthi1024e4:pathl1:b12:small_89.txteed6:lengthi1024e4:pathl1:b11:small_9.txteed6:lengthi1024e4:pathl1:b12:small_90.txteed6:lengthi1024e4:pathl1:b12:small_91.txteed6:lengthi1024e4:pathl1:b12:small_92.txteed6:lengthi1024e4:pathl1:b12:small_93.txteed6:lengthi1024e4:pathl1:b12:small_94.txteed6:lengthi1024e4:pathl1:b12:small_95.txteed6:lengthi1024e4:pathl1:b12:small_96.txteed6:lengthi1024e4:pathl1:b12:small_97.txteed6:lengthi1024e4:pathl1:b12:small_98.txteed6:lengthi1024e4:pathl1:b12:small_99.txteed6:lengthi5368709120e4:pathl9:large.txteee4:name1:a12:piece lengthi4194304e6:pieces25620:+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;+̽/8\}Z;Zic^c.>N7ee \ No newline at end of file diff --git a/contrib/bencode/src/access/bencode.rs b/contrib/bencode/src/access/bencode.rs new file mode 100644 index 000000000..ee90296e2 --- /dev/null +++ b/contrib/bencode/src/access/bencode.rs @@ -0,0 +1,120 @@ +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; + +/// Abstract representation of a `BencodeRef` object. +pub enum RefKind<'a, K, V> { + /// Bencode Integer. + Int(i64), + /// Bencode Bytes. + Bytes(&'a [u8]), + /// Bencode List. + List(&'a dyn BListAccess), + /// Bencode Dictionary. + Dict(&'a dyn BDictAccess), +} + +/// Trait for read access to some bencode type. +pub trait BRefAccess: Sized { + type BKey; + type BType: BRefAccess; + + /// Access the bencode as a `BencodeRefKind`. + fn kind(&self) -> RefKind<'_, Self::BKey, Self::BType>; + + /// Attempt to access the bencode as a `str`. + fn str(&self) -> Option<&str>; + + /// Attempt to access the bencode as an `i64`. + fn int(&self) -> Option; + + /// Attempt to access the bencode as an `[u8]`. + fn bytes(&self) -> Option<&[u8]>; + + /// Attempt to access the bencode as an `BListAccess`. + fn list(&self) -> Option<&dyn BListAccess>; + + /// Attempt to access the bencode as an `BDictAccess`. + fn dict(&self) -> Option<&dyn BDictAccess>; +} + +/// Trait for extended read access to some bencode type. +/// +/// Use this trait when you want to make sure that the lifetime of +/// the underlying buffers is tied to the lifetime of the backing +/// bencode buffer. +pub trait BRefAccessExt<'a>: BRefAccess { + /// Attempt to access the bencode as a `str`. + fn str_ext(&self) -> Option<&'a str>; + + /// Attempt to access the bencode as an `[u8]`. + fn bytes_ext(&self) -> Option<&'a [u8]>; +} + +impl<'a, T> BRefAccess for &'a T +where + T: BRefAccess, +{ + type BKey = T::BKey; + type BType = T::BType; + + fn kind(&self) -> RefKind<'_, Self::BKey, Self::BType> { + (*self).kind() + } + + fn str(&self) -> Option<&str> { + (*self).str() + } + + fn int(&self) -> Option { + (*self).int() + } + + fn bytes(&self) -> Option<&[u8]> { + (*self).bytes() + } + + fn list(&self) -> Option<&dyn BListAccess> { + (*self).list() + } + + fn dict(&self) -> Option<&dyn BDictAccess> { + (*self).dict() + } +} + +impl<'a: 'b, 'b, T> BRefAccessExt<'a> for &'b T +where + T: BRefAccessExt<'a>, +{ + fn str_ext(&self) -> Option<&'a str> { + (*self).str_ext() + } + + fn bytes_ext(&self) -> Option<&'a [u8]> { + (*self).bytes_ext() + } +} + +/// Abstract representation of a `BencodeMut` object. +pub enum MutKind<'a, K, V> { + /// Bencode Integer. + Int(i64), + /// Bencode Bytes. + Bytes(&'a [u8]), + /// Bencode List. + List(&'a mut dyn BListAccess), + /// Bencode Dictionary. + Dict(&'a mut dyn BDictAccess), +} + +/// Trait for write access to some bencode type. +pub trait BMutAccess: Sized + BRefAccess { + /// Access the bencode as a `BencodeMutKind`. + fn kind_mut(&mut self) -> MutKind<'_, Self::BKey, Self::BType>; + + /// Attempt to access the bencode as a mutable `BListAccess`. + fn list_mut(&mut self) -> Option<&mut dyn BListAccess>; + + /// Attempt to access the bencode as a mutable `BDictAccess`. + fn dict_mut(&mut self) -> Option<&mut dyn BDictAccess>; +} diff --git a/contrib/bencode/src/access/convert.rs b/contrib/bencode/src/access/convert.rs new file mode 100644 index 000000000..42b04f267 --- /dev/null +++ b/contrib/bencode/src/access/convert.rs @@ -0,0 +1,230 @@ +#![allow(clippy::missing_errors_doc)] +use crate::access::bencode::{BRefAccess, BRefAccessExt}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; +use crate::{BencodeConvertError, BencodeConvertErrorKind}; + +/// Trait for extended casting of bencode objects and converting conversion errors into application specific errors. +pub trait BConvertExt: BConvert { + /// See `BConvert::convert_bytes`. + fn convert_bytes_ext<'a, B, E>(&self, bencode: B, error_key: E) -> Result<&'a [u8], Self::Error> + where + B: BRefAccessExt<'a>, + E: AsRef<[u8]>, + { + bencode.bytes_ext().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Bytes".to_owned(), + })), + ) + } + + /// See `BConvert::convert_str`. + fn convert_str_ext<'a, B, E>(&self, bencode: &B, error_key: E) -> Result<&'a str, Self::Error> + where + B: BRefAccessExt<'a>, + E: AsRef<[u8]>, + { + bencode.str_ext().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "UTF-8 Bytes".to_owned(), + })), + ) + } + + /// See `BConvert::lookup_and_convert_bytes`. + fn lookup_and_convert_bytes_ext<'a, B, K1, K2>( + &self, + dictionary: &dyn BDictAccess, + key: K2, + ) -> Result<&'a [u8], Self::Error> + where + B: BRefAccessExt<'a>, + K2: AsRef<[u8]>, + { + self.convert_bytes_ext(self.lookup(dictionary, &key)?, &key) + } + + /// See `BConvert::lookup_and_convert_str`. + fn lookup_and_convert_str_ext<'a, B, K1, K2>( + &self, + dictionary: &dyn BDictAccess, + key: K2, + ) -> Result<&'a str, Self::Error> + where + B: BRefAccessExt<'a>, + K2: AsRef<[u8]>, + { + self.convert_str_ext(self.lookup(dictionary, &key)?, &key) + } +} + +/// Trait for casting bencode objects and converting conversion errors into application specific errors. +#[allow(clippy::module_name_repetitions)] +pub trait BConvert { + type Error; + + /// Convert the given conversion error into the appropriate error type. + fn handle_error(&self, error: BencodeConvertError) -> Self::Error; + + /// Attempt to convert the given bencode value into an integer. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_int(&self, bencode: B, error_key: E) -> Result + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.int().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Integer".to_owned(), + })), + ) + } + + /// Attempt to convert the given bencode value into bytes. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_bytes<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a [u8], Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.bytes().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Bytes".to_owned(), + })), + ) + } + + /// Attempt to convert the given bencode value into a UTF-8 string. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_str<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a str, Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.str().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "UTF-8 Bytes".to_owned(), + })), + ) + } + + /// Attempt to convert the given bencode value into a list. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_list<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a dyn BListAccess, Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.list().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "List".to_owned(), + })), + ) + } + + /// Attempt to convert the given bencode value into a dictionary. + /// + /// Error key is used to generate an appropriate error message should the operation return an error. + fn convert_dict<'a, B, E>(&self, bencode: &'a B, error_key: E) -> Result<&'a dyn BDictAccess, Self::Error> + where + B: BRefAccess, + E: AsRef<[u8]>, + { + bencode.dict().ok_or( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::WrongType { + key: error_key.as_ref().to_owned(), + expected_type: "Dictionary".to_owned(), + })), + ) + } + + /// Look up a value in a dictionary of bencoded values using the given key. + fn lookup<'a, B, K1, K2>(&self, dictionary: &'a dyn BDictAccess, key: K2) -> Result<&'a B, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + let key_ref = key.as_ref(); + + match dictionary.lookup(key_ref) { + Some(n) => Ok(n), + None => Err( + self.handle_error(BencodeConvertError::from_kind(BencodeConvertErrorKind::MissingKey { + key: key_ref.to_owned(), + })), + ), + } + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to an integer. + fn lookup_and_convert_int(&self, dictionary: &dyn BDictAccess, key: K2) -> Result + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_int(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a series of bytes. + fn lookup_and_convert_bytes<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a [u8], Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_bytes(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a UTF-8 string. + fn lookup_and_convert_str<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a str, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_str(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a list. + fn lookup_and_convert_list<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a dyn BListAccess, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_list(self.lookup(dictionary, &key)?, &key) + } + + /// Combines a lookup operation on the given key with a conversion of the value, if found, to a dictionary. + fn lookup_and_convert_dict<'a, B, K1, K2>( + &self, + dictionary: &'a dyn BDictAccess, + key: K2, + ) -> Result<&'a dyn BDictAccess, Self::Error> + where + B: BRefAccess, + K2: AsRef<[u8]>, + { + self.convert_dict(self.lookup(dictionary, &key)?, &key) + } +} diff --git a/contrib/bencode/src/access/dict.rs b/contrib/bencode/src/access/dict.rs new file mode 100644 index 000000000..596d9535e --- /dev/null +++ b/contrib/bencode/src/access/dict.rs @@ -0,0 +1,64 @@ +use std::borrow::Cow; +use std::collections::BTreeMap; + +/// Trait for working with generic map data structures. +pub trait BDictAccess { + /// Convert the dictionary to an unordered list of key/value pairs. + fn to_list(&self) -> Vec<(&K, &V)>; + + /// Lookup a value in the dictionary. + fn lookup(&self, key: &[u8]) -> Option<&V>; + + /// Lookup a mutable value in the dictionary. + fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V>; + + /// Insert a key/value pair into the dictionary. + fn insert(&mut self, key: K, value: V) -> Option; + + /// Remove a value from the dictionary and return it. + fn remove(&mut self, key: &[u8]) -> Option; +} + +impl<'a, V> BDictAccess<&'a [u8], V> for BTreeMap<&'a [u8], V> { + fn to_list(&self) -> Vec<(&&'a [u8], &V)> { + self.iter().map(|(k, v)| (k, v)).collect() + } + + fn lookup(&self, key: &[u8]) -> Option<&V> { + self.get(key) + } + + fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V> { + self.get_mut(key) + } + + fn insert(&mut self, key: &'a [u8], value: V) -> Option { + self.insert(key, value) + } + + fn remove(&mut self, key: &[u8]) -> Option { + self.remove(key) + } +} + +impl<'a, V> BDictAccess, V> for BTreeMap, V> { + fn to_list(&self) -> Vec<(&Cow<'a, [u8]>, &V)> { + self.iter().map(|(k, v)| (k, v)).collect() + } + + fn lookup(&self, key: &[u8]) -> Option<&V> { + self.get(key) + } + + fn lookup_mut(&mut self, key: &[u8]) -> Option<&mut V> { + self.get_mut(key) + } + + fn insert(&mut self, key: Cow<'a, [u8]>, value: V) -> Option { + self.insert(key, value) + } + + fn remove(&mut self, key: &[u8]) -> Option { + self.remove(key) + } +} diff --git a/contrib/bencode/src/access/list.rs b/contrib/bencode/src/access/list.rs new file mode 100644 index 000000000..840bffa1e --- /dev/null +++ b/contrib/bencode/src/access/list.rs @@ -0,0 +1,108 @@ +use std::ops::{Index, IndexMut}; + +/// Trait for working with generic list data structures. +pub trait BListAccess { + /// Get a list element at the given index. + fn get(&self, index: usize) -> Option<&V>; + + /// Get a mutable list element at the given index. + fn get_mut(&mut self, index: usize) -> Option<&mut V>; + + /// Remove a list element at the given index. + fn remove(&mut self, index: usize) -> Option; + + /// Insert a list element at the given index. + fn insert(&mut self, index: usize, item: V); + + /// Push an element to the back of the list. + fn push(&mut self, item: V); + + /// Get the length of the list. + fn len(&self) -> usize; + + fn is_empty(&self) -> bool; +} + +impl<'a, V: 'a> Index for &'a dyn BListAccess { + type Output = V; + + fn index(&self, index: usize) -> &V { + self.get(index).unwrap() + } +} + +impl<'a, V: 'a> Index for &'a mut dyn BListAccess { + type Output = V; + + fn index(&self, index: usize) -> &V { + self.get(index).unwrap() + } +} + +impl<'a, V: 'a> IndexMut for &'a mut dyn BListAccess { + fn index_mut(&mut self, index: usize) -> &mut V { + self.get_mut(index).unwrap() + } +} + +impl<'a, V: 'a> IntoIterator for &'a dyn BListAccess { + type Item = &'a V; + type IntoIter = BListIter<'a, V>; + + fn into_iter(self) -> BListIter<'a, V> { + BListIter { index: 0, access: self } + } +} + +pub struct BListIter<'a, V> { + index: usize, + access: &'a dyn BListAccess, +} + +impl<'a, V> Iterator for BListIter<'a, V> { + type Item = &'a V; + + fn next(&mut self) -> Option<&'a V> { + let opt_next = self.access.get(self.index); + + if opt_next.is_some() { + self.index += 1; + } + + opt_next + } +} + +impl BListAccess for Vec { + fn get(&self, index: usize) -> Option<&V> { + self[..].get(index) + } + + fn get_mut(&mut self, index: usize) -> Option<&mut V> { + self[..].get_mut(index) + } + + fn remove(&mut self, index: usize) -> Option { + if index >= self[..].len() { + None + } else { + Some(Vec::remove(self, index)) + } + } + + fn insert(&mut self, index: usize, item: V) { + Vec::insert(self, index, item); + } + + fn push(&mut self, item: V) { + Vec::push(self, item); + } + + fn len(&self) -> usize { + Vec::len(self) + } + + fn is_empty(&self) -> bool { + Vec::is_empty(self) + } +} diff --git a/contrib/bencode/src/access/mod.rs b/contrib/bencode/src/access/mod.rs new file mode 100644 index 000000000..f14b032d4 --- /dev/null +++ b/contrib/bencode/src/access/mod.rs @@ -0,0 +1,4 @@ +pub mod bencode; +pub mod convert; +pub mod dict; +pub mod list; diff --git a/contrib/bencode/src/cow.rs b/contrib/bencode/src/cow.rs new file mode 100644 index 000000000..0d38c751b --- /dev/null +++ b/contrib/bencode/src/cow.rs @@ -0,0 +1,44 @@ +use std::borrow::Cow; + +/// Trait for macros to convert owned/borrowed types to `Cow`. +/// +/// This is needed because `&str` and `String` do not have `From` +/// implements into `Cow<_, [u8]>`. One solution is to just call `AsRef<[u8]>` +/// before converting. However, then when a user specifies an owned type, +/// we will implicitly borrow that; this trait prevents that so that macro +/// behavior is intuitive, so that owned types stay owned. +pub trait BCowConvert<'a> { + fn convert(self) -> Cow<'a, [u8]>; +} + +// TODO: Enable when specialization lands. +/* +impl<'a, T> BCowConvert<'a> for T where T: AsRef<[u8]> + 'a { + fn convert(self) -> Cow<'a, [u8]> { + self.into() + } +}*/ + +impl<'a> BCowConvert<'a> for &'a [u8] { + fn convert(self) -> Cow<'a, [u8]> { + self.into() + } +} + +impl<'a> BCowConvert<'a> for &'a str { + fn convert(self) -> Cow<'a, [u8]> { + self.as_bytes().into() + } +} + +impl BCowConvert<'static> for String { + fn convert(self) -> Cow<'static, [u8]> { + self.into_bytes().into() + } +} + +impl BCowConvert<'static> for Vec { + fn convert(self) -> Cow<'static, [u8]> { + self.into() + } +} diff --git a/contrib/bencode/src/error.rs b/contrib/bencode/src/error.rs new file mode 100644 index 000000000..18ebe9605 --- /dev/null +++ b/contrib/bencode/src/error.rs @@ -0,0 +1,101 @@ +use error_chain::error_chain; + +error_chain! { + types { + BencodeParseError, BencodeParseErrorKind, BencodeParseResultExt, BencodeParseResult; + } + + errors { + BytesEmpty { + pos: usize + } { + description("Incomplete Number Of Bytes") + display("Incomplete Number Of Bytes At {:?}", pos) + } + InvalidByte { + pos: usize + } { + description("Invalid Byte Found") + display("Invalid Byte Found At {:?}", pos) + } + InvalidIntNoDelimiter { + pos: usize + } { + description("Invalid Integer Found With No Delimiter") + display("Invalid Integer Found With No Delimiter At {:?}", pos) + } + InvalidIntNegativeZero { + pos: usize + } { + description("Invalid Integer Found As Negative Zero") + display("Invalid Integer Found As Negative Zero At {:?}", pos) + } + InvalidIntZeroPadding { + pos: usize + } { + description("Invalid Integer Found With Zero Padding") + display("Invalid Integer Found With Zero Padding At {:?}", pos) + } + InvalidIntParseError { + pos: usize + } { + description("Invalid Integer Found To Fail Parsing") + display("Invalid Integer Found To Fail Parsing At {:?}", pos) + } + InvalidKeyOrdering { + pos: usize, + key: Vec + } { + description("Invalid Dictionary Key Ordering Found") + display("Invalid Dictionary Key Ordering Found At {:?} For Key {:?}", pos, key) + } + InvalidKeyDuplicates { + pos: usize, + key: Vec + } { + description("Invalid Dictionary Duplicate Keys Found") + display("Invalid Dictionary Key Found At {:?} For Key {:?}", pos, key) + } + InvalidLengthNegative { + pos: usize + } { + description("Invalid Byte Length Found As Negative") + display("Invalid Byte Length Found As Negative At {:?}", pos) + } + InvalidLengthOverflow { + pos: usize + } { + description("Invalid Byte Length Found To Overflow Buffer Length") + display("Invalid Byte Length Found To Overflow Buffer Length At {:?}", pos) + } + InvalidRecursionExceeded { + pos: usize, + max: usize + } { + description("Invalid Recursion Limit Exceeded") + display("Invalid Recursion Limit Exceeded At {:?} For Limit {:?}", pos, max) + } + } +} + +error_chain! { + types { + BencodeConvertError, BencodeConvertErrorKind, BencodeConvertResultExt, BencodeConvertResult; + } + + errors { + MissingKey { + key: Vec + } { + description("Missing Key In Bencode") + display("Missing Key In Bencode For {:?}", key) + } + WrongType { + key: Vec, + expected_type: String + } { + description("Wrong Type In Bencode") + display("Wrong Type In Bencode For {:?} Expected Type {}", key, expected_type) + } + } +} diff --git a/contrib/bencode/src/lib.rs b/contrib/bencode/src/lib.rs new file mode 100644 index 000000000..78e113b66 --- /dev/null +++ b/contrib/bencode/src/lib.rs @@ -0,0 +1,143 @@ +//! Library for parsing and converting bencoded data. +//! +//! # Examples +//! +//! Decoding bencoded data: +//! +//! ```rust +//! extern crate bencode; +//! +//! use std::default::Default; +//! use bencode::{BencodeRef, BRefAccess, BDecodeOpt}; +//! +//! fn main() { +//! let data = b"d12:lucky_numberi7ee"; // cspell:disable-line +//! let bencode = BencodeRef::decode(data, BDecodeOpt::default()).unwrap(); +//! +//! assert_eq!(7, bencode.dict().unwrap().lookup("lucky_number".as_bytes()) +//! .unwrap().int().unwrap()); +//! } +//! ``` +//! +//! Encoding bencoded data: +//! +//! ```rust +//! #[macro_use] +//! extern crate bencode; +//! +//! fn main() { +//! let message = (ben_map!{ +//! "lucky_number" => ben_int!(7), +//! "lucky_string" => ben_bytes!("7") +//! }).encode(); +//! +//! let data = b"d12:lucky_numberi7e12:lucky_string1:7e"; // cspell:disable-line +//! assert_eq!(&data[..], &message[..]); +//! } +//! ``` + +mod access; +mod cow; +mod error; +mod mutable; +mod reference; + +/// Traits for implementation functionality. +pub mod inner { + pub use crate::cow::BCowConvert; +} + +/// Traits for extended functionality. +pub mod ext { + #[allow(clippy::module_name_repetitions)] + pub use crate::access::bencode::BRefAccessExt; + #[allow(clippy::module_name_repetitions)] + pub use crate::access::convert::BConvertExt; +} + +#[deprecated(since = "1.0.0", note = "use `MutKind` instead.")] +pub use crate::access::bencode::MutKind as BencodeMutKind; +#[deprecated(since = "1.0.0", note = "use `RefKind` instead.")] +pub use crate::access::bencode::RefKind as BencodeRefKind; +pub use crate::access::bencode::{BMutAccess, BRefAccess, MutKind, RefKind}; +pub use crate::access::convert::BConvert; +pub use crate::access::dict::BDictAccess; +pub use crate::access::list::BListAccess; +pub use crate::error::{ + BencodeConvertError, BencodeConvertErrorKind, BencodeConvertResult, BencodeParseError, BencodeParseErrorKind, + BencodeParseResult, +}; +pub use crate::mutable::bencode_mut::BencodeMut; +pub use crate::reference::bencode_ref::BencodeRef; +pub use crate::reference::decode_opt::BDecodeOpt; + +const BEN_END: u8 = b'e'; +const DICT_START: u8 = b'd'; +const LIST_START: u8 = b'l'; +const INT_START: u8 = b'i'; + +const BYTE_LEN_LOW: u8 = b'0'; +const BYTE_LEN_HIGH: u8 = b'9'; +const BYTE_LEN_END: u8 = b':'; + +/// Construct a `BencodeMut` map by supplying string references as keys and `BencodeMut` as values. +#[macro_export] +macro_rules! ben_map { +( $($key:expr => $val:expr),* ) => { + { + use $crate::{BMutAccess, BencodeMut}; + use $crate::inner::BCowConvert; + + let mut bencode_map = BencodeMut::new_dict(); + { + let map = bencode_map.dict_mut().unwrap(); + $( + map.insert(BCowConvert::convert($key), $val); + )* + } + + bencode_map + } + } +} + +/// Construct a `BencodeMut` list by supplying a list of `BencodeMut` values. +#[macro_export] +macro_rules! ben_list { + ( $($ben:expr),* ) => { + { + use $crate::{BencodeMut, BMutAccess}; + + let mut bencode_list = BencodeMut::new_list(); + { + let list = bencode_list.list_mut().unwrap(); + $( + list.push($ben); + )* + } + + bencode_list + } + } +} + +/// Construct `BencodeMut` bytes by supplying a type convertible to `Vec`. +#[macro_export] +macro_rules! ben_bytes { + ( $ben:expr ) => {{ + use $crate::inner::BCowConvert; + use $crate::BencodeMut; + + BencodeMut::new_bytes(BCowConvert::convert($ben)) + }}; +} + +/// Construct a `BencodeMut` integer by supplying an `i64`. +#[macro_export] +macro_rules! ben_int { + ( $ben:expr ) => {{ + use $crate::BencodeMut; + + BencodeMut::new_int($ben) + }}; +} diff --git a/contrib/bencode/src/mutable/bencode_mut.rs b/contrib/bencode/src/mutable/bencode_mut.rs new file mode 100644 index 000000000..a3f95dbbf --- /dev/null +++ b/contrib/bencode/src/mutable/bencode_mut.rs @@ -0,0 +1,229 @@ +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::str; + +use crate::access::bencode::{BMutAccess, BRefAccess, MutKind, RefKind}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; +use crate::mutable::encode; + +/// Bencode object that holds references to the underlying data. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub enum Inner<'a> { + /// Bencode Integer. + Int(i64), + /// Bencode Bytes. + Bytes(Cow<'a, [u8]>), + /// Bencode List. + List(Vec>), + /// Bencode Dictionary. + Dict(BTreeMap, BencodeMut<'a>>), +} + +/// `BencodeMut` object that stores references to some data. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub struct BencodeMut<'a> { + inner: Inner<'a>, +} + +impl<'a> BencodeMut<'a> { + fn new(inner: Inner<'a>) -> BencodeMut<'a> { + BencodeMut { inner } + } + + /// Create a new `BencodeMut` representing an `i64`. + #[must_use] + pub fn new_int(value: i64) -> BencodeMut<'a> { + BencodeMut::new(Inner::Int(value)) + } + + /// Create a new `BencodeMut` representing a `[u8]`. + #[must_use] + pub fn new_bytes(value: Cow<'a, [u8]>) -> BencodeMut<'a> { + BencodeMut::new(Inner::Bytes(value)) + } + + /// Create a new `BencodeMut` representing a `BListAccess`. + #[must_use] + pub fn new_list() -> BencodeMut<'a> { + BencodeMut::new(Inner::List(Vec::new())) + } + + /// Create a new `BencodeMut` representing a `BDictAccess`. + #[must_use] + pub fn new_dict() -> BencodeMut<'a> { + BencodeMut::new(Inner::Dict(BTreeMap::new())) + } + + /// Encode the `BencodeMut` into a buffer representing the bencode. + #[must_use] + pub fn encode(&self) -> Vec { + let mut buffer = Vec::new(); + + encode::encode(self, &mut buffer); + + buffer + } +} + +impl<'a> BRefAccess for BencodeMut<'a> { + type BKey = Cow<'a, [u8]>; + type BType = BencodeMut<'a>; + + fn kind<'b>(&'b self) -> RefKind<'b, Cow<'a, [u8]>, BencodeMut<'a>> { + match self.inner { + Inner::Int(n) => RefKind::Int(n), + Inner::Bytes(ref n) => RefKind::Bytes(n), + Inner::List(ref n) => RefKind::List(n), + Inner::Dict(ref n) => RefKind::Dict(n), + } + } + + fn str(&self) -> Option<&str> { + let bytes = self.bytes()?; + + match str::from_utf8(bytes) { + Ok(n) => Some(n), + Err(_) => None, + } + } + + fn int(&self) -> Option { + match self.inner { + Inner::Int(n) => Some(n), + _ => None, + } + } + + fn bytes(&self) -> Option<&[u8]> { + match self.inner { + Inner::Bytes(ref n) => Some(n.as_ref()), + _ => None, + } + } + + fn list(&self) -> Option<&dyn BListAccess>> { + match self.inner { + Inner::List(ref n) => Some(n), + _ => None, + } + } + + fn dict(&self) -> Option<&dyn BDictAccess, BencodeMut<'a>>> { + match self.inner { + Inner::Dict(ref n) => Some(n), + _ => None, + } + } +} + +impl<'a> BMutAccess for BencodeMut<'a> { + fn kind_mut<'b>(&'b mut self) -> MutKind<'b, Cow<'a, [u8]>, BencodeMut<'a>> { + match self.inner { + Inner::Int(n) => MutKind::Int(n), + Inner::Bytes(ref mut n) => MutKind::Bytes((*n).as_ref()), + Inner::List(ref mut n) => MutKind::List(n), + Inner::Dict(ref mut n) => MutKind::Dict(n), + } + } + + fn list_mut(&mut self) -> Option<&mut dyn BListAccess>> { + match self.inner { + Inner::List(ref mut n) => Some(n), + _ => None, + } + } + + fn dict_mut(&mut self) -> Option<&mut dyn BDictAccess, BencodeMut<'a>>> { + match self.inner { + Inner::Dict(ref mut n) => Some(n), + _ => None, + } + } +} + +// impl<'a> From> for BencodeMut<'a> { +// fn from(value: BencodeRef<'a>) -> Self { +// let inner = match value.kind() { +// BencodeRefKind::Int(value) => InnerBencodeMut::Int(value), +// BencodeRefKind::Bytes(value) => InnerBencodeMut::Bytes(Cow::Owned(Vec::from(value))), +// BencodeRefKind::List(value) => { +// InnerBencodeMut::List(value.clone().into_iter().map(|b| BencodeMut::from(b.clone())).collect()) +// } +// BencodeRefKind::Dict(value) => InnerBencodeMut::Dict( +// value +// .to_list() +// .into_iter() +// .map(|(key, value)| (Cow::Owned(Vec::from(*key)), BencodeMut::from(value.clone()))) +// .collect(), +// ), +// }; +// BencodeMut { inner } +// } +// } + +#[cfg(test)] +mod test { + use crate::access::bencode::BMutAccess; + use crate::mutable::bencode_mut::BencodeMut; + + #[test] + fn positive_int_encode() { + let bencode_int = BencodeMut::new_int(-560); + + let int_bytes = b"i-560e"; // cspell:disable-line + assert_eq!(&int_bytes[..], &bencode_int.encode()[..]); + } + + #[test] + fn positive_bytes_encode() { + /* cspell:disable-next-line */ + let bencode_bytes = BencodeMut::new_bytes((&b"asdasd"[..]).into()); + + let bytes_bytes = b"6:asdasd"; // cspell:disable-line + assert_eq!(&bytes_bytes[..], &bencode_bytes.encode()[..]); + } + + #[test] + fn positive_empty_list_encode() { + let bencode_list = BencodeMut::new_list(); + + let list_bytes = b"le"; // cspell:disable-line + assert_eq!(&list_bytes[..], &bencode_list.encode()[..]); + } + + #[test] + fn positive_nonempty_list_encode() { + let mut bencode_list = BencodeMut::new_list(); + + { + let list_mut = bencode_list.list_mut().unwrap(); + list_mut.push(BencodeMut::new_int(56)); + } + + let list_bytes = b"li56ee"; // cspell:disable-line + assert_eq!(&list_bytes[..], &bencode_list.encode()[..]); + } + + #[test] + fn positive_empty_dict_encode() { + let bencode_dict = BencodeMut::new_dict(); + + let dict_bytes = b"de"; // cspell:disable-line + assert_eq!(&dict_bytes[..], &bencode_dict.encode()[..]); + } + + #[test] + fn positive_nonempty_dict_encode() { + let mut bencode_dict = BencodeMut::new_dict(); + + { + let dict_mut = bencode_dict.dict_mut().unwrap(); + /* cspell:disable-next-line */ + dict_mut.insert((&b"asd"[..]).into(), BencodeMut::new_bytes((&b"asdasd"[..]).into())); + } + + let dict_bytes = b"d3:asd6:asdasde"; // cspell:disable-line + assert_eq!(&dict_bytes[..], &bencode_dict.encode()[..]); + } +} diff --git a/contrib/bencode/src/mutable/encode.rs b/contrib/bencode/src/mutable/encode.rs new file mode 100644 index 000000000..811c35816 --- /dev/null +++ b/contrib/bencode/src/mutable/encode.rs @@ -0,0 +1,67 @@ +use std::iter::Extend; + +use crate::access::bencode::{BRefAccess, RefKind}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; + +pub fn encode(val: T, bytes: &mut Vec) +where + T: BRefAccess, + T::BKey: AsRef<[u8]>, +{ + match val.kind() { + RefKind::Int(n) => encode_int(n, bytes), + RefKind::Bytes(n) => encode_bytes(n, bytes), + RefKind::List(n) => encode_list(n, bytes), + RefKind::Dict(n) => encode_dict(n, bytes), + } +} + +fn encode_int(val: i64, bytes: &mut Vec) { + bytes.push(crate::INT_START); + + bytes.extend(val.to_string().into_bytes()); + + bytes.push(crate::BEN_END); +} + +fn encode_bytes(list: &[u8], bytes: &mut Vec) { + bytes.extend(list.len().to_string().into_bytes()); + + bytes.push(crate::BYTE_LEN_END); + + bytes.extend(list.iter().copied()); +} + +fn encode_list(list: &dyn BListAccess, bytes: &mut Vec) +where + T: BRefAccess, + T::BKey: AsRef<[u8]>, +{ + bytes.push(crate::LIST_START); + + for i in list { + encode(i, bytes); + } + + bytes.push(crate::BEN_END); +} + +fn encode_dict(dict: &dyn BDictAccess, bytes: &mut Vec) +where + K: AsRef<[u8]>, + V: BRefAccess, + V::BKey: AsRef<[u8]>, +{ + // Need To Sort The Keys In The Map Before Encoding + let mut sort_dict = dict.to_list(); + sort_dict.sort_by(|&(a, _), &(b, _)| a.as_ref().cmp(b.as_ref())); + + bytes.push(crate::DICT_START); + // Iterate And Dictionary Encode The (String, Bencode) Pairs + for (key, value) in &sort_dict { + encode_bytes(key.as_ref(), bytes); + encode(value, bytes); + } + bytes.push(crate::BEN_END); +} diff --git a/contrib/bencode/src/mutable/mod.rs b/contrib/bencode/src/mutable/mod.rs new file mode 100644 index 000000000..329ee9f7a --- /dev/null +++ b/contrib/bencode/src/mutable/mod.rs @@ -0,0 +1,2 @@ +pub mod bencode_mut; +mod encode; diff --git a/contrib/bencode/src/reference/bencode_ref.rs b/contrib/bencode/src/reference/bencode_ref.rs new file mode 100644 index 000000000..760dd3016 --- /dev/null +++ b/contrib/bencode/src/reference/bencode_ref.rs @@ -0,0 +1,265 @@ +use std::collections::BTreeMap; +use std::str; + +use crate::access::bencode::{BRefAccess, BRefAccessExt, RefKind}; +use crate::access::dict::BDictAccess; +use crate::access::list::BListAccess; +use crate::error::{BencodeParseError, BencodeParseErrorKind, BencodeParseResult}; +use crate::reference::decode; +use crate::reference::decode_opt::BDecodeOpt; + +/// Bencode object that holds references to the underlying data. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub enum Inner<'a> { + /// Bencode Integer. + Int(i64, &'a [u8]), + /// Bencode Bytes. + Bytes(&'a [u8], &'a [u8]), + /// Bencode List. + List(Vec>, &'a [u8]), + /// Bencode Dictionary. + Dict(BTreeMap<&'a [u8], BencodeRef<'a>>, &'a [u8]), +} + +impl<'a> From> for BencodeRef<'a> { + fn from(val: Inner<'a>) -> Self { + BencodeRef { inner: val } + } +} + +/// `BencodeRef` object that stores references to some buffer. +#[derive(Debug, Eq, PartialEq, Clone, Hash)] +pub struct BencodeRef<'a> { + inner: Inner<'a>, +} + +impl<'a> BencodeRef<'a> { + /// Decode the given bytes into a `BencodeRef` using the given decode options. + #[allow(clippy::missing_errors_doc)] + pub fn decode(bytes: &'a [u8], opts: BDecodeOpt) -> BencodeParseResult> { + // Apply try so any errors return before the eof check + let (bencode, end_pos) = decode::decode(bytes, 0, opts, 0)?; + + if end_pos != bytes.len() && opts.enforce_full_decode() { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::BytesEmpty { + pos: end_pos, + })); + } + + Ok(bencode) + } + + /// Get a byte slice of the current bencode byte representation. + #[must_use] + pub fn buffer(&self) -> &'a [u8] { + #[allow(clippy::match_same_arms)] + match self.inner { + Inner::Int(_, buffer) => buffer, + Inner::Bytes(_, buffer) => buffer, + Inner::List(_, buffer) => buffer, + Inner::Dict(_, buffer) => buffer, + } + } +} + +impl<'a> BRefAccess for BencodeRef<'a> { + type BKey = &'a [u8]; + type BType = BencodeRef<'a>; + + fn kind<'b>(&'b self) -> RefKind<'b, &'a [u8], BencodeRef<'a>> { + match self.inner { + Inner::Int(n, _) => RefKind::Int(n), + Inner::Bytes(n, _) => RefKind::Bytes(n), + Inner::List(ref n, _) => RefKind::List(n), + Inner::Dict(ref n, _) => RefKind::Dict(n), + } + } + + fn str(&self) -> Option<&str> { + self.str_ext() + } + + fn int(&self) -> Option { + match self.inner { + Inner::Int(n, _) => Some(n), + _ => None, + } + } + + fn bytes(&self) -> Option<&[u8]> { + self.bytes_ext() + } + + fn list(&self) -> Option<&dyn BListAccess>> { + match self.inner { + Inner::List(ref n, _) => Some(n), + _ => None, + } + } + + fn dict(&self) -> Option<&dyn BDictAccess<&'a [u8], BencodeRef<'a>>> { + match self.inner { + Inner::Dict(ref n, _) => Some(n), + _ => None, + } + } +} + +impl<'a> BRefAccessExt<'a> for BencodeRef<'a> { + fn str_ext(&self) -> Option<&'a str> { + let bytes = self.bytes_ext()?; + + match str::from_utf8(bytes) { + Ok(n) => Some(n), + Err(_) => None, + } + } + + fn bytes_ext(&self) -> Option<&'a [u8]> { + match self.inner { + Inner::Bytes(n, _) => Some(&n[0..]), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use std::default::Default; + + use crate::access::bencode::BRefAccess; + use crate::reference::bencode_ref::BencodeRef; + use crate::reference::decode_opt::BDecodeOpt; + + #[test] + fn positive_int_buffer() { + let int_bytes = b"i-500e"; // cspell:disable-line + let bencode = BencodeRef::decode(&int_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(int_bytes, bencode.buffer()); + } + + #[test] + fn positive_bytes_buffer() { + let bytes_bytes = b"3:asd"; // cspell:disable-line + let bencode = BencodeRef::decode(&bytes_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(bytes_bytes, bencode.buffer()); + } + + #[test] + fn positive_list_buffer() { + let list_bytes = b"l3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&list_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(list_bytes, bencode.buffer()); + } + + #[test] + fn positive_dict_buffer() { + let dict_bytes = b"d3:asd3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&dict_bytes[..], BDecodeOpt::default()).unwrap(); + + assert_eq!(dict_bytes, bencode.buffer()); + } + + #[test] + fn positive_list_nested_int_buffer() { + let nested_int_bytes = b"li-500ee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_int_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_int = bencode_list.get(0).unwrap(); + + let int_bytes = b"i-500e"; // cspell:disable-line + assert_eq!(int_bytes, bencode_int.buffer()); + } + + #[test] + fn positive_dict_nested_int_buffer() { + let nested_int_bytes = b"d3:asdi-500ee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_int_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_int = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let int_bytes = b"i-500e"; // cspell:disable-line + assert_eq!(int_bytes, bencode_int.buffer()); + } + + #[test] + fn positive_list_nested_bytes_buffer() { + let nested_bytes_bytes = b"l3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_bytes_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_bytes = bencode_list.get(0).unwrap(); + + let bytes_bytes = b"3:asd"; // cspell:disable-line + assert_eq!(bytes_bytes, bencode_bytes.buffer()); + } + + #[test] + fn positive_dict_nested_bytes_buffer() { + let nested_bytes_bytes = b"d3:asd3:asde"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_bytes_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_bytes = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let bytes_bytes = b"3:asd"; // cspell:disable-line + assert_eq!(bytes_bytes, bencode_bytes.buffer()); + } + + #[test] + fn positive_list_nested_list_buffer() { + let nested_list_bytes = b"ll3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_list_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_list = bencode_list.get(0).unwrap(); + + let list_bytes = b"l3:asde"; // cspell:disable-line + assert_eq!(list_bytes, bencode_list.buffer()); + } + + #[test] + fn positive_dict_nested_list_buffer() { + let nested_list_bytes = b"d3:asdl3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_list_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_list = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let list_bytes = b"l3:asde"; // cspell:disable-line + assert_eq!(list_bytes, bencode_list.buffer()); + } + + #[test] + fn positive_list_nested_dict_buffer() { + let nested_dict_bytes = b"ld3:asd3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_dict_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_list = bencode.list().unwrap(); + let bencode_dict = bencode_list.get(0).unwrap(); + + let dict_bytes = b"d3:asd3:asde"; // cspell:disable-line + assert_eq!(dict_bytes, bencode_dict.buffer()); + } + + #[test] + fn positive_dict_nested_dict_buffer() { + let nested_dict_bytes = b"d3:asdd3:asd3:asdee"; // cspell:disable-line + let bencode = BencodeRef::decode(&nested_dict_bytes[..], BDecodeOpt::default()).unwrap(); + + let bencode_dict = bencode.dict().unwrap(); + /* cspell:disable-next-line */ + let bencode_dict = bencode_dict.lookup(&b"asd"[..]).unwrap(); + + let dict_bytes = b"d3:asd3:asde"; // cspell:disable-line + assert_eq!(dict_bytes, bencode_dict.buffer()); + } +} diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs new file mode 100644 index 000000000..d2aa180f8 --- /dev/null +++ b/contrib/bencode/src/reference/decode.rs @@ -0,0 +1,397 @@ +use std::collections::btree_map::Entry; +use std::collections::BTreeMap; +use std::str::{self}; + +use crate::error::{BencodeParseError, BencodeParseErrorKind, BencodeParseResult}; +use crate::reference::bencode_ref::{BencodeRef, Inner}; +use crate::reference::decode_opt::BDecodeOpt; + +pub fn decode(bytes: &[u8], pos: usize, opts: BDecodeOpt, depth: usize) -> BencodeParseResult<(BencodeRef<'_>, usize)> { + if depth >= opts.max_recursion() { + return Err(BencodeParseError::from_kind( + BencodeParseErrorKind::InvalidRecursionExceeded { pos, max: depth }, + )); + } + let curr_byte = peek_byte(bytes, pos)?; + + match curr_byte { + crate::INT_START => { + let (bencode, next_pos) = decode_int(bytes, pos + 1, crate::BEN_END)?; + Ok((Inner::Int(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + crate::LIST_START => { + let (bencode, next_pos) = decode_list(bytes, pos + 1, opts, depth)?; + Ok((Inner::List(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + crate::DICT_START => { + let (bencode, next_pos) = decode_dict(bytes, pos + 1, opts, depth)?; + Ok((Inner::Dict(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + crate::BYTE_LEN_LOW..=crate::BYTE_LEN_HIGH => { + let (bencode, next_pos) = decode_bytes(bytes, pos)?; + // Include the length digit, don't increment position + Ok((Inner::Bytes(bencode, &bytes[pos..next_pos]).into(), next_pos)) + } + _ => Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidByte { pos })), + } +} + +fn decode_int(bytes: &[u8], pos: usize, delim: u8) -> BencodeParseResult<(i64, usize)> { + let (_, begin_decode) = bytes.split_at(pos); + + let Some(relative_end_pos) = begin_decode.iter().position(|n| *n == delim) else { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntNoDelimiter { + pos, + })); + }; + let int_byte_slice = &begin_decode[..relative_end_pos]; + + if int_byte_slice.len() > 1 { + // Negative zero is not allowed (this would not be caught when converting) + if int_byte_slice[0] == b'-' && int_byte_slice[1] == b'0' { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntNegativeZero { + pos, + })); + } + + // Zero padding is illegal, and unspecified for key lengths (we disallow both) + if int_byte_slice[0] == b'0' { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntZeroPadding { + pos, + })); + } + } + + let Ok(int_str) = str::from_utf8(int_byte_slice) else { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntParseError { + pos, + })); + }; + + // Position of end of integer type, next byte is the start of the next value + let absolute_end_pos = pos + relative_end_pos; + let next_pos = absolute_end_pos + 1; + match int_str.parse::() { + Ok(n) => Ok((n, next_pos)), + Err(_) => Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidIntParseError { + pos, + })), + } +} + +fn decode_bytes(bytes: &[u8], pos: usize) -> BencodeParseResult<(&[u8], usize)> { + let (num_bytes, start_pos) = decode_int(bytes, pos, crate::BYTE_LEN_END)?; + + if num_bytes < 0 { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidLengthNegative { + pos, + })); + } + + // Should be safe to cast to usize (TODO: Check if cast would overflow to provide + // a more helpful error message, otherwise, parsing will probably fail with an + // unrelated message). + let num_bytes = + usize::try_from(num_bytes).map_err(|_| BencodeParseErrorKind::Msg(format!("input length is too long: {num_bytes}")))?; + + if num_bytes > bytes[start_pos..].len() { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidLengthOverflow { + pos, + })); + } + + let next_pos = start_pos + num_bytes; + Ok((&bytes[start_pos..next_pos], next_pos)) +} + +fn decode_list(bytes: &[u8], pos: usize, opts: BDecodeOpt, depth: usize) -> BencodeParseResult<(Vec>, usize)> { + let mut bencode_list = Vec::new(); + + let mut curr_pos = pos; + let mut curr_byte = peek_byte(bytes, curr_pos)?; + + while curr_byte != crate::BEN_END { + let (bencode, next_pos) = decode(bytes, curr_pos, opts, depth + 1)?; + + bencode_list.push(bencode); + + curr_pos = next_pos; + curr_byte = peek_byte(bytes, curr_pos)?; + } + + let next_pos = curr_pos + 1; + Ok((bencode_list, next_pos)) +} + +fn decode_dict( + bytes: &[u8], + pos: usize, + opts: BDecodeOpt, + depth: usize, +) -> BencodeParseResult<(BTreeMap<&[u8], BencodeRef<'_>>, usize)> { + let mut bencode_dict = BTreeMap::new(); + + let mut curr_pos = pos; + let mut curr_byte = peek_byte(bytes, curr_pos)?; + + while curr_byte != crate::BEN_END { + let (key_bytes, next_pos) = decode_bytes(bytes, curr_pos)?; + + // Spec says that the keys must be in alphabetical order + match (bencode_dict.keys().last(), opts.check_key_sort()) { + (Some(last_key), true) if key_bytes < *last_key => { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidKeyOrdering { + pos: curr_pos, + key: key_bytes.to_vec(), + })) + } + _ => (), + }; + curr_pos = next_pos; + + let (value, next_pos) = decode(bytes, curr_pos, opts, depth + 1)?; + match bencode_dict.entry(key_bytes) { + Entry::Vacant(n) => n.insert(value), + Entry::Occupied(_) => { + return Err(BencodeParseError::from_kind(BencodeParseErrorKind::InvalidKeyDuplicates { + pos: curr_pos, + key: key_bytes.to_vec(), + })) + } + }; + + curr_pos = next_pos; + curr_byte = peek_byte(bytes, curr_pos)?; + } + + let next_pos = curr_pos + 1; + Ok((bencode_dict, next_pos)) +} + +fn peek_byte(bytes: &[u8], pos: usize) -> BencodeParseResult { + bytes + .get(pos) + .copied() + .ok_or_else(|| BencodeParseError::from_kind(BencodeParseErrorKind::BytesEmpty { pos })) +} + +#[cfg(test)] +mod tests { + use std::default::Default; + + use crate::access::bencode::BRefAccess; + use crate::reference::bencode_ref::BencodeRef; + use crate::reference::decode_opt::BDecodeOpt; + + /* cSpell:disable */ + // Positive Cases + const GENERAL: &[u8] = b"d0:12:zero_len_key8:location17:udp://test.com:8011:nested dictd4:listli-500500eee6:numberi500500ee"; + const RECURSION: &[u8] = b"lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; + const BYTES_UTF8: &[u8] = b"16:valid_utf8_bytes"; + const DICTIONARY: &[u8] = b"d9:test_dictd10:nested_key12:nested_value11:nested_listli500ei-500ei0eee8:test_key10:test_valuee"; + const LIST: &[u8] = b"l10:test_bytesi500ei0ei-500el12:nested_bytesed8:test_key10:test_valueee"; + const BYTES: &[u8] = b"5:\xC5\xE6\xBE\xE6\xF2"; + const BYTES_ZERO_LEN: &[u8] = b"0:"; + const INT: &[u8] = b"i500e"; + const INT_NEGATIVE: &[u8] = b"i-500e"; + const INT_ZERO: &[u8] = b"i0e"; + const PARTIAL: &[u8] = b"i0e_asd"; + + // Negative Cases + const BYTES_NEG_LEN: &[u8] = b"-4:test"; + const BYTES_EXTRA: &[u8] = b"l15:processed_bytese17:unprocessed_bytes"; + const BYTES_NOT_UTF8: &[u8] = b"5:\xC5\xE6\xBE\xE6\xF2"; + const INT_NAN: &[u8] = b"i500a500e"; + const INT_LEADING_ZERO: &[u8] = b"i0500e"; + const INT_DOUBLE_ZERO: &[u8] = b"i00e"; + const INT_NEGATIVE_ZERO: &[u8] = b"i-0e"; + const INT_DOUBLE_NEGATIVE: &[u8] = b"i--5e"; + const DICT_UNORDERED_KEYS: &[u8] = b"d5:z_key5:value5:a_key5:valuee"; + const DICT_DUP_KEYS_SAME_DATA: &[u8] = b"d5:a_keyi0e5:a_keyi0ee"; + const DICT_DUP_KEYS_DIFF_DATA: &[u8] = b"d5:a_keyi0e5:a_key7:a_valuee"; + /* cSpell:enable */ + + #[test] + fn positive_decode_general() { + let bencode = BencodeRef::decode(GENERAL, BDecodeOpt::default()).unwrap(); + + let ben_dict = bencode.dict().unwrap(); + assert_eq!(ben_dict.lookup("".as_bytes()).unwrap().str().unwrap(), "zero_len_key"); + assert_eq!( + ben_dict.lookup("location".as_bytes()).unwrap().str().unwrap(), + "udp://test.com:80" + ); + assert_eq!(ben_dict.lookup("number".as_bytes()).unwrap().int().unwrap(), 500_500_i64); + + let nested_dict = ben_dict.lookup("nested dict".as_bytes()).unwrap().dict().unwrap(); + let nested_list = nested_dict.lookup("list".as_bytes()).unwrap().list().unwrap(); + assert_eq!(nested_list[0].int().unwrap(), -500_500_i64); + } + + #[test] + fn positive_decode_recursion() { + BencodeRef::decode(RECURSION, BDecodeOpt::new(50, true, true)).unwrap_err(); + + // As long as we didn't overflow our call stack, we are good! + } + + #[test] + fn positive_decode_bytes_utf8() { + let bencode = BencodeRef::decode(BYTES_UTF8, BDecodeOpt::default()).unwrap(); + + assert_eq!(bencode.str().unwrap(), "valid_utf8_bytes"); + } + + #[test] + fn positive_decode_dict() { + let bencode = BencodeRef::decode(DICTIONARY, BDecodeOpt::default()).unwrap(); + let dict = bencode.dict().unwrap(); + assert_eq!(dict.lookup("test_key".as_bytes()).unwrap().str().unwrap(), "test_value"); + + let nested_dict = dict.lookup("test_dict".as_bytes()).unwrap().dict().unwrap(); + assert_eq!( + nested_dict.lookup("nested_key".as_bytes()).unwrap().str().unwrap(), + "nested_value" + ); + + let nested_list = nested_dict.lookup("nested_list".as_bytes()).unwrap().list().unwrap(); + assert_eq!(nested_list[0].int().unwrap(), 500i64); + assert_eq!(nested_list[1].int().unwrap(), -500i64); + assert_eq!(nested_list[2].int().unwrap(), 0i64); + } + + #[test] + fn positive_decode_list() { + let bencode = BencodeRef::decode(LIST, BDecodeOpt::default()).unwrap(); + let list = bencode.list().unwrap(); + + assert_eq!(list[0].str().unwrap(), "test_bytes"); + assert_eq!(list[1].int().unwrap(), 500i64); + assert_eq!(list[2].int().unwrap(), 0i64); + assert_eq!(list[3].int().unwrap(), -500i64); + + let nested_list = list[4].list().unwrap(); + assert_eq!(nested_list[0].str().unwrap(), "nested_bytes"); + + let nested_dict = list[5].dict().unwrap(); + assert_eq!( + nested_dict.lookup("test_key".as_bytes()).unwrap().str().unwrap(), + "test_value" + ); + } + + #[test] + fn positive_decode_bytes() { + let bytes = super::decode_bytes(BYTES, 0).unwrap().0; + assert_eq!(bytes.len(), 5); + assert_eq!(bytes[0] as char, 'Å'); + assert_eq!(bytes[1] as char, 'æ'); + assert_eq!(bytes[2] as char, '¾'); + assert_eq!(bytes[3] as char, 'æ'); + assert_eq!(bytes[4] as char, 'ò'); + } + + #[test] + fn positive_decode_bytes_zero_len() { + let bytes = super::decode_bytes(BYTES_ZERO_LEN, 0).unwrap().0; + assert_eq!(bytes.len(), 0); + } + + #[test] + fn positive_decode_int() { + let int_value = super::decode_int(INT, 1, crate::BEN_END).unwrap().0; + assert_eq!(int_value, 500i64); + } + + #[test] + fn positive_decode_int_negative() { + let int_value = super::decode_int(INT_NEGATIVE, 1, crate::BEN_END).unwrap().0; + assert_eq!(int_value, -500i64); + } + + #[test] + fn positive_decode_int_zero() { + let int_value = super::decode_int(INT_ZERO, 1, crate::BEN_END).unwrap().0; + assert_eq!(int_value, 0i64); + } + + #[test] + fn positive_decode_partial() { + let bencode = BencodeRef::decode(PARTIAL, BDecodeOpt::new(2, true, false)).unwrap(); + + assert_ne!(PARTIAL.len(), bencode.buffer().len()); + assert_eq!(3, bencode.buffer().len()); + } + + #[test] + fn positive_decode_dict_unordered_keys() { + BencodeRef::decode(DICT_UNORDERED_KEYS, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic = "BencodeParseError(InvalidByte { pos: 0 }"] + fn negative_decode_bytes_neg_len() { + BencodeRef::decode(BYTES_NEG_LEN, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic = "BencodeParseError(BytesEmpty { pos: 20 }"] + fn negative_decode_bytes_extra() { + BencodeRef::decode(BYTES_EXTRA, BDecodeOpt::default()).unwrap(); + } + + #[test] + fn negative_decode_bytes_not_utf8() { + let bencode = BencodeRef::decode(BYTES_NOT_UTF8, BDecodeOpt::default()).unwrap(); + + assert!(bencode.str().is_none()); + } + + #[test] + #[should_panic = "BencodeParseError(InvalidIntParseError { pos: 1 }"] + fn negative_decode_int_nan() { + super::decode_int(INT_NAN, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = "BencodeParseError(InvalidIntZeroPadding { pos: 1 }"] + fn negative_decode_int_leading_zero() { + super::decode_int(INT_LEADING_ZERO, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = "BencodeParseError(InvalidIntZeroPadding { pos: 1 }"] + fn negative_decode_int_double_zero() { + super::decode_int(INT_DOUBLE_ZERO, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = "BencodeParseError(InvalidIntNegativeZero { pos: 1 }"] + fn negative_decode_int_negative_zero() { + super::decode_int(INT_NEGATIVE_ZERO, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = " BencodeParseError(InvalidIntParseError { pos: 1 }"] + fn negative_decode_int_double_negative() { + super::decode_int(INT_DOUBLE_NEGATIVE, 1, crate::BEN_END).unwrap(); + } + + #[test] + #[should_panic = "BencodeParseError(InvalidKeyOrdering { pos: 15, key: [97, 95, 107, 101, 121] }"] + fn negative_decode_dict_unordered_keys() { + BencodeRef::decode(DICT_UNORDERED_KEYS, BDecodeOpt::new(5, true, true)).unwrap(); + } + + #[test] + #[should_panic = "BencodeParseError(InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] + fn negative_decode_dict_dup_keys_same_data() { + BencodeRef::decode(DICT_DUP_KEYS_SAME_DATA, BDecodeOpt::default()).unwrap(); + } + + #[test] + #[should_panic = "BencodeParseError(InvalidKeyDuplicates { pos: 18, key: [97, 95, 107, 101, 121] }"] + fn negative_decode_dict_dup_keys_diff_data() { + BencodeRef::decode(DICT_DUP_KEYS_DIFF_DATA, BDecodeOpt::default()).unwrap(); + } +} diff --git a/contrib/bencode/src/reference/decode_opt.rs b/contrib/bencode/src/reference/decode_opt.rs new file mode 100644 index 000000000..ac94d0311 --- /dev/null +++ b/contrib/bencode/src/reference/decode_opt.rs @@ -0,0 +1,55 @@ +use std::default::Default; + +const DEFAULT_MAX_RECURSION: usize = 50; +const DEFAULT_CHECK_KEY_SORT: bool = false; +const DEFAULT_ENFORCE_FULL_DECODE: bool = true; + +/// Stores decoding options for modifying decode behavior. +#[derive(Copy, Clone)] +#[allow(clippy::module_name_repetitions)] +pub struct BDecodeOpt { + max_recursion: usize, + check_key_sort: bool, + enforce_full_decode: bool, +} + +impl BDecodeOpt { + /// Create a new `BDecodeOpt` object. + #[must_use] + pub fn new(max_recursion: usize, check_key_sort: bool, enforce_full_decode: bool) -> BDecodeOpt { + BDecodeOpt { + max_recursion, + check_key_sort, + enforce_full_decode, + } + } + + /// Maximum limit allowed when decoding bencode. + #[must_use] + pub fn max_recursion(&self) -> usize { + self.max_recursion + } + + /// Whether or not an error should be thrown for out of order dictionary keys. + #[must_use] + pub fn check_key_sort(&self) -> bool { + self.check_key_sort + } + + /// Whether or not we enforce that the decoded bencode must make up all of the input + /// bytes or not. + /// + /// It may be useful to disable this if for example, the input bencode is prepended to + /// some payload and you would like to disassociate it. In this case, to find where the + /// rest of the payload starts that wasn't decoded, get the bencode buffer, and call len(). + #[must_use] + pub fn enforce_full_decode(&self) -> bool { + self.enforce_full_decode + } +} + +impl Default for BDecodeOpt { + fn default() -> BDecodeOpt { + BDecodeOpt::new(DEFAULT_MAX_RECURSION, DEFAULT_CHECK_KEY_SORT, DEFAULT_ENFORCE_FULL_DECODE) + } +} diff --git a/contrib/bencode/src/reference/mod.rs b/contrib/bencode/src/reference/mod.rs new file mode 100644 index 000000000..6a0ae6e40 --- /dev/null +++ b/contrib/bencode/src/reference/mod.rs @@ -0,0 +1,3 @@ +pub mod bencode_ref; +pub mod decode; +pub mod decode_opt; diff --git a/contrib/bencode/test/mod.rs b/contrib/bencode/test/mod.rs new file mode 100644 index 000000000..14606c175 --- /dev/null +++ b/contrib/bencode/test/mod.rs @@ -0,0 +1,18 @@ +use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map}; + +#[test] +fn positive_ben_map_macro() { + let result = (ben_map! { + "key" => ben_bytes!("value") + }) + .encode(); + + assert_eq!("d3:key5:valuee".as_bytes(), &result[..]); // cspell:disable-line +} + +#[test] +fn positive_ben_list_macro() { + let result = (ben_list!(ben_int!(5))).encode(); + + assert_eq!("li5ee".as_bytes(), &result[..]); // cspell:disable-line +} diff --git a/contrib/dev-tools/containers/docker-build.sh b/contrib/dev-tools/containers/docker-build.sh new file mode 100755 index 000000000..39143910f --- /dev/null +++ b/contrib/dev-tools/containers/docker-build.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +echo "Building docker image ..." + +docker build --target release --tag torrust-tracker:release --file Containerfile . diff --git a/contrib/dev-tools/containers/docker-install.sh b/contrib/dev-tools/containers/docker-install.sh new file mode 100755 index 000000000..6034e8233 --- /dev/null +++ b/contrib/dev-tools/containers/docker-install.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +./contrib/dev-tools/containers/docker-build.sh diff --git a/contrib/dev-tools/containers/docker-run-local.sh b/contrib/dev-tools/containers/docker-run-local.sh new file mode 100755 index 000000000..05e23f4a0 --- /dev/null +++ b/contrib/dev-tools/containers/docker-run-local.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +docker run -it \ + --env USER_ID"$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:rw \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:rw \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:rw \ + torrust-tracker:release diff --git a/contrib/dev-tools/containers/docker-run-public.sh b/contrib/dev-tools/containers/docker-run-public.sh new file mode 100755 index 000000000..73bcf600a --- /dev/null +++ b/contrib/dev-tools/containers/docker-run-public.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +docker run -it \ + --env USER_ID"$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:rw \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:rw \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:rw \ + torrust/tracker:latest diff --git a/contrib/dev-tools/init/install-local.sh b/contrib/dev-tools/init/install-local.sh new file mode 100755 index 000000000..f9806a0b8 --- /dev/null +++ b/contrib/dev-tools/init/install-local.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +# This script is only intended to be used for local development or testing environments. + +# Generate storage directory if it does not exist +mkdir -p ./storage/tracker/lib/database + +# Generate the sqlite database if it does not exist +if ! [ -f "./storage/tracker/lib/database/sqlite3.db" ]; then + # todo: it should get the path from tracker.toml and only do it when we use sqlite + sqlite3 ./storage/tracker/lib/database/sqlite3.db "VACUUM;" +fi diff --git a/contrib/dev-tools/su-exec/LICENSE b/contrib/dev-tools/su-exec/LICENSE new file mode 100644 index 000000000..f623b904e --- /dev/null +++ b/contrib/dev-tools/su-exec/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 ncopa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/contrib/dev-tools/su-exec/Makefile b/contrib/dev-tools/su-exec/Makefile new file mode 100644 index 000000000..bda768957 --- /dev/null +++ b/contrib/dev-tools/su-exec/Makefile @@ -0,0 +1,17 @@ + +CFLAGS ?= -Wall -Werror -g +LDFLAGS ?= + +PROG := su-exec +SRCS := $(PROG).c + +all: $(PROG) + +$(PROG): $(SRCS) + $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) + +$(PROG)-static: $(SRCS) + $(CC) $(CFLAGS) -o $@ $^ -static $(LDFLAGS) + +clean: + rm -f $(PROG) $(PROG)-static diff --git a/contrib/dev-tools/su-exec/README.md b/contrib/dev-tools/su-exec/README.md new file mode 100644 index 000000000..2b0517377 --- /dev/null +++ b/contrib/dev-tools/su-exec/README.md @@ -0,0 +1,46 @@ +# su-exec +switch user and group id, setgroups and exec + +## Purpose + +This is a simple tool that will simply execute a program with different +privileges. The program will be executed directly and not run as a child, +like su and sudo does, which avoids TTY and signal issues (see below). + +Notice that su-exec depends on being run by the root user, non-root +users do not have permission to change uid/gid. + +## Usage + +```shell +su-exec user-spec command [ arguments... ] +``` + +`user-spec` is either a user name (e.g. `nobody`) or user name and group +name separated with colon (e.g. `nobody:ftp`). Numeric uid/gid values +can be used instead of names. Example: + +```shell +$ su-exec apache:1000 /usr/sbin/httpd -f /opt/www/httpd.conf +``` + +## TTY & parent/child handling + +Notice how `su` will make `ps` be a child of a shell while `su-exec` +just executes `ps` directly. + +```shell +$ docker run -it --rm alpine:edge su postgres -c 'ps aux' +PID USER TIME COMMAND + 1 postgres 0:00 ash -c ps aux + 12 postgres 0:00 ps aux +$ docker run -it --rm -v $PWD/su-exec:/sbin/su-exec:ro alpine:edge su-exec postgres ps aux +PID USER TIME COMMAND + 1 postgres 0:00 ps aux +``` + +## Why reinvent gosu? + +This does more or less exactly the same thing as [gosu](https://github.com/tianon/gosu) +but it is only 10kb instead of 1.8MB. + diff --git a/contrib/dev-tools/su-exec/su-exec.c b/contrib/dev-tools/su-exec/su-exec.c new file mode 100644 index 000000000..499071c6e --- /dev/null +++ b/contrib/dev-tools/su-exec/su-exec.c @@ -0,0 +1,109 @@ +/* set user and group id and exec */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +static char *argv0; + +static void usage(int exitcode) +{ + printf("Usage: %s user-spec command [args]\n", argv0); + exit(exitcode); +} + +int main(int argc, char *argv[]) +{ + char *user, *group, **cmdargv; + char *end; + + uid_t uid = getuid(); + gid_t gid = getgid(); + + argv0 = argv[0]; + if (argc < 3) + usage(0); + + user = argv[1]; + group = strchr(user, ':'); + if (group) + *group++ = '\0'; + + cmdargv = &argv[2]; + + struct passwd *pw = NULL; + if (user[0] != '\0') { + uid_t nuid = strtol(user, &end, 10); + if (*end == '\0') + uid = nuid; + else { + pw = getpwnam(user); + if (pw == NULL) + err(1, "getpwnam(%s)", user); + } + } + if (pw == NULL) { + pw = getpwuid(uid); + } + if (pw != NULL) { + uid = pw->pw_uid; + gid = pw->pw_gid; + } + + setenv("HOME", pw != NULL ? pw->pw_dir : "/", 1); + + if (group && group[0] != '\0') { + /* group was specified, ignore grouplist for setgroups later */ + pw = NULL; + + gid_t ngid = strtol(group, &end, 10); + if (*end == '\0') + gid = ngid; + else { + struct group *gr = getgrnam(group); + if (gr == NULL) + err(1, "getgrnam(%s)", group); + gid = gr->gr_gid; + } + } + + if (pw == NULL) { + if (setgroups(1, &gid) < 0) + err(1, "setgroups(%i)", gid); + } else { + int ngroups = 0; + gid_t *glist = NULL; + + while (1) { + int r = getgrouplist(pw->pw_name, gid, glist, &ngroups); + + if (r >= 0) { + if (setgroups(ngroups, glist) < 0) + err(1, "setgroups"); + break; + } + + glist = realloc(glist, ngroups * sizeof(gid_t)); + if (glist == NULL) + err(1, "malloc"); + } + } + + if (setgid(gid) < 0) + err(1, "setgid(%i)", gid); + + if (setuid(uid) < 0) + err(1, "setuid(%i)", uid); + + execvp(cmdargv[0], cmdargv); + err(1, "%s", cmdargv[0]); + + return 1; +} diff --git a/docker/README.md b/docker/README.md deleted file mode 100644 index e0fee61e7..000000000 --- a/docker/README.md +++ /dev/null @@ -1,261 +0,0 @@ -# Docker - -## Requirements - -- Docker version 20.10.21 -- You need to create the `storage` directory with this structure and files: - -```s -$ tree storage/ -storage/ -├── database -│   └── data.db -└── ssl_certificates - ├── localhost.crt - └── localhost.key -``` - -> NOTE: you only need the `ssl_certificates` directory and certificates in case you have enabled SSL for the one HTTP tracker or the API. - -## Dev environment - -When using docker you have to bind the exposed ports to the wildcard address `0.0.0.0`, so you can access the application from the host machine. - -The default API configuration uses `127.0.0.1`, so you have to change it to: - -```toml -[http_api] -bind_address = "0.0.0.0:1212" -``` - -Otherwise the API will be only accessible from inside the container. - -### With docker - -Build and run locally: - -```s -docker context use default -export TORRUST_TRACKER_USER_UID=1000 -./docker/bin/build.sh $TORRUST_TRACKER_USER_UID -./bin/install.sh -./docker/bin/run.sh $TORRUST_TRACKER_USER_UID -``` - -Run using the pre-built public docker image: - -```s -export TORRUST_TRACKER_USER_UID=1000 -docker run -it \ - --user="$TORRUST_TRACKER_USER_UID" \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --volume "$(pwd)/storage":"/app/storage" \ - torrust/tracker -``` - -> NOTES: -> -> - You have to create the SQLite DB (`data.db`) and configuration (`config.toml`) before running the tracker. See `bin/install.sh`. -> - You have to replace the user UID (`1000`) with yours. -> - Remember to switch to your default docker context `docker context use default`. - -### With docker-compose - -The docker-compose configuration includes the MySQL service configuration. If you want to use MySQL instead of SQLite you have to change your `config.toml` configuration: - -```toml -db_driver = "MySQL" -db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" -``` - -If you want to inject an environment variable into docker-compose you can use the file `.env`. There is a template `.env.local`. - -Build and run it locally: - -```s -docker compose up --build -``` - -After running the "up" command you will have two running containers: - -```s -$ docker ps -CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES -06feacb91a9e torrust-tracker "cargo run" 18 minutes ago Up 4 seconds 0.0.0.0:1212->1212/tcp, :::1212->1212/tcp, 0.0.0.0:7070->7070/tcp, :::7070->7070/tcp, 0.0.0.0:6969->6969/udp, :::6969->6969/udp torrust-tracker-1 -34d29e792ee2 mysql:8.0 "docker-entrypoint.s…" 18 minutes ago Up 5 seconds (healthy) 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp torrust-mysql-1 -``` - -And you should be able to use the application, for example making a request to the API: - - - -You can stop the containers with: - -```s -docker compose down -``` - -Additionally, you can delete all resources (containers, volumes, networks) with: - -```s -docker compose down -v -``` - -### Access Mysql with docker - -These are some useful commands for MySQL. - -Open a shell in the MySQL container using docker or docker-compose. - -```s -docker exec -it torrust-mysql-1 /bin/bash -docker compose exec mysql /bin/bash -``` - -Connect to MySQL from inside the MySQL container or from the host: - -```s -mysql -h127.0.0.1 -uroot -proot_secret_password -``` - -The when MySQL container is started the first time, it creates the database, user, and permissions needed. -If you see the error "Host is not allowed to connect to this MySQL server" you can check that users have the right permissions in the database. Make sure the user `root` and `db_user` can connect from any host (`%`). - -```s -mysql> SELECT host, user FROM mysql.user; -+-----------+------------------+ -| host | user | -+-----------+------------------+ -| % | db_user | -| % | root | -| localhost | mysql.infoschema | -| localhost | mysql.session | -| localhost | mysql.sys | -| localhost | root | -+-----------+------------------+ -6 rows in set (0.00 sec) -``` - -If the database, user or permissions are not created the reason could be the MySQL container volume can be corrupted. Delete it and start again the containers. - -### SSL Certificates - -You can use a certificate for localhost. You can create your [localhost certificate](https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates) and use it in the `storage` folder and the configuration file (`config.toml`). For example: - -The storage folder must contain your certificates: - -```s -$ tree storage/ -storage/ -├── database -│   └── data.db -└── ssl_certificates - ├── localhost.crt - └── localhost.key -``` - -You have not enabled it in your `config.toml` file: - -```toml -... -[[http_trackers]] -enabled = true -bind_address = "0.0.0.0:7070" -ssl_enabled = true -ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -ssl_key_path = "./storage/ssl_certificates/localhost.key" - -[http_api] -enabled = true -bind_address = "0.0.0.0:1212" -ssl_enabled = true -ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -ssl_key_path = "./storage/ssl_certificates/localhost.key" -... -``` - -> NOTE: you can enable it independently for each HTTP tracker or the API. - -If you enable the SSL certificate for the API, for example, you can load the API with this URL: - - - -## Prod environment - -In this section, you will learn how to deploy the tracker to a single docker container in Azure Container Instances. - -> NOTE: Azure Container Instances is a solution when you want to run an isolated container. If you need full container orchestration, including service discovery across multiple containers, automatic scaling, and coordinated application upgrades, we recommend [Kubernetes](https://kubernetes.io/). - -Deploy to Azure Container Instance following [docker documentation](https://docs.docker.com/cloud/aci-integration/). - -You have to create the ACI context and the storage: - -```s -docker context create aci myacicontext -docker context use myacicontext -docker volume create test-volume --storage-account torrustracker -``` - -You need to create all the files needed by the application in the storage dir `storage/database`. - -And finally, you can run the container: - -```s -docker run \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --volume torrustracker/test-volume:/app/storage \ - registry.hub.docker.com/torrust/tracker:latest -``` - -Detach from container logs when the container starts. By default, the command line stays attached and follows container logs. - -```s -docker run \ - --detach - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \latest - --volume torrustracker/test-volume:/app/storage \ - registry.hub.docker.com/torrust/tracker:latest -``` - -You should see something like this: - -```s -[+] Running 2/2 - ⠿ Group intelligent-hawking Created 5.0s - ⠿ intelligent-hawking Created 41.7s -2022-12-08T18:39:19.697869300+00:00 [torrust_tracker::logging][INFO] logging initialized. -2022-12-08T18:39:19.712651100+00:00 [torrust_tracker::jobs::udp_tracker][INFO] Starting UDP server on: 0.0.0.0:6969 -2022-12-08T18:39:19.712792700+00:00 [torrust_tracker::jobs::tracker_api][INFO] Starting Torrust API server on: 0.0.0.0:1212 -2022-12-08T18:39:19.725124+00:00 [torrust_tracker::jobs::tracker_api][INFO] Torrust API server started -``` - -You can see the container with: - -```s -$ docker ps -CONTAINER ID IMAGE COMMAND STATUS PORTS -intelligent-hawking registry.hub.docker.com/torrust/tracker:latest Running 4.236.213.57:6969->6969/udp, 4.236.213.57:1212->1212/tcp -``` - -After a while, you can use the tracker API `http://4.236.213.57:1212/api/v1/stats?token=MyAccessToken` and the UDP tracker with your BitTorrent client using this tracker announce URL `udp://4.236.213.57:6969`. - -> NOTES: -> -> - [There is no support for mounting a single file](https://docs.docker.com/cloud/aci-container-features/#persistent-volumes), or mounting a subfolder from an `Azure File Share`. -> - [ACI does not allow port mapping](https://docs.docker.com/cloud/aci-integration/#exposing-ports). -> - [Azure file share volume mount requires the Linux container run as root](https://learn.microsoft.com/en-us/azure/container-instances/container-instances-volume-azure-files#limitations). -> - It can take some minutes until the public IP for the ACI container is available. -> - You can use the Azure web UI to download files from the storage. For example, the SQLite database. -> - [It seems you can only expose web interfaces on port 80 on Azure Container Instances](https://stackoverflow.com/a/56768087/3012842). Not official documentation! - -## Links - -- [Deploying Docker containers on Azure](https://docs.docker.com/cloud/aci-integration/). -- [Docker run options for ACI containers](https://docs.docker.com/cloud/aci-container-features/). -- [Quickstart: Deploy a container instance in Azure using the Docker CLI](https://learn.microsoft.com/en-us/azure/container-instances/quickstart-docker-cli). diff --git a/docker/bin/build.sh b/docker/bin/build.sh deleted file mode 100755 index d77d1ad34..000000000 --- a/docker/bin/build.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -TORRUST_TRACKER_USER_UID=${TORRUST_TRACKER_USER_UID:-1000} -TORRUST_TRACKER_RUN_AS_USER=${TORRUST_TRACKER_RUN_AS_USER:-appuser} - -echo "Building docker image ..." -echo "TORRUST_TRACKER_USER_UID: $TORRUST_TRACKER_USER_UID" -echo "TORRUST_TRACKER_RUN_AS_USER: $TORRUST_TRACKER_RUN_AS_USER" - -docker build \ - --build-arg UID="$TORRUST_TRACKER_USER_UID" \ - --build-arg RUN_AS_USER="$TORRUST_TRACKER_RUN_AS_USER" \ - -t torrust-tracker . diff --git a/docker/bin/install.sh b/docker/bin/install.sh deleted file mode 100755 index a58969378..000000000 --- a/docker/bin/install.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash - -./docker/bin/build.sh -./bin/install.sh diff --git a/docker/bin/run.sh b/docker/bin/run.sh deleted file mode 100755 index 86465baeb..000000000 --- a/docker/bin/run.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash - -TORRUST_TRACKER_USER_UID=${TORRUST_TRACKER_USER_UID:-1000} -TORRUST_TRACKER_CONFIG=$(cat config.toml) - -docker run -it \ - --user="$TORRUST_TRACKER_USER_UID" \ - --publish 6969:6969/udp \ - --publish 7070:7070/tcp \ - --publish 1212:1212/tcp \ - --env TORRUST_TRACKER_CONFIG="$TORRUST_TRACKER_CONFIG" \ - --volume "$(pwd)/storage":"/app/storage" \ - torrust-tracker diff --git a/docs/containers.md b/docs/containers.md new file mode 100644 index 000000000..737ce40a0 --- /dev/null +++ b/docs/containers.md @@ -0,0 +1,430 @@ +# Containers (Docker or Podman) + +## Demo environment +It is simple to setup the tracker with the default +configuration and run it using the pre-built public docker image: + + +With Docker: + +```sh +docker run -it torrust/tracker:latest +``` + +or with Podman: + +```sh +podman run -it torrust/tracker:latest +``` + + +## Requirements +- Tested with recent versions of Docker or Podman. + +## Volumes +The [Containerfile](../Containerfile) (i.e. the Dockerfile) Defines Three Volumes: + +```Dockerfile +VOLUME ["/var/lib/torrust/tracker","/var/log/torrust/tracker","/etc/torrust/tracker"] +``` + +When instancing the container image with the `docker run` or `podman run` command, we map these volumes to the local storage: + +```s +./storage/tracker/lib -> /var/lib/torrust/tracker +./storage/tracker/log -> /var/log/torrust/tracker +./storage/tracker/etc -> /etc/torrust/tracker +``` + +> NOTE: You can adjust this mapping for your preference, however this mapping is the default in our guides and scripts. + +### Pre-Create Host-Mapped Folders: +Please run this command where you wish to run the container: + +```sh +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ +``` + +### Matching Ownership ID's of Host Storage and Container Volumes +It is important that the `torrust` user has the same uid `$(id -u)` as the host mapped folders. In our [entry script](../share/container/entry_script_sh), installed to `/usr/local/bin/entry.sh` inside the container, switches to the `torrust` user created based upon the `USER_UID` environmental variable. + +When running the container, you may use the `--env USER_ID="$(id -u)"` argument that gets the current user-id and passes to the container. + +### Mapped Tree Structure +Using the standard mapping defined above produces this following mapped tree: + +```s +storage/tracker/ +├── lib +│ ├── database +│ │   └── sqlite3.db => /var/lib/torrust/tracker/database/sqlite3.db [auto populated] +│ └── tls +│ ├── localhost.crt => /var/lib/torrust/tracker/tls/localhost.crt [user supplied] +│ └── localhost.key => /var/lib/torrust/tracker/tls/localhost.key [user supplied] +├── log => /var/log/torrust/tracker (future use) +└── etc + └── tracker.toml => /etc/torrust/tracker/tracker.toml [auto populated] +``` + +> NOTE: you only need the `tls` directory and certificates in case you have enabled SSL. + +## Building the Container + +### Clone and Change into Repository + +```sh +# Inside your dev folder +git clone https://github.com/torrust/torrust-tracker.git; cd torrust-tracker +``` + +### (Docker) Setup Context +Before starting, if you are using docker, it is helpful to reset the context to the default: + +```sh +docker context use default +``` + +### (Docker) Build + +```sh +# Release Mode +docker build --target release --tag torrust-tracker:release --file Containerfile . + +# Debug Mode +docker build --target debug --tag torrust-tracker:debug --file Containerfile . +``` + +### (Podman) Build + +```sh +# Release Mode +podman build --target release --tag torrust-tracker:release --file Containerfile . + +# Debug Mode +podman build --target debug --tag torrust-tracker:debug --file Containerfile . +``` + +## Running the Container + +### Basic Run +No arguments are needed for simply checking the container image works: + +#### (Docker) Run Basic + +```sh +# Release Mode +docker run -it torrust-tracker:release + +# Debug Mode +docker run -it torrust-tracker:debug +``` +#### (Podman) Run Basic + +```sh +# Release Mode +podman run -it torrust-tracker:release + +# Debug Mode +podman run -it torrust-tracker:debug +``` + +### Arguments +The arguments need to be placed before the image tag. i.e. + +`run [arguments] torrust-tracker:release` + +#### Environmental Variables: +Environmental variables are loaded through the `--env`, in the format `--env VAR="value"`. + +The following environmental variables can be set: + +- `TORRUST_TRACKER_PATH_CONFIG` - The in-container path to the tracker configuration file, (default: `"/etc/torrust/tracker/tracker.toml"`). +- `TORRUST_TRACKER_API_ADMIN_TOKEN` - Override of the admin token. If set, this value overrides any value set in the config. +- `TORRUST_TRACKER_DATABASE_DRIVER` - The database type used for the container, (options: `sqlite3`, `mysql`, default `sqlite3`). Please Note: This dose not override the database configuration within the `.toml` config file. +- `TORRUST_TRACKER_CONFIG` - Load config from this environmental variable instead from a file, (i.e: `TORRUST_TRACKER_CONFIG=$(cat tracker-tracker.toml)`). +- `USER_ID` - The user id for the runtime crated `torrust` user. Please Note: This user id should match the ownership of the host-mapped volumes, (default `1000`). +- `UDP_PORT` - The port for the UDP tracker. This should match the port used in the configuration, (default `6969`). +- `HTTP_PORT` - The port for the HTTP tracker. This should match the port used in the configuration, (default `7070`). +- `API_PORT` - The port for the tracker API. This should match the port used in the configuration, (default `1212`). + + +### Sockets +Socket ports used internally within the container can be mapped to with the `--publish` argument. + +The format is: `--publish [optional_host_ip]:[host_port]:[container_port]/[optional_protocol]`, for example: `--publish 127.0.0.1:8080:80/tcp`. + +The default ports can be mapped with the following: + +```s +--publish 0.0.0.0:7070:7070/tcp \ +--publish 0.0.0.0:6969:6969/udp \ +--publish 0.0.0.0:1212:1212/tcp \ +``` + +> NOTE: Inside the container it is necessary to expose a socket with the wildcard address `0.0.0.0` so that it may be accessible from the host. Verify that the configuration that the sockets are wildcard. + +### Volumes +By default the container will use install volumes for `/var/lib/torrust/tracker`, `/var/log/torrust/tracker`, and `/etc/torrust/tracker`, however for better administration it good to make these volumes host-mapped. + +The argument to host-map volumes is `--volume`, with the format: `--volume=[host-src:]container-dest[:]`. + +The default mapping can be supplied with the following arguments: + +```s +--volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ +--volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ +--volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ +``` + + +Please not the `:Z` at the end of the podman `--volume` mapping arguments, this is to give read-write permission on SELinux enabled systemd, if this doesn't work on your system, you can use `:rw` instead. + +## Complete Example: + +### With Docker + +```sh +## Setup Docker Default Context +docker context use default + +## Build Container Image +docker build --target release --tag torrust-tracker:release --file Containerfile . + +## Setup Mapped Volumes +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +## Run Torrust Tracker Container Image +docker run -it \ + --env TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ + --env USER_ID="$(id -u)" \ + --publish 0.0.0.0:7070:7070/tcp \ + --publish 0.0.0.0:6969:6969/udp \ + --publish 0.0.0.0:1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ + torrust-tracker:release +``` + +### With Podman + +```sh +## Build Container Image +podman build --target release --tag torrust-tracker:release --file Containerfile . + +## Setup Mapped Volumes +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +## Run Torrust Tracker Container Image +podman run -it \ + --env TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ + --env USER_ID="$(id -u)" \ + --publish 0.0.0.0:7070:7070/tcp \ + --publish 0.0.0.0:6969:6969/udp \ + --publish 0.0.0.0:1212:1212/tcp \ + --volume ./storage/tracker/lib:/var/lib/torrust/tracker:Z \ + --volume ./storage/tracker/log:/var/log/torrust/tracker:Z \ + --volume ./storage/tracker/etc:/etc/torrust/tracker:Z \ + torrust-tracker:release +``` + +## Docker Compose + +The docker-compose configuration includes the MySQL service configuration. If you want to use MySQL instead of SQLite you should verify the `/etc/torrust/tracker/tracker.toml` (i.e `./storage/tracker/etc/tracker.toml`) configuration: + +```toml +db_driver = "MySQL" +db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" +``` + +### Build and Run: + +```sh +docker build --target release --tag torrust-tracker:release --file Containerfile . + +mkdir -p ./storage/tracker/lib/ ./storage/tracker/log/ ./storage/tracker/etc/ + +USER_ID=$(id -u) \ + TORRUST_TRACKER_API_ADMIN_TOKEN="MySecretToken" \ + docker compose up --build +``` + +After running the `compose up` command you will have two running containers: + +```s +$ docker ps +CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +06feacb91a9e torrust-tracker "cargo run" 18 minutes ago Up 4 seconds 0.0.0.0:1212->1212/tcp, :::1212->1212/tcp, 0.0.0.0:7070->7070/tcp, :::7070->7070/tcp, 0.0.0.0:6969->6969/udp, :::6969->6969/udp torrust-tracker-1 +34d29e792ee2 mysql:8.0 "docker-entrypoint.s…" 18 minutes ago Up 5 seconds (healthy) 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp torrust-mysql-1 +``` + +And you should be able to use the application, for example making a request to the API: + + + +You can stop the containers with: + +```s +docker compose down +``` + +Additionally, you can delete all resources (containers, volumes, networks) with: + +```s +docker compose down -v +``` + +### Access Mysql with docker + +These are some useful commands for MySQL. + +Open a shell in the MySQL container using docker or docker-compose. + +```s +docker exec -it torrust-mysql-1 /bin/bash +docker compose exec mysql /bin/bash +``` + +Connect to MySQL from inside the MySQL container or from the host: + +```s +mysql -h127.0.0.1 -uroot -proot_secret_password +``` + +The when MySQL container is started the first time, it creates the database, user, and permissions needed. +If you see the error "Host is not allowed to connect to this MySQL server" you can check that users have the right permissions in the database. Make sure the user `root` and `db_user` can connect from any host (`%`). + +```s +mysql> SELECT host, user FROM mysql.user; ++-----------+------------------+ +| host | user | ++-----------+------------------+ +| % | db_user | +| % | root | +| localhost | mysql.infoschema | +| localhost | mysql.session | +| localhost | mysql.sys | +| localhost | root | ++-----------+------------------+ +6 rows in set (0.00 sec) +``` + +If the database, user or permissions are not created the reason could be the MySQL container volume can be corrupted. Delete it and start again the containers. + +### SSL Certificates + +You can use a certificate for localhost. You can create your [localhost certificate](https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates) and use it in the `storage` folder and the configuration file (`tracker.toml`). For example: + +The storage folder must contain your certificates: + +```s +storage/tracker/lib/tls + ├── localhost.crt + └── localhost.key +``` + +You have not enabled it in your `tracker.toml` file: + +```toml + +[[http_trackers]] +# ... +ssl_enabled = true +# ... + +[http_api] +# ... +ssl_enabled = true +# ... + +``` + +> NOTE: you can enable it independently for each HTTP tracker or the API. + +If you enable the SSL certificate for the API, for example, you can load the API with this URL: + + + +## Prod environment + +In this section, you will learn how to deploy the tracker to a single docker container in Azure Container Instances. + +> NOTE: Azure Container Instances is a solution when you want to run an isolated container. If you need full container orchestration, including service discovery across multiple containers, automatic scaling, and coordinated application upgrades, we recommend [Kubernetes](https://kubernetes.io/). + +Deploy to Azure Container Instance following [docker documentation](https://docs.docker.com/cloud/aci-integration/). + +You have to create the ACI context and the storage: + +```s +docker context create aci myacicontext +docker context use myacicontext +docker volume create test-volume --storage-account torrustracker +``` + +You need to create all the files needed by the application in the storage dir `storage/lib/database`. + +And finally, you can run the container: + +```s +docker run \ + --env USER_ID="$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \ + --volume torrustracker/lib:/var/lib/torrust/tracker:rw \ + --volume torrustracker/log:/var/log/torrust/tracker:rw \ + --volume torrustracker/etc:/etc/torrust/tracker:rw \ + registry.hub.docker.com/torrust/tracker:latest +``` + +Detach from container logs when the container starts. By default, the command line stays attached and follows container logs. + +```s +docker run \ + --detach + --env USER_ID="$(id -u)" \ + --publish 6969:6969/udp \ + --publish 7070:7070/tcp \ + --publish 1212:1212/tcp \latest + --volume torrustracker/lib:/var/lib/torrust/tracker:rw \ + --volume torrustracker/log:/var/log/torrust/tracker:rw \ + --volume torrustracker/etc:/etc/torrust/tracker:rw \ + registry.hub.docker.com/torrust/tracker:latest +``` + +You should see something like this: + +```s +[+] Running 2/2 + ⠿ Group intelligent-hawking Created 5.0s + ⠿ intelligent-hawking Created 41.7s +2022-12-08T18:39:19.697869300+00:00 [torrust_tracker::logging][INFO] logging initialized. +2022-12-08T18:39:19.712651100+00:00 [torrust_tracker::jobs::udp_tracker][INFO] Starting UDP server on: 0.0.0.0:6969 +2022-12-08T18:39:19.712792700+00:00 [torrust_tracker::jobs::tracker_api][INFO] Starting Torrust API server on: 0.0.0.0:1212 +2022-12-08T18:39:19.725124+00:00 [torrust_tracker::jobs::tracker_api][INFO] Torrust API server started +``` + +You can see the container with: + +```s +$ docker ps +CONTAINER ID IMAGE COMMAND STATUS PORTS +intelligent-hawking registry.hub.docker.com/torrust/tracker:latest Running 4.236.213.57:6969->6969/udp, 4.236.213.57:1212->1212/tcp +``` + +After a while, you can use the tracker API `http://4.236.213.57:1212/api/v1/stats?token=MyAccessToken` and the UDP tracker with your BitTorrent client using this tracker announce URL `udp://4.236.213.57:6969`. + +> NOTES: +> +> - [There is no support for mounting a single file](https://docs.docker.com/cloud/aci-container-features/#persistent-volumes), or mounting a subfolder from an `Azure File Share`. +> - [ACI does not allow port mapping](https://docs.docker.com/cloud/aci-integration/#exposing-ports). +> - [Azure file share volume mount requires the Linux container run as root](https://learn.microsoft.com/en-us/azure/container-instances/container-instances-volume-azure-files#limitations). +> - It can take some minutes until the public IP for the ACI container is available. +> - You can use the Azure web UI to download files from the storage. For example, the SQLite database. +> - [It seems you can only expose web interfaces on port 80 on Azure Container Instances](https://stackoverflow.com/a/56768087/3012842). Not official documentation! + +## Links + +- [Deploying Docker containers on Azure](https://docs.docker.com/cloud/aci-integration/). +- [Docker run options for ACI containers](https://docs.docker.com/cloud/aci-container-features/). +- [Quickstart: Deploy a container instance in Azure using the Docker CLI](https://learn.microsoft.com/en-us/azure/container-instances/quickstart-docker-cli). diff --git a/docs/release_process.md b/docs/release_process.md new file mode 100644 index 000000000..d5d945694 --- /dev/null +++ b/docs/release_process.md @@ -0,0 +1,79 @@ +# Torrust Tracker Release Process (v2.2.1) + +## Version: +> **The `[semantic version]` is bumped according to releases, new features, and breaking changes.** +> +> *The `develop` branch uses the (semantic version) suffix `-develop`.* + +## Process: + +### 1. The `develop` branch is ready for a release. +The `develop` branch should have the version `[semantic version]-develop` that is ready to be released. + +### 2. Stage `develop` HEAD for merging into the `main` branch: + +```sh +git fetch --all +git push --force torrust develop:staging/main +``` + +### 3. Create Release Commit: + +```sh +git stash +git switch staging/main +# change `[semantic version]-develop` to `[semantic version]`. +git add -A +git commit -m "release: version [semantic version]" +git push torrust +``` + +### 4. Create and Merge Pull Request from `staging/main` into `main` branch. + +Pull request title format: "Release Version `[semantic version]`". + +This pull request merges the new version into the `main` branch. + +### 5. Push new version from `main` HEAD to `releases/v[semantic version]` branch: + +```sh +git fetch --all +git push torrust main:releases/v[semantic version] +``` + +> **Check that the deployment is successful!** + +### 6. Create Release Tag: + +```sh +git switch releases/v[semantic version] +git tag --sign v[semantic version] +git push --tags torrust +``` + +### 7. Create Release on Github from Tag. +This is for those who wish to download the source code. + +### 8. Stage `main` HEAD for merging into the `develop` branch: +Merge release back into the develop branch. + +```sh +git fetch --all +git push --force torrust main:staging/develop +``` +### 9. Create Comment that bumps next development version: + +```sh +git stash +git switch staging/main +# change `[semantic version]` to `(next)[semantic version]-develop`. +git add -A +git commit -m "develop: bump to version (next)[semantic version]-develop" +git push torrust +``` + +### 10. Create and Merge Pull Request from `staging/develop` into `develop` branch. + +Pull request title format: "Version `[semantic version]` was Released". + +This pull request merges the new release into the `develop` branch and bumps the version number. diff --git a/packages/configuration/Cargo.toml b/packages/configuration/Cargo.toml index 6f9e5cbc5..b21e64751 100644 --- a/packages/configuration/Cargo.toml +++ b/packages/configuration/Cargo.toml @@ -1,20 +1,28 @@ [package] -name = "torrust-tracker-configuration" description = "A library to provide configuration to the Torrust Tracker." -license = "AGPL-3.0" -version.workspace = true +keywords = ["config", "library", "settings"] +name = "torrust-tracker-configuration" +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license-file.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true [dependencies] -serde = { version = "1.0", features = ["derive"] } -serde_with = "2.0" config = "0.13" -toml = "0.7" log = { version = "0.4", features = ["release_max_level_info"] } +serde = { version = "1.0", features = ["derive"] } +serde_with = "3.2" thiserror = "1.0" -torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "../primitives" } -torrust-tracker-located-error = { version = "3.0.0-alpha.2", path = "../located-error" } +toml = "0.8" +torrust-tracker-located-error = { version = "3.0.0-alpha.10", path = "../located-error" } +torrust-tracker-primitives = { version = "3.0.0-alpha.10", path = "../primitives" } [dev-dependencies] uuid = { version = "1", features = ["v4"] } diff --git a/packages/configuration/src/lib.rs b/packages/configuration/src/lib.rs index e48355757..059316a26 100644 --- a/packages/configuration/src/lib.rs +++ b/packages/configuration/src/lib.rs @@ -4,7 +4,7 @@ //! Torrust Tracker, which is a `BitTorrent` tracker server. //! //! The configuration is loaded from a [TOML](https://toml.io/en/) file -//! `config.toml` in the project root folder or from an environment variable +//! `tracker.toml` in the project root folder or from an environment variable //! with the same content as the file. //! //! When you run the tracker without a configuration file, a new one will be @@ -67,7 +67,7 @@ //! storage/ //! ├── database //! │ └── data.db -//! └── ssl_certificates +//! └── tls //! ├── localhost.crt //! └── localhost.key //! ``` @@ -176,14 +176,14 @@ //! [[http_trackers]] //! enabled = true //! ... -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! //! [http_api] //! enabled = true //! ... -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! ``` //! //! ## Default configuration @@ -194,7 +194,7 @@ //! log_level = "info" //! mode = "public" //! db_driver = "Sqlite3" -//! db_path = "./storage/database/data.db" +//! db_path = "./storage/tracker/lib/database/sqlite3.db" //! announce_interval = 120 //! min_announce_interval = 120 //! max_peer_timeout = 900 @@ -228,20 +228,78 @@ //!``` use std::collections::{HashMap, HashSet}; use std::net::IpAddr; -use std::panic::Location; -use std::path::Path; use std::str::FromStr; use std::sync::Arc; use std::{env, fs}; use config::{Config, ConfigError, File, FileFormat}; -use log::warn; use serde::{Deserialize, Serialize}; use serde_with::{serde_as, NoneAsEmptyString}; use thiserror::Error; use torrust_tracker_located_error::{Located, LocatedError}; use torrust_tracker_primitives::{DatabaseDriver, TrackerMode}; +/// Information required for loading config +#[derive(Debug, Default, Clone)] +pub struct Info { + tracker_toml: String, + api_admin_token: Option, +} + +impl Info { + /// Build Configuration Info + /// + /// # Examples + /// + /// ``` + /// use torrust_tracker_configuration::Info; + /// + /// let result = Info::new(env_var_config, env_var_path_config, default_path_config, env_var_api_admin_token); + /// assert_eq!(result, ); + /// ``` + /// + /// # Errors + /// + /// Will return `Err` if unable to obtain a configuration. + /// + #[allow(clippy::needless_pass_by_value)] + pub fn new( + env_var_config: String, + env_var_path_config: String, + default_path_config: String, + env_var_api_admin_token: String, + ) -> Result { + let tracker_toml = if let Ok(tracker_toml) = env::var(&env_var_config) { + println!("Loading configuration from env var {env_var_config} ..."); + + tracker_toml + } else { + let config_path = if let Ok(config_path) = env::var(env_var_path_config) { + println!("Loading configuration file: `{config_path}` ..."); + + config_path + } else { + println!("Loading default configuration file: `{default_path_config}` ..."); + + default_path_config + }; + + fs::read_to_string(config_path) + .map_err(|e| Error::UnableToLoadFromConfigFile { + source: (Arc::new(e) as Arc).into(), + })? + .parse() + .map_err(|_e: std::convert::Infallible| Error::Infallible)? + }; + let api_admin_token = env::var(env_var_api_admin_token).ok(); + + Ok(Self { + tracker_toml, + api_admin_token, + }) + } +} + /// Configuration for each UDP tracker. #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)] pub struct UdpTracker { @@ -301,6 +359,12 @@ pub struct HttpApi { pub access_tokens: HashMap, } +impl HttpApi { + fn override_admin_token(&mut self, api_admin_token: &str) { + self.access_tokens.insert("admin".to_string(), api_admin_token.to_string()); + } +} + impl HttpApi { /// Checks if the given token is one of the token in the configuration. #[must_use] @@ -326,7 +390,7 @@ pub struct Configuration { pub db_driver: DatabaseDriver, /// Database connection string. The format depends on the database driver. /// For `Sqlite3`, the format is `path/to/database.db`, for example: - /// `./storage/database/data.db`. + /// `./storage/tracker/lib/database/sqlite3.db`. /// For `Mysql`, the format is `mysql://db_user:db_user_password:port/db_name`, for /// example: `root:password@localhost:3306/torrust`. pub db_path: String, @@ -414,20 +478,17 @@ pub enum Error { source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, - /// If you run the tracker without providing the configuration (via the - /// `TORRUST_TRACKER_CONFIG` environment variable or configuration file), - /// the tracker will create a default configuration file but it will not - /// load it. It will return this error instead and you have to restart the - /// it. - #[error("Default configuration created at: `{path}`, please review and reload tracker, {location}")] - CreatedNewConfigHalt { - location: &'static Location<'static>, - path: String, + #[error("Unable to load from Config File: {source}")] + UnableToLoadFromConfigFile { + source: LocatedError<'static, dyn std::error::Error + Send + Sync>, }, /// Unable to load the configuration from the configuration file. #[error("Failed processing the configuration: {source}")] ConfigError { source: LocatedError<'static, ConfigError> }, + + #[error("The error for errors that can never happen.")] + Infallible, } impl From for Error { @@ -445,7 +506,7 @@ impl Default for Configuration { log_level: Option::from(String::from("info")), mode: TrackerMode::Public, db_driver: DatabaseDriver::Sqlite3, - db_path: String::from("./storage/database/data.db"), + db_path: String::from("./storage/tracker/lib/database/sqlite3.db"), announce_interval: 120, min_announce_interval: 120, max_peer_timeout: 900, @@ -485,6 +546,10 @@ impl Default for Configuration { } impl Configuration { + fn override_api_admin_token(&mut self, api_admin_token: &str) { + self.http_api.override_admin_token(api_admin_token); + } + /// Returns the tracker public IP address id defined in the configuration, /// and `None` otherwise. #[must_use] @@ -502,51 +567,51 @@ impl Configuration { /// /// # Errors /// - /// Will return `Err` if `path` does not exist or has a bad configuration. + /// Will return `Err` if `path` does not exist or has a bad configuration. pub fn load_from_file(path: &str) -> Result { let config_builder = Config::builder(); #[allow(unused_assignments)] let mut config = Config::default(); - if Path::new(path).exists() { - config = config_builder.add_source(File::with_name(path)).build()?; - } else { - warn!("No config file found."); - warn!("Creating config file.."); - let config = Configuration::default(); - config.save_to_file(path)?; - return Err(Error::CreatedNewConfigHalt { - location: Location::caller(), - path: path.to_string(), - }); - } + config = config_builder.add_source(File::with_name(path)).build()?; let torrust_config: Configuration = config.try_deserialize()?; Ok(torrust_config) } - /// Loads the configuration from the environment variable. The whole - /// configuration must be in the environment variable. It contains the same - /// configuration as the configuration file with the same format. + /// Saves the default configuration at the given path. + /// + /// # Errors + /// + /// Will return `Err` if `path` is not a valid path or the configuration + /// file cannot be created. + pub fn create_default_configuration_file(path: &str) -> Result { + let config = Configuration::default(); + config.save_to_file(path)?; + Ok(config) + } + + /// Loads the configuration from the `Info` struct. The whole + /// configuration in toml format is included in the `info.tracker_toml` string. + /// + /// Optionally will override the admin api token. /// /// # Errors /// /// Will return `Err` if the environment variable does not exist or has a bad configuration. - pub fn load_from_env_var(config_env_var_name: &str) -> Result { - match env::var(config_env_var_name) { - Ok(config_toml) => { - let config_builder = Config::builder() - .add_source(File::from_str(&config_toml, FileFormat::Toml)) - .build()?; - let config = config_builder.try_deserialize()?; - Ok(config) - } - Err(e) => Err(Error::UnableToLoadFromEnvironmentVariable { - source: (Arc::new(e) as Arc).into(), - }), - } + pub fn load(info: &Info) -> Result { + let config_builder = Config::builder() + .add_source(File::from_str(&info.tracker_toml, FileFormat::Toml)) + .build()?; + let mut config: Configuration = config_builder.try_deserialize()?; + + if let Some(ref token) = info.api_admin_token { + config.override_api_admin_token(token); + }; + + Ok(config) } /// Saves the configuration to the configuration file. @@ -556,6 +621,10 @@ impl Configuration { /// Will return `Err` if `filename` does not exist or the user does not have /// permission to read it. Will also return `Err` if the configuration is /// not valid or cannot be encoded to TOML. + /// + /// # Panics + /// + /// Will panic if the configuration cannot be written into the file. pub fn save_to_file(&self, path: &str) -> Result<(), Error> { fs::write(path, self.to_toml()).expect("Could not write to file!"); Ok(()) @@ -576,7 +645,7 @@ mod tests { let config = r#"log_level = "info" mode = "public" db_driver = "Sqlite3" - db_path = "./storage/database/data.db" + db_path = "./storage/tracker/lib/database/sqlite3.db" announce_interval = 120 min_announce_interval = 120 on_reverse_proxy = false diff --git a/packages/located-error/Cargo.toml b/packages/located-error/Cargo.toml index acd13def3..b4c813df3 100644 --- a/packages/located-error/Cargo.toml +++ b/packages/located-error/Cargo.toml @@ -1,14 +1,21 @@ [package] -name = "torrust-tracker-located-error" description = "A library to provide error decorator with the location and the source of the original error." -license = "AGPL-3.0" -version.workspace = true +keywords = ["errors", "helper", "library"] +name = "torrust-tracker-located-error" +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license-file.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true [dependencies] log = { version = "0.4", features = ["release_max_level_info"] } [dev-dependencies] thiserror = "1.0" - diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index 67c432528..bf8618686 100644 --- a/packages/located-error/src/lib.rs +++ b/packages/located-error/src/lib.rs @@ -128,7 +128,7 @@ mod tests { fn error_should_include_location() { let e = TestError::Test; - let b: LocatedError = Located(e).into(); + let b: LocatedError<'_, TestError> = Located(e).into(); let l = get_caller_location(); assert_eq!(b.location.file(), l.file()); diff --git a/packages/primitives/Cargo.toml b/packages/primitives/Cargo.toml index bba45cf5d..ce6c20ff0 100644 --- a/packages/primitives/Cargo.toml +++ b/packages/primitives/Cargo.toml @@ -1,11 +1,19 @@ [package] -name = "torrust-tracker-primitives" description = "A library with the primitive types shared by the Torrust tracker packages." -license = "AGPL-3.0" -version.workspace = true +keywords = ["api", "library", "primitives"] +name = "torrust-tracker-primitives" +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license-file.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true [dependencies] -serde = { version = "1.0", features = ["derive"] } derive_more = "0.99" +serde = { version = "1.0", features = ["derive"] } diff --git a/packages/test-helpers/Cargo.toml b/packages/test-helpers/Cargo.toml index 5d360d101..170f532c8 100644 --- a/packages/test-helpers/Cargo.toml +++ b/packages/test-helpers/Cargo.toml @@ -1,13 +1,21 @@ [package] -name = "torrust-tracker-test-helpers" description = "A library providing helpers for testing the Torrust tracker." -license = "AGPL-3.0" -version.workspace = true +keywords = ["helper", "library", "testing"] +name = "torrust-tracker-test-helpers" +readme = "README.md" + authors.workspace = true +documentation.workspace = true edition.workspace = true +homepage.workspace = true +license-file.workspace = true +publish.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true [dependencies] lazy_static = "1.4" rand = "0.8.5" -torrust-tracker-configuration = { version = "3.0.0-alpha.2", path = "../configuration"} -torrust-tracker-primitives = { version = "3.0.0-alpha.2", path = "../primitives"} +torrust-tracker-configuration = { version = "3.0.0-alpha.10", path = "../configuration" } +torrust-tracker-primitives = { version = "3.0.0-alpha.10", path = "../primitives" } diff --git a/rustfmt.toml b/rustfmt.toml index 3e878b271..76046e6f4 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,4 +1,3 @@ -max_width = 130 -imports_granularity = "Module" group_imports = "StdExternalCrate" - +imports_granularity = "Module" +max_width = 130 diff --git a/share/container/entry_script_sh b/share/container/entry_script_sh new file mode 100644 index 000000000..94dfa6b81 --- /dev/null +++ b/share/container/entry_script_sh @@ -0,0 +1,81 @@ +#!/bin/sh +set -x + +to_lc() { echo "$1" | tr '[:upper:]' '[:lower:]'; } +clean() { echo "$1" | tr -d -c 'a-zA-Z0-9-' ; } +cmp_lc() { [ "$(to_lc "$(clean "$1")")" = "$(to_lc "$(clean "$2")")" ]; } + + +inst() { + if [ -n "$1" ] && [ -n "$2" ] && [ -e "$1" ] && [ ! -e "$2" ]; then + install -D -m 0640 -o torrust -g torrust "$1" "$2"; fi; } + + +# Add torrust user, based upon supplied user-id. +if [ -z "$USER_ID" ] && [ "$USER_ID" -lt 1000 ]; then + echo "ERROR: USER_ID is not set, or less than 1000" + exit 1 +fi + +adduser --disabled-password --shell "/bin/sh" --uid "$USER_ID" "torrust" + +# Configure Permissions for Torrust Folders +mkdir -p /var/lib/torrust/tracker/database/ /etc/torrust/tracker/ +chown -R "${USER_ID}":"${USER_ID}" /var/lib/torrust /var/log/torrust /etc/torrust +chmod -R 2770 /var/lib/torrust /var/log/torrust /etc/torrust + + +# Install the database and config: +if [ -n "$TORRUST_TRACKER_DATABASE_DRIVER" ]; then + if cmp_lc "$TORRUST_TRACKER_DATABASE_DRIVER" "sqlite3"; then + + # Select sqlite3 empty database + default_database="/usr/share/torrust/default/database/tracker.sqlite3.db" + + # Select sqlite3 default configuration + default_config="/usr/share/torrust/default/config/tracker.container.sqlite3.toml" + + elif cmp_lc "$TORRUST_TRACKER_DATABASE_DRIVER" "mysql"; then + + # (no database file needed for mysql) + + # Select default mysql configuration + default_config="/usr/share/torrust/default/config/tracker.container.mysql.toml" + + else + echo "Error: Unsupported Database Type: \"$TORRUST_TRACKER_DATABASE_DRIVER\"." + echo "Please Note: Supported Database Types: \"sqlite3\", \"mysql\"." + exit 1 + fi +else + echo "Error: \"\$TORRUST_TRACKER_DATABASE_DRIVER\" was not set!"; exit 1; +fi + +install_config="/etc/torrust/tracker/tracker.toml" +install_database="/var/lib/torrust/tracker/database/sqlite3.db" + +inst "$default_config" "$install_config" +inst "$default_database" "$install_database" + +# Make Minimal Message of the Day +if cmp_lc "$RUNTIME" "runtime"; then + printf '\n in runtime \n' >> /etc/motd; +elif cmp_lc "$RUNTIME" "debug"; then + printf '\n in debug mode \n' >> /etc/motd; +elif cmp_lc "$RUNTIME" "release"; then + printf '\n in release mode \n' >> /etc/motd; +else + echo "ERROR: running in unknown mode: \"$RUNTIME\""; exit 1 +fi + +if [ -e "/usr/share/torrust/container/message" ]; then + cat "/usr/share/torrust/container/message" >> /etc/motd; chmod 0644 /etc/motd +fi + +# Load message of the day from Profile +echo '[ ! -z "$TERM" -a -r /etc/motd ] && cat /etc/motd' >> /etc/profile + +cd /home/torrust || exit 1 + +# Switch to torrust user +exec /bin/su-exec torrust "$@" diff --git a/share/container/message b/share/container/message new file mode 100644 index 000000000..6bfd6bfb8 --- /dev/null +++ b/share/container/message @@ -0,0 +1,4 @@ + +Lovely welcome to our Torrust Tracker Container! + +run 'torrust-tracker' to start tracker diff --git a/share/default/config/tracker.container.mysql.toml b/share/default/config/tracker.container.mysql.toml new file mode 100644 index 000000000..fb9cbf789 --- /dev/null +++ b/share/default/config/tracker.container.mysql.toml @@ -0,0 +1,38 @@ +announce_interval = 120 +db_driver = "MySQL" +db_path = "mysql://db_user:db_user_secret_password@mysql:3306/torrust_tracker" +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "info" +max_peer_timeout = 900 +min_announce_interval = 120 +mode = "public" +on_reverse_proxy = false +persistent_torrent_completed_stat = false +remove_peerless_torrents = true +tracker_usage_statistics = true + +[[udp_trackers]] +bind_address = "0.0.0.0:6969" +enabled = false + +[[http_trackers]] +bind_address = "0.0.0.0:7070" +enabled = false +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +[http_api] +bind_address = "0.0.0.0:1212" +enabled = true +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +# Please override the admin token setting the +# `TORRUST_TRACKER_API_ADMIN_TOKEN` +# environmental variable! + +[http_api.access_tokens] +admin = "MyAccessToken" diff --git a/share/default/config/tracker.container.sqlite3.toml b/share/default/config/tracker.container.sqlite3.toml new file mode 100644 index 000000000..54cfd4023 --- /dev/null +++ b/share/default/config/tracker.container.sqlite3.toml @@ -0,0 +1,38 @@ +announce_interval = 120 +db_driver = "Sqlite3" +db_path = "/var/lib/torrust/tracker/database/sqlite3.db" +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "info" +max_peer_timeout = 900 +min_announce_interval = 120 +mode = "public" +on_reverse_proxy = false +persistent_torrent_completed_stat = false +remove_peerless_torrents = true +tracker_usage_statistics = true + +[[udp_trackers]] +bind_address = "0.0.0.0:6969" +enabled = false + +[[http_trackers]] +bind_address = "0.0.0.0:7070" +enabled = false +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +[http_api] +bind_address = "0.0.0.0:1212" +enabled = true +ssl_cert_path = "/var/lib/torrust/tracker/tls/localhost.crt" +ssl_enabled = false +ssl_key_path = "/var/lib/torrust/tracker/tls/localhost.key" + +# Please override the admin token setting the +# `TORRUST_TRACKER_API_ADMIN_TOKEN` +# environmental variable! + +[http_api.access_tokens] +admin = "MyAccessToken" diff --git a/config.toml.local b/share/default/config/tracker.development.sqlite3.toml similarity index 92% rename from config.toml.local rename to share/default/config/tracker.development.sqlite3.toml index baf272d5a..20f95ac5d 100644 --- a/config.toml.local +++ b/share/default/config/tracker.development.sqlite3.toml @@ -1,33 +1,33 @@ -log_level = "info" -mode = "public" -db_driver = "Sqlite3" -db_path = "./storage/database/data.db" announce_interval = 120 -min_announce_interval = 120 +db_driver = "Sqlite3" +db_path = "./storage/tracker/lib/database/sqlite3.db" +external_ip = "0.0.0.0" +inactive_peer_cleanup_interval = 600 +log_level = "info" max_peer_timeout = 900 +min_announce_interval = 120 +mode = "public" on_reverse_proxy = false -external_ip = "0.0.0.0" -tracker_usage_statistics = true persistent_torrent_completed_stat = false -inactive_peer_cleanup_interval = 600 remove_peerless_torrents = true +tracker_usage_statistics = true [[udp_trackers]] -enabled = false bind_address = "0.0.0.0:6969" +enabled = false [[http_trackers]] -enabled = false bind_address = "0.0.0.0:7070" -ssl_enabled = false +enabled = false ssl_cert_path = "" +ssl_enabled = false ssl_key_path = "" [http_api] -enabled = true bind_address = "127.0.0.1:1212" -ssl_enabled = false +enabled = true ssl_cert_path = "" +ssl_enabled = false ssl_key_path = "" [http_api.access_tokens] diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index c0e688a0d..6961e15f0 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -11,11 +11,11 @@ //! 2. Initialize static variables. //! 3. Initialize logging. //! 4. Initialize the domain tracker. -use std::env; use std::sync::Arc; use torrust_tracker_configuration::Configuration; +use super::config::initialize_configuration; use crate::bootstrap; use crate::shared::clock::static_time; use crate::shared::crypto::ephemeral_instance_keys; @@ -55,35 +55,6 @@ pub fn initialize_static() { lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED); } -/// It loads the application configuration from the environment. -/// -/// There are two methods to inject the configuration: -/// -/// 1. By using a config file: `config.toml`. The file must be in the same folder where you are running the tracker. -/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `config.toml` file. -/// -/// Environment variable has priority over the config file. -/// -/// Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. -/// -/// # Panics -/// -/// Will panic if it can't load the configuration from either -/// `./config.toml` file or the env var `TORRUST_TRACKER_CONFIG`. -#[must_use] -fn initialize_configuration() -> Configuration { - const CONFIG_PATH: &str = "./config.toml"; - const CONFIG_ENV_VAR_NAME: &str = "TORRUST_TRACKER_CONFIG"; - - if env::var(CONFIG_ENV_VAR_NAME).is_ok() { - println!("Loading configuration from env var {CONFIG_ENV_VAR_NAME}"); - Configuration::load_from_env_var(CONFIG_ENV_VAR_NAME).unwrap() - } else { - println!("Loading configuration from config file {CONFIG_PATH}"); - Configuration::load_from_file(CONFIG_PATH).unwrap() - } -} - /// It builds the domain tracker /// /// The tracker is the domain layer service. It's the entrypoint to make requests to the domain layer. diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs new file mode 100644 index 000000000..858fd59fc --- /dev/null +++ b/src/bootstrap/config.rs @@ -0,0 +1,57 @@ +//! Initialize configuration from file or env var. +//! +//! All environment variables are prefixed with `TORRUST_TRACKER_BACK_`. + +use torrust_tracker_configuration::{Configuration, Info}; + +// Environment variables + +/// The whole `tracker.toml` file content. It has priority over the config file. +/// Even if the file is not on the default path. +const ENV_VAR_CONFIG: &str = "TORRUST_TRACKER_CONFIG"; +const ENV_VAR_API_ADMIN_TOKEN: &str = "TORRUST_TRACKER_API_ADMIN_TOKEN"; + +/// The `tracker.toml` file location. +pub const ENV_VAR_PATH_CONFIG: &str = "TORRUST_TRACKER_PATH_CONFIG"; + +// Default values +pub const DEFAULT_PATH_CONFIG: &str = "./share/default/config/tracker.development.sqlite3.toml"; + +/// It loads the application configuration from the environment. +/// +/// There are two methods to inject the configuration: +/// +/// 1. By using a config file: `tracker.toml`. +/// 2. Environment variable: `TORRUST_TRACKER_CONFIG`. The variable contains the same contents as the `tracker.toml` file. +/// +/// Environment variable has priority over the config file. +/// +/// Refer to the [configuration documentation](https://docs.rs/torrust-tracker-configuration) for the configuration options. +/// +/// # Panics +/// +/// Will panic if it can't load the configuration from either +/// `./tracker.toml` file or the env var `TORRUST_TRACKER_CONFIG`. +#[must_use] +pub fn initialize_configuration() -> Configuration { + let info = Info::new( + ENV_VAR_CONFIG.to_string(), + ENV_VAR_PATH_CONFIG.to_string(), + DEFAULT_PATH_CONFIG.to_string(), + ENV_VAR_API_ADMIN_TOKEN.to_string(), + ) + .unwrap(); + + Configuration::load(&info).unwrap() +} + +#[cfg(test)] +mod tests { + + #[test] + fn it_should_load_with_default_config() { + use crate::bootstrap::config::initialize_configuration; + + drop(initialize_configuration()); + } +} diff --git a/src/bootstrap/mod.rs b/src/bootstrap/mod.rs index e39cf3adc..22044aafd 100644 --- a/src/bootstrap/mod.rs +++ b/src/bootstrap/mod.rs @@ -6,5 +6,6 @@ //! like cleaning torrents, and other jobs because they can be enabled/disabled depending on the configuration. //! For example, you can have more than one UDP and HTTP tracker, each server is executed like a independent job. pub mod app; +pub mod config; pub mod jobs; pub mod logging; diff --git a/src/lib.rs b/src/lib.rs index e219e59e3..c862d373a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -64,26 +64,64 @@ //! ## Minimum requirements //! //! - Rust Stable `1.68` -//! - You might have problems compiling with a machine with low resources. Or with low resources limits on docker containers. It has been tested with docker containers with 6 CPUs, 7.5 GM of memory and 2GB of swap. +//! - You might have problems compiling with a machine with low resources. +//! +//! It has been tested with: +//! +//! Docker containers with: +//! +//! - 6 CPUs +//! - 7.5G of ram +//! - 2GB of swap +//! +//! [VM](https://github.com/torrust/torrust-tracker/issues/321) with: +//! +//! - 1 core of Intel Xeon Processor (Icelake) +//! - 1G of ram +//! - 25G of disk +//! - Debian 11 +//! - no swap by default +//! +//! Adding swap may help with compilation. See issue [#321](https://github.com/torrust/torrust-tracker/issues/321). //! //! ## Prerequisites //! +//! The tracker has some system dependencies: +//! +//! Since we are using the `openssl` crate with the [vendored feature](https://docs.rs/openssl/latest/openssl/#vendored), +//! enabled, you will need to install the following dependencies: +//! +//! ```text +//! sudo apt-get install pkg-config libssl-dev make +//! ``` +//! +//! If you are using `SQLite3` as database driver, you will need to install the +//! following dependency: +//! +//! ```text +//! sudo apt-get install libsqlite3-dev +//! ``` +//! +//! > **NOTICE**: those are the commands for `Ubuntu`. If you are using a +//! different OS, you will need to install the equivalent packages. Please +//! refer to the documentation of your OS. +//! //! With the default configuration you will need to create the `storage` directory: //! //! ```text //! storage/ //! ├── database //! │   └── data.db -//! └── ssl_certificates +//! └── tls //! ├── localhost.crt //! └── localhost.key //! ``` //! -//! The default configuration expects a directory `./storage/database` to be writable by the tracker process. +//! The default configuration expects a directory `./storage/tracker/lib/database` to be writable by the tracker process. //! //! By default the tracker uses `SQLite` and the database file name `data.db`. //! -//! You only need the `ssl_certificates` directory in case you are setting up SSL for the HTTP tracker or the tracker API. +//! You only need the `tls` directory in case you are setting up SSL for the HTTP tracker or the tracker API. //! Visit [`HTTP`](crate::servers::http) or [`API`](crate::servers::apis) if you want to know how you can use HTTPS. //! //! ## Install from sources @@ -92,33 +130,19 @@ //! git clone https://github.com/torrust/torrust-tracker.git \ //! && cd torrust-tracker \ //! && cargo build --release \ -//! && mkdir -p ./storage/database \ -//! && mkdir -p ./storage/ssl_certificates +//! && mkdir -p ./storage/tracker/lib/database \ +//! && mkdir -p ./storage/tracker/lib/tls //! ``` //! //! ## Run with docker //! -//! You can run the tracker with a pre-built docker image: -//! -//! ```text -//! mkdir -p ./storage/database \ -//! && mkdir -p ./storage/ssl_certificates \ -//! && export TORRUST_TRACKER_USER_UID=1000 \ -//! && docker run -it \ -//! --user="$TORRUST_TRACKER_USER_UID" \ -//! --publish 6969:6969/udp \ -//! --publish 7070:7070/tcp \ -//! --publish 1212:1212/tcp \ -//! --volume "$(pwd)/storage":"/app/storage" \ -//! torrust/tracker:3.0.0-alpha.2 -//! ``` -//! -//! For more information about using docker visit the [tracker docker documentation](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! You can run the tracker with a pre-built docker image. Please refer to the +//! [tracker docker documentation](https://github.com/torrust/torrust-tracker/tree/develop/docker). //! //! # Configuration //! //! In order to run the tracker you need to provide the configuration. If you run the tracker without providing the configuration, -//! the tracker will generate the default configuration the first time you run it. It will generate a `config.toml` file with +//! the tracker will generate the default configuration the first time you run it. It will generate a `tracker.toml` file with //! in the root directory. //! //! The default configuration is: @@ -127,7 +151,7 @@ //! log_level = "info" //! mode = "public" //! db_driver = "Sqlite3" -//! db_path = "./storage/database/data.db" +//! db_path = "./storage/tracker/lib/database/sqlite3.db" //! announce_interval = 120 //! min_announce_interval = 120 //! max_peer_timeout = 900 @@ -164,18 +188,18 @@ //! //! For more information about each service and options you can visit the documentation for the [torrust-tracker-configuration crate](https://docs.rs/torrust-tracker-configuration). //! -//! Alternatively to the `config.toml` file you can use one environment variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: +//! Alternatively to the `tracker.toml` file you can use one environment variable `TORRUST_TRACKER_CONFIG` to pass the configuration to the tracker: //! //! ```text -//! TORRUST_TRACKER_CONFIG=$(cat config.toml) +//! TORRUST_TRACKER_CONFIG=$(cat tracker.toml) //! cargo run //! ``` //! -//! In the previous example you are just setting the env var with the contents of the `config.toml` file. +//! In the previous example you are just setting the env var with the contents of the `tracker.toml` file. //! -//! The env var contains the same data as the `config.toml`. It's particularly useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). +//! The env var contains the same data as the `tracker.toml`. It's particularly useful in you are [running the tracker with docker](https://github.com/torrust/torrust-tracker/tree/develop/docker). //! -//! > NOTE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `config.toml` file. +//! > NOTE: The `TORRUST_TRACKER_CONFIG` env var has priority over the `tracker.toml` file. //! //! # Usage //! diff --git a/src/servers/apis/mod.rs b/src/servers/apis/mod.rs index eb278bf3c..afed9ff12 100644 --- a/src/servers/apis/mod.rs +++ b/src/servers/apis/mod.rs @@ -28,8 +28,8 @@ //! enabled = true //! bind_address = "0.0.0.0:1212" //! ssl_enabled = false -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" @@ -41,7 +41,7 @@ //! When you run the tracker with enabled API, you will see the following message: //! //! ```text -//! Loading configuration from config file ./config.toml +//! Loading configuration from config file ./tracker.toml //! 023-03-28T12:19:24.963054069+01:00 [torrust_tracker::bootstrap::logging][INFO] logging initialized. //! ... //! 023-03-28T12:19:24.964138723+01:00 [torrust_tracker::bootstrap::jobs::tracker_apis][INFO] Starting Torrust APIs server on: http://0.0.0.0:1212 @@ -116,8 +116,8 @@ //! enabled = true //! bind_address = "0.0.0.0:1212" //! ssl_enabled = true -//! ssl_cert_path = "./storage/ssl_certificates/localhost.crt" -//! ssl_key_path = "./storage/ssl_certificates/localhost.key" +//! ssl_cert_path = "./storage/tracker/lib/tls/localhost.crt" +//! ssl_key_path = "./storage/tracker/lib/tls/localhost.key" //! //! [http_api.access_tokens] //! admin = "MyAccessToken" diff --git a/src/servers/apis/routes.rs b/src/servers/apis/routes.rs index a4c4642c7..7801389f3 100644 --- a/src/servers/apis/routes.rs +++ b/src/servers/apis/routes.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use axum::{middleware, Router}; +use tower_http::compression::CompressionLayer; use super::v1; use crate::tracker::Tracker; @@ -21,8 +22,10 @@ pub fn router(tracker: Arc) -> Router { let router = v1::routes::add(prefix, router, tracker.clone()); - router.layer(middleware::from_fn_with_state( - tracker.config.clone(), - v1::middlewares::auth::auth, - )) + router + .layer(middleware::from_fn_with_state( + tracker.config.clone(), + v1::middlewares::auth::auth, + )) + .layer(CompressionLayer::new()) } diff --git a/src/servers/apis/server.rs b/src/servers/apis/server.rs index 91821aa79..778a17d90 100644 --- a/src/servers/apis/server.rs +++ b/src/servers/apis/server.rs @@ -83,6 +83,10 @@ impl ApiServer { /// # Errors /// /// It would return an error if no `SocketAddr` is returned after launching the server. + /// + /// # Panics + /// + /// It would panic if the bound socket address cannot be sent back to this starter. pub async fn start(self, tracker: Arc) -> Result, Error> { let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::(); let (addr_sender, addr_receiver) = tokio::sync::oneshot::channel::(); @@ -124,7 +128,7 @@ impl ApiServer { .send(0) .map_err(|_| Error::Error("Task killer channel was closed.".to_string()))?; - let _ = self.state.task.await; + drop(self.state.task.await); Ok(ApiServer { cfg: self.cfg, @@ -229,6 +233,10 @@ impl Launcher { } /// Starts the API server with graceful shutdown on the current thread. +/// +/// # Panics +/// +/// It would panic if it fails to listen to shutdown signal. pub fn start(socket_addr: SocketAddr, tracker: Arc) -> impl Future> { let app = router(tracker); @@ -241,6 +249,10 @@ pub fn start(socket_addr: SocketAddr, tracker: Arc) -> impl Future invalid_auth_key_param_response(&seconds_valid_or_key.0), Ok(key) => match tracker.remove_auth_key(&key).await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_delete_key_response(e), }, } @@ -90,7 +90,7 @@ pub async fn delete_auth_key_handler( /// for more information about this endpoint. pub async fn reload_keys_handler(State(tracker): State>) -> Response { match tracker.load_keys_from_database().await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_reload_keys_response(e), } } diff --git a/src/servers/apis/v1/context/auth_key/resources.rs b/src/servers/apis/v1/context/auth_key/resources.rs index 3eeafbda0..5099fad8b 100644 --- a/src/servers/apis/v1/context/auth_key/resources.rs +++ b/src/servers/apis/v1/context/auth_key/resources.rs @@ -27,6 +27,7 @@ impl From for auth::ExpiringKey { } } +#[allow(deprecated)] impl From for AuthKey { fn from(auth_key: auth::ExpiringKey) -> Self { AuthKey { @@ -63,6 +64,7 @@ mod tests { } #[test] + #[allow(deprecated)] fn it_should_be_convertible_into_an_auth_key() { let auth_key_resource = AuthKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".to_string(), // cspell:disable-line @@ -80,6 +82,7 @@ mod tests { } #[test] + #[allow(deprecated)] fn it_should_be_convertible_from_an_auth_key() { let auth_key = auth::ExpiringKey { key: "IaWDneuFNZi8IB4MPA3qW1CD0M30EZSM".parse::().unwrap(), // cspell:disable-line @@ -97,6 +100,7 @@ mod tests { } #[test] + #[allow(deprecated)] fn it_should_be_convertible_into_json() { assert_eq!( serde_json::to_string(&AuthKey { diff --git a/src/servers/apis/v1/context/whitelist/handlers.rs b/src/servers/apis/v1/context/whitelist/handlers.rs index 8e8c20b50..bd1da735e 100644 --- a/src/servers/apis/v1/context/whitelist/handlers.rs +++ b/src/servers/apis/v1/context/whitelist/handlers.rs @@ -30,7 +30,7 @@ pub async fn add_torrent_to_whitelist_handler( match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), Ok(info_hash) => match tracker.add_torrent_to_whitelist(&info_hash).await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_whitelist_torrent_response(e), }, } @@ -53,7 +53,7 @@ pub async fn remove_torrent_from_whitelist_handler( match InfoHash::from_str(&info_hash.0) { Err(_) => invalid_info_hash_param_response(&info_hash.0), Ok(info_hash) => match tracker.remove_torrent_from_whitelist(&info_hash).await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_remove_torrent_from_whitelist_response(e), }, } @@ -71,7 +71,7 @@ pub async fn remove_torrent_from_whitelist_handler( /// for more information about this endpoint. pub async fn reload_whitelist_handler(State(tracker): State>) -> Response { match tracker.load_whitelist_from_database().await { - Ok(_) => ok_response(), + Ok(()) => ok_response(), Err(e) => failed_to_reload_whitelist_response(e), } } diff --git a/src/servers/apis/v1/middlewares/auth.rs b/src/servers/apis/v1/middlewares/auth.rs index 608a1b7d2..3e8f74d0c 100644 --- a/src/servers/apis/v1/middlewares/auth.rs +++ b/src/servers/apis/v1/middlewares/auth.rs @@ -11,7 +11,7 @@ //! The token must be one of the `access_tokens` in the tracker //! [HTTP API configuration](torrust_tracker_configuration::HttpApi). //! -//! The configuration file `config.toml` contains a list of tokens: +//! The configuration file `tracker.toml` contains a list of tokens: //! //! ```toml //! [http_api.access_tokens] @@ -49,7 +49,9 @@ pub async fn auth( where B: Send, { - let Some(token) = params.token else { return AuthError::Unauthorized.into_response() }; + let Some(token) = params.token else { + return AuthError::Unauthorized.into_response(); + }; if !authenticate(&token, &config.http_api) { return AuthError::TokenNotValid.into_response(); diff --git a/src/servers/http/server.rs b/src/servers/http/server.rs index 6a46b81df..6007d212d 100644 --- a/src/servers/http/server.rs +++ b/src/servers/http/server.rs @@ -104,6 +104,11 @@ impl HttpServer> { /// # Errors /// /// It would return an error if no `SocketAddr` is returned after launching the server. + /// + /// # Panics + /// + /// It would panic spawned HTTP server launcher cannot send the bound `SocketAddr` + /// back to the main thread. pub async fn start(self, tracker: Arc) -> Result>, Error> { let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::(); let (addr_sender, addr_receiver) = tokio::sync::oneshot::channel::(); diff --git a/src/servers/http/v1/handlers/announce.rs b/src/servers/http/v1/handlers/announce.rs index 5b26b3758..0e49bd422 100644 --- a/src/servers/http/v1/handlers/announce.rs +++ b/src/servers/http/v1/handlers/announce.rs @@ -87,7 +87,7 @@ async fn handle_announce( if tracker.requires_authentication() { match maybe_key { Some(key) => match tracker.authenticate(&key).await { - Ok(_) => (), + Ok(()) => (), Err(error) => return Err(responses::error::Error::from(error)), }, None => { @@ -100,7 +100,7 @@ async fn handle_announce( // Authorization match tracker.authorize(&announce_request.info_hash).await { - Ok(_) => (), + Ok(()) => (), Err(error) => return Err(responses::error::Error::from(error)), } diff --git a/src/servers/http/v1/handlers/scrape.rs b/src/servers/http/v1/handlers/scrape.rs index b8c1cbea1..58b8aa84c 100644 --- a/src/servers/http/v1/handlers/scrape.rs +++ b/src/servers/http/v1/handlers/scrape.rs @@ -78,7 +78,7 @@ async fn handle_scrape( let return_real_scrape_data = if tracker.requires_authentication() { match maybe_key { Some(key) => match tracker.authenticate(&key).await { - Ok(_) => true, + Ok(()) => true, Err(_error) => false, }, None => false, diff --git a/src/servers/http/v1/launcher.rs b/src/servers/http/v1/launcher.rs index 96dd1baac..b5faf8d46 100644 --- a/src/servers/http/v1/launcher.rs +++ b/src/servers/http/v1/launcher.rs @@ -22,6 +22,14 @@ pub enum Error { pub struct Launcher; impl Launcher { + /// It starts a new HTTP server instance from a TCP listener with graceful shutdown. + /// + /// # Panics + /// + /// Will panic if: + /// + /// - The TCP listener could not be bound. + /// - The Axum server crashes. pub fn start_from_tcp_listener_with_graceful_shutdown( tcp_listener: std::net::TcpListener, tracker: Arc, @@ -42,6 +50,14 @@ impl Launcher { }) } + /// It starts a new HTTPS server instance from a TCP listener with graceful shutdown. + /// + /// # Panics + /// + /// Will panic if: + /// + /// - The SSL certificate could not be read from the provided path or is invalid. + /// - The Axum server crashes. pub fn start_tls_from_tcp_listener_with_graceful_shutdown( tcp_listener: std::net::TcpListener, (ssl_cert_path, ssl_key_path): (String, String), @@ -114,6 +130,11 @@ impl HttpServerLauncher for Launcher { } } +/// Starts a new HTTP server instance. +/// +/// # Panics +/// +/// Panics if the server could not listen to shutdown (ctrl+c) signal. pub fn start(socket_addr: std::net::SocketAddr, tracker: Arc) -> impl Future> { let app = router(tracker); @@ -125,6 +146,11 @@ pub fn start(socket_addr: std::net::SocketAddr, tracker: Arc) -> impl F }) } +/// Starts a new HTTPS server instance. +/// +/// # Panics +/// +/// Panics if the server could not listen to shutdown (ctrl+c) signal. pub fn start_tls( socket_addr: std::net::SocketAddr, ssl_config: RustlsConfig, diff --git a/src/servers/http/v1/query.rs b/src/servers/http/v1/query.rs index 6bbdc63e9..745796b61 100644 --- a/src/servers/http/v1/query.rs +++ b/src/servers/http/v1/query.rs @@ -137,7 +137,7 @@ impl From> for Query { } impl std::fmt::Display for Query { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let query = self .params .iter_all() @@ -185,7 +185,7 @@ impl FromStr for NameValuePair { } impl std::fmt::Display for NameValuePair { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}={}", self.name, self.value) } } @@ -208,7 +208,7 @@ impl FieldValuePairSet { } impl std::fmt::Display for FieldValuePairSet { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let query = self .pairs .iter() diff --git a/src/servers/http/v1/requests/announce.rs b/src/servers/http/v1/requests/announce.rs index 1cf632eb5..c330ca3bd 100644 --- a/src/servers/http/v1/requests/announce.rs +++ b/src/servers/http/v1/requests/announce.rs @@ -166,7 +166,7 @@ impl FromStr for Event { } impl fmt::Display for Event { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Event::Started => write!(f, "started"), Event::Stopped => write!(f, "stopped"), @@ -194,7 +194,7 @@ pub enum Compact { } impl fmt::Display for Compact { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Compact::Accepted => write!(f, "1"), Compact::NotAccepted => write!(f, "0"), @@ -264,12 +264,10 @@ fn extract_info_hash(query: &Query) -> Result })?, ) } - None => { - return Err(ParseAnnounceQueryError::MissingParam { - location: Location::caller(), - param_name: INFO_HASH.to_owned(), - }) - } + None => Err(ParseAnnounceQueryError::MissingParam { + location: Location::caller(), + param_name: INFO_HASH.to_owned(), + }), } } @@ -282,12 +280,10 @@ fn extract_peer_id(query: &Query) -> Result { source: Located(err).into(), })?, ), - None => { - return Err(ParseAnnounceQueryError::MissingParam { - location: Location::caller(), - param_name: PEER_ID.to_owned(), - }) - } + None => Err(ParseAnnounceQueryError::MissingParam { + location: Location::caller(), + param_name: PEER_ID.to_owned(), + }), } } @@ -298,12 +294,10 @@ fn extract_port(query: &Query) -> Result { param_value: raw_param.clone(), location: Location::caller(), })?), - None => { - return Err(ParseAnnounceQueryError::MissingParam { - location: Location::caller(), - param_name: PORT.to_owned(), - }) - } + None => Err(ParseAnnounceQueryError::MissingParam { + location: Location::caller(), + param_name: PORT.to_owned(), + }), } } diff --git a/src/servers/http/v1/requests/scrape.rs b/src/servers/http/v1/requests/scrape.rs index 227ea74ae..7c52b9fc4 100644 --- a/src/servers/http/v1/requests/scrape.rs +++ b/src/servers/http/v1/requests/scrape.rs @@ -74,12 +74,10 @@ fn extract_info_hashes(query: &Query) -> Result, ParseScrapeQueryE Ok(info_hashes) } - None => { - return Err(ParseScrapeQueryError::MissingParam { - location: Location::caller(), - param_name: INFO_HASH.to_owned(), - }) - } + None => Err(ParseScrapeQueryError::MissingParam { + location: Location::caller(), + param_name: INFO_HASH.to_owned(), + }), } } diff --git a/src/servers/http/v1/responses/announce.rs b/src/servers/http/v1/responses/announce.rs index 8fbe5df35..3596275f4 100644 --- a/src/servers/http/v1/responses/announce.rs +++ b/src/servers/http/v1/responses/announce.rs @@ -7,9 +7,9 @@ use std::panic::Location; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; -use bip_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; use serde::{self, Deserialize, Serialize}; use thiserror::Error; +use torrust_tracker_contrib_bencode::{ben_bytes, ben_int, ben_list, ben_map, BMutAccess, BencodeMut}; use crate::servers::http::v1::responses; use crate::tracker::{self, AnnounceData}; @@ -116,7 +116,7 @@ pub struct Peer { impl Peer { #[must_use] - pub fn ben_map(&self) -> BencodeMut { + pub fn ben_map(&self) -> BencodeMut<'_> { ben_map! { "peer id" => ben_bytes!(self.peer_id.clone().to_vec()), "ip" => ben_bytes!(self.ip.to_string()), diff --git a/src/servers/http/v1/responses/scrape.rs b/src/servers/http/v1/responses/scrape.rs index 6610f9dc4..9cd88b9ab 100644 --- a/src/servers/http/v1/responses/scrape.rs +++ b/src/servers/http/v1/responses/scrape.rs @@ -5,7 +5,7 @@ use std::borrow::Cow; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; -use bip_bencode::{ben_int, ben_map, BMutAccess}; +use torrust_tracker_contrib_bencode::{ben_int, ben_map, BMutAccess}; use crate::tracker::ScrapeData; diff --git a/src/servers/http/v1/routes.rs b/src/servers/http/v1/routes.rs index 86bdf480f..6546dcbb8 100644 --- a/src/servers/http/v1/routes.rs +++ b/src/servers/http/v1/routes.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use axum::routing::get; use axum::Router; use axum_client_ip::SecureClientIpSource; +use tower_http::compression::CompressionLayer; use super::handlers::{announce, scrape}; use crate::tracker::Tracker; @@ -23,4 +24,5 @@ pub fn router(tracker: Arc) -> Router { .route("/scrape/:key", get(scrape::handle_with_key).with_state(tracker)) // Add extension to get the client IP from the connection info .layer(SecureClientIpSource::ConnectInfo.into_extension()) + .layer(CompressionLayer::new()) } diff --git a/src/servers/signals.rs b/src/servers/signals.rs index f0312b886..51f53738d 100644 --- a/src/servers/signals.rs +++ b/src/servers/signals.rs @@ -2,6 +2,10 @@ use log::info; /// Resolves on `ctrl_c` or the `terminate` signal. +/// +/// # Panics +/// +/// Will panic if the `ctrl_c` or `terminate` signal resolves with an error. pub async fn global_shutdown_signal() { let ctrl_c = async { tokio::signal::ctrl_c().await.expect("failed to install Ctrl+C handler"); @@ -19,18 +23,22 @@ pub async fn global_shutdown_signal() { let terminate = std::future::pending::<()>(); tokio::select! { - _ = ctrl_c => {}, - _ = terminate => {} + () = ctrl_c => {}, + () = terminate => {} } } /// Resolves when the `stop_receiver` or the `global_shutdown_signal()` resolves. +/// +/// # Panics +/// +/// Will panic if the `stop_receiver` resolves with an error. pub async fn shutdown_signal(stop_receiver: tokio::sync::oneshot::Receiver) { let stop = async { stop_receiver.await.expect("Failed to install stop signal.") }; tokio::select! { _ = stop => {}, - _ = global_shutdown_signal() => {} + () = global_shutdown_signal() => {} } } diff --git a/src/servers/udp/connection_cookie.rs b/src/servers/udp/connection_cookie.rs index a389388a7..4dc9896ab 100644 --- a/src/servers/udp/connection_cookie.rs +++ b/src/servers/udp/connection_cookie.rs @@ -314,7 +314,7 @@ mod tests { } #[test] - #[should_panic] + #[should_panic = "InvalidConnectionId"] fn it_should_be_not_valid_after_their_last_time_extent() { let remote_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0); diff --git a/src/servers/udp/handlers.rs b/src/servers/udp/handlers.rs index e94e0292f..64d60e549 100644 --- a/src/servers/udp/handlers.rs +++ b/src/servers/udp/handlers.rs @@ -104,6 +104,7 @@ pub async fn handle_connect(remote_addr: SocketAddr, request: &ConnectRequest, t /// # Errors /// /// Will return `Error` if unable to `authenticate_request`. +#[allow(deprecated)] pub async fn authenticate(info_hash: &InfoHash, tracker: &Tracker) -> Result<(), Error> { tracker .authenticate_request(info_hash, &None) @@ -225,6 +226,7 @@ pub async fn handle_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tra let info_hash = file.0; let swarm_metadata = file.1; + #[allow(deprecated)] let scrape_entry = if tracker.authenticate_request(info_hash, &None).await.is_ok() { #[allow(clippy::cast_possible_truncation)] TorrentScrapeStatistics { diff --git a/src/servers/udp/server.rs b/src/servers/udp/server.rs index a4f1faae8..5e5c98704 100644 --- a/src/servers/udp/server.rs +++ b/src/servers/udp/server.rs @@ -143,7 +143,7 @@ impl UdpServer { pub async fn stop(self) -> Result, Error> { self.state.stop_job_sender.send(1).map_err(|e| Error::Error(e.to_string()))?; - let _ = self.state.job.await; + drop(self.state.job.await); let stopped_api_server: UdpServer = UdpServer { cfg: self.cfg, @@ -220,7 +220,7 @@ impl Udp { let socket = self.socket.clone(); tokio::select! { - _ = &mut shutdown_signal => { + () = &mut shutdown_signal => { info!("Stopping UDP server: {}..", self.socket.local_addr().unwrap()); break; } @@ -244,7 +244,7 @@ impl Udp { let mut cursor = Cursor::new(buffer); match response.write(&mut cursor) { - Ok(_) => { + Ok(()) => { #[allow(clippy::cast_possible_truncation)] let position = cursor.position() as usize; let inner = cursor.get_ref(); diff --git a/src/shared/bit_torrent/info_hash.rs b/src/shared/bit_torrent/info_hash.rs index 7392c791d..20c3cb38b 100644 --- a/src/shared/bit_torrent/info_hash.rs +++ b/src/shared/bit_torrent/info_hash.rs @@ -167,7 +167,7 @@ impl InfoHash { } impl std::fmt::Display for InfoHash { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut chars = [0u8; 40]; binascii::bin2hex(&self.0, &mut chars).expect("failed to hexlify"); write!(f, "{}", std::str::from_utf8(&chars).unwrap()) @@ -195,7 +195,7 @@ impl Ord for InfoHash { impl std::cmp::PartialOrd for InfoHash { fn partial_cmp(&self, other: &InfoHash) -> Option { - self.0.partial_cmp(&other.0) + Some(self.cmp(other)) } } @@ -271,7 +271,7 @@ struct InfoHashVisitor; impl<'v> serde::de::Visitor<'v> for InfoHashVisitor { type Value = InfoHash; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "a 40 character long hash") } diff --git a/src/shared/clock/mod.rs b/src/shared/clock/mod.rs index 7a5290f49..922ca3200 100644 --- a/src/shared/clock/mod.rs +++ b/src/shared/clock/mod.rs @@ -120,7 +120,7 @@ pub fn convert_from_datetime_utc_to_timestamp(datetime_utc: &DateTime) -> D /// (this will naturally happen in 292.5 billion years) #[must_use] pub fn convert_from_timestamp_to_datetime_utc(duration: DurationSinceUnixEpoch) -> DateTime { - DateTime::::from_utc( + DateTime::::from_naive_utc_and_offset( NaiveDateTime::from_timestamp_opt( i64::try_from(duration.as_secs()).expect("Overflow of i64 seconds, very future!"), duration.subsec_nanos(), @@ -162,13 +162,13 @@ mod tests { let timestamp = DurationSinceUnixEpoch::ZERO; assert_eq!( convert_from_timestamp_to_datetime_utc(timestamp), - DateTime::::from_utc(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc) + DateTime::::from_naive_utc_and_offset(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc) ); } #[test] fn should_be_converted_from_datetime_utc() { - let datetime = DateTime::::from_utc(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc); + let datetime = DateTime::::from_naive_utc_and_offset(NaiveDateTime::from_timestamp_opt(0, 0).unwrap(), Utc); assert_eq!( convert_from_datetime_utc_to_timestamp(&datetime), DurationSinceUnixEpoch::ZERO diff --git a/src/shared/clock/time_extent.rs b/src/shared/clock/time_extent.rs index 2f9e003be..a5a359e52 100644 --- a/src/shared/clock/time_extent.rs +++ b/src/shared/clock/time_extent.rs @@ -285,18 +285,15 @@ pub type DefaultTimeExtentMaker = StoppedTimeExtentMaker; #[cfg(test)] mod test { - - use crate::shared::clock::time_extent::{ - checked_duration_from_nanos, Base, DefaultTimeExtentMaker, Extent, Make, Multiplier, Product, TimeExtent, MAX, ZERO, - }; - use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; + use crate::shared::clock::time_extent::TimeExtent; const TIME_EXTENT_VAL: TimeExtent = TimeExtent::from_sec(2, &239_812_388_723); mod fn_checked_duration_from_nanos { use std::time::Duration; - use super::*; + use crate::shared::clock::time_extent::checked_duration_from_nanos; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; const NANOS_PER_SEC: u32 = 1_000_000_000; @@ -335,11 +332,9 @@ mod test { } mod time_extent { - use super::*; mod fn_default { - - use super::*; + use crate::shared::clock::time_extent::{TimeExtent, ZERO}; #[test] fn it_should_default_initialize_to_zero() { @@ -348,7 +343,8 @@ mod test { } mod fn_from_sec { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Multiplier, TimeExtent, ZERO}; #[test] fn it_should_make_empty_for_zero() { @@ -364,7 +360,8 @@ mod test { } mod fn_new { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, Extent, Multiplier, TimeExtent, ZERO}; #[test] fn it_should_make_empty_for_zero() { @@ -386,7 +383,8 @@ mod test { mod fn_increase { use std::num::IntErrorKind; - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Extent, TimeExtent, ZERO}; #[test] fn it_should_not_increase_for_zero() { @@ -413,7 +411,8 @@ mod test { mod fn_decrease { use std::num::IntErrorKind; - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Extent, TimeExtent, ZERO}; #[test] fn it_should_not_decrease_for_zero() { @@ -438,7 +437,8 @@ mod test { } mod fn_total { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; #[test] fn it_should_be_zero_for_zero() { @@ -485,7 +485,8 @@ mod test { } mod fn_total_next { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, Extent, Product, TimeExtent, MAX, ZERO}; #[test] fn it_should_be_zero_for_zero() { @@ -539,10 +540,11 @@ mod test { } mod make_time_extent { - use super::*; mod fn_now { - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make, TimeExtent}; + use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; #[test] fn it_should_give_a_time_extent() { @@ -580,7 +582,9 @@ mod test { mod fn_now_after { use std::time::Duration; - use super::*; + use crate::shared::clock::time_extent::test::TIME_EXTENT_VAL; + use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make}; + use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; #[test] fn it_should_give_a_time_extent() { @@ -617,7 +621,8 @@ mod test { mod fn_now_before { use std::time::Duration; - use super::*; + use crate::shared::clock::time_extent::{Base, DefaultTimeExtentMaker, Make, TimeExtent}; + use crate::shared::clock::{Current, DurationSinceUnixEpoch, StoppedTime}; #[test] fn it_should_give_a_time_extent() { diff --git a/src/tracker/databases/driver.rs b/src/tracker/databases/driver.rs index 7115bae8e..19cb7046e 100644 --- a/src/tracker/databases/driver.rs +++ b/src/tracker/databases/driver.rs @@ -18,7 +18,7 @@ use super::{Builder, Database}; /// use torrust_tracker_primitives::DatabaseDriver; /// /// let db_driver = DatabaseDriver::Sqlite3; -/// let db_path = "./storage/database/data.db".to_string(); +/// let db_path = "./storage/tracker/lib/database/sqlite3.db".to_string(); /// let database = databases::driver::build(&db_driver, &db_path); /// ``` /// @@ -41,6 +41,10 @@ use super::{Builder, Database}; /// # Errors /// /// This function will return an error if unable to connect to the database. +/// +/// # Panics +/// +/// This function will panic if unable to create database tables. pub fn build(driver: &DatabaseDriver, db_path: &str) -> Result, Error> { let database = match driver { DatabaseDriver::Sqlite3 => Builder::::build(db_path), diff --git a/src/tracker/databases/mod.rs b/src/tracker/databases/mod.rs index 3b02415df..e0a26be23 100644 --- a/src/tracker/databases/mod.rs +++ b/src/tracker/databases/mod.rs @@ -56,7 +56,7 @@ use self::error::Error; use crate::shared::bit_torrent::info_hash::InfoHash; use crate::tracker::auth::{self, Key}; -pub(self) struct Builder +struct Builder where T: Database, { diff --git a/src/tracker/mod.rs b/src/tracker/mod.rs index 2cabd5a82..040751e12 100644 --- a/src/tracker/mod.rs +++ b/src/tracker/mod.rs @@ -320,7 +320,7 @@ //! log_level = "debug" //! mode = "public" //! db_driver = "Sqlite3" -//! db_path = "./storage/database/data.db" +//! db_path = "./storage/tracker/lib/database/sqlite3.db" //! announce_interval = 120 //! min_announce_interval = 120 //! max_peer_timeout = 900 @@ -643,7 +643,7 @@ impl Tracker { for info_hash in info_hashes { let swarm_metadata = match self.authorize(info_hash).await { - Ok(_) => self.get_swarm_metadata(info_hash).await, + Ok(()) => self.get_swarm_metadata(info_hash).await, Err(_) => SwarmMetadata::zeroed(), }; scrape_data.add_file(info_hash, swarm_metadata); @@ -732,10 +732,11 @@ impl Tracker { // todo: move this action to a separate worker if self.config.persistent_torrent_completed_stat && stats_updated { - let _ = self - .database - .save_persistent_torrent(info_hash, torrent_entry.completed) - .await; + drop( + self.database + .save_persistent_torrent(info_hash, torrent_entry.completed) + .await, + ); } let (seeders, completed, leechers) = torrent_entry.get_stats(); @@ -794,7 +795,7 @@ impl Tracker { } }); } else { - for (_, torrent_entry) in torrents_lock.iter_mut() { + for torrent_entry in (*torrents_lock).values_mut() { torrent_entry.remove_inactive_peers(self.config.max_peer_timeout); } } @@ -966,10 +967,10 @@ impl Tracker { return Ok(()); } - return Err(Error::TorrentNotWhitelisted { + Err(Error::TorrentNotWhitelisted { info_hash: *info_hash, location: Location::caller(), - }); + }) } /// It adds a torrent to the whitelist. @@ -1064,7 +1065,7 @@ impl Tracker { whitelist.clear(); for info_hash in whitelisted_torrents_from_database { - let _ = whitelist.insert(info_hash); + let _: bool = whitelist.insert(info_hash); } Ok(()) diff --git a/src/tracker/peer.rs b/src/tracker/peer.rs index a54346280..d6517f213 100644 --- a/src/tracker/peer.rs +++ b/src/tracker/peer.rs @@ -150,7 +150,13 @@ impl Id { /// Will panic if byte slice does not contains the exact amount of bytes need for the `Id`. #[must_use] pub fn from_bytes(bytes: &[u8]) -> Self { - assert_eq!(bytes.len(), PEER_ID_BYTES_LEN); + assert_eq!( + PEER_ID_BYTES_LEN, + bytes.len(), + "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` ({}) and the supplied `bytes` length: {}", + PEER_ID_BYTES_LEN, + bytes.len(), + ); let mut ret = Self([0u8; PEER_ID_BYTES_LEN]); ret.0.clone_from_slice(bytes); ret @@ -363,17 +369,17 @@ mod test { } #[test] - #[should_panic] + #[should_panic = "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` (20) and the supplied `bytes` length: 19"] fn should_fail_trying_to_instantiate_from_a_byte_slice_with_less_than_20_bytes() { let less_than_20_bytes = [0; 19]; - let _ = peer::Id::from_bytes(&less_than_20_bytes); + let _: peer::Id = peer::Id::from_bytes(&less_than_20_bytes); } #[test] - #[should_panic] + #[should_panic = "we are testing the equality of the constant: `PEER_ID_BYTES_LEN` (20) and the supplied `bytes` length: 21"] fn should_fail_trying_to_instantiate_from_a_byte_slice_with_more_than_20_bytes() { let more_than_20_bytes = [0; 21]; - let _ = peer::Id::from_bytes(&more_than_20_bytes); + let _: peer::Id = peer::Id::from_bytes(&more_than_20_bytes); } #[test] @@ -418,15 +424,15 @@ mod test { } #[test] - #[should_panic] + #[should_panic = "NotEnoughBytes"] fn should_fail_trying_to_convert_from_a_byte_vector_with_less_than_20_bytes() { - let _ = peer::Id::try_from([0; 19].to_vec()).unwrap(); + let _: peer::Id = peer::Id::try_from([0; 19].to_vec()).unwrap(); } #[test] - #[should_panic] + #[should_panic = "TooManyBytes"] fn should_fail_trying_to_convert_from_a_byte_vector_with_more_than_20_bytes() { - let _ = peer::Id::try_from([0; 21].to_vec()).unwrap(); + let _: peer::Id = peer::Id::try_from([0; 21].to_vec()).unwrap(); } #[test] diff --git a/src/tracker/services/torrent.rs b/src/tracker/services/torrent.rs index 3610d930c..0db044d07 100644 --- a/src/tracker/services/torrent.rs +++ b/src/tracker/services/torrent.rs @@ -99,7 +99,7 @@ pub async fn get_torrent_info(tracker: Arc, info_hash: &InfoHash) -> Op let Some(torrent_entry) = torrent_entry_option else { return None; - }; + }; let (seeders, completed, leechers) = torrent_entry.get_stats(); diff --git a/src/tracker/torrent.rs b/src/tracker/torrent.rs index 22deed2b4..4f7e28b6b 100644 --- a/src/tracker/torrent.rs +++ b/src/tracker/torrent.rs @@ -103,7 +103,7 @@ impl Entry { match peer.event { AnnounceEvent::Stopped => { - let _ = self.peers.remove(&peer.peer_id); + let _: Option = self.peers.remove(&peer.peer_id); } AnnounceEvent::Completed => { let peer_old = self.peers.insert(peer.peer_id, *peer); @@ -114,7 +114,7 @@ impl Entry { } } _ => { - let _ = self.peers.insert(peer.peer_id, *peer); + let _: Option = self.peers.insert(peer.peer_id, *peer); } } diff --git a/tests/servers/api/v1/contract/configuration.rs b/tests/servers/api/v1/contract/configuration.rs index e4b608607..cfdb59b0c 100644 --- a/tests/servers/api/v1/contract/configuration.rs +++ b/tests/servers/api/v1/contract/configuration.rs @@ -3,7 +3,8 @@ use torrust_tracker_test_helpers::configuration; use crate::servers::api::test_environment::stopped_test_environment; #[tokio::test] -#[should_panic] +#[ignore] +#[should_panic = "Could not receive bind_address."] async fn should_fail_with_ssl_enabled_and_bad_ssl_config() { let mut test_env = stopped_test_environment(configuration::ephemeral()); diff --git a/tests/servers/http/requests/announce.rs b/tests/servers/http/requests/announce.rs index 20c5ddaa7..f7f25da3e 100644 --- a/tests/servers/http/requests/announce.rs +++ b/tests/servers/http/requests/announce.rs @@ -21,7 +21,7 @@ pub struct Query { } impl fmt::Display for Query { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.build()) } } @@ -57,7 +57,7 @@ pub enum Event { } impl fmt::Display for Event { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { //Event::Started => write!(f, "started"), //Event::Stopped => write!(f, "stopped"), @@ -74,7 +74,7 @@ pub enum Compact { } impl fmt::Display for Compact { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Compact::Accepted => write!(f, "1"), Compact::NotAccepted => write!(f, "0"), @@ -163,7 +163,7 @@ pub struct QueryParams { } impl std::fmt::Display for QueryParams { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut params = vec![]; if let Some(info_hash) = &self.info_hash { diff --git a/tests/servers/http/requests/scrape.rs b/tests/servers/http/requests/scrape.rs index 9e4257d6c..264c72c33 100644 --- a/tests/servers/http/requests/scrape.rs +++ b/tests/servers/http/requests/scrape.rs @@ -10,7 +10,7 @@ pub struct Query { } impl fmt::Display for Query { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.build()) } } @@ -93,7 +93,7 @@ impl QueryParams { } impl std::fmt::Display for QueryParams { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let query = self .info_hash .iter() diff --git a/tests/servers/http/v1/contract.rs b/tests/servers/http/v1/contract.rs index b508dfc39..2e24af6b7 100644 --- a/tests/servers/http/v1/contract.rs +++ b/tests/servers/http/v1/contract.rs @@ -67,11 +67,12 @@ mod for_all_config_modes { // Vuze (bittorrent client) docs: // https://wiki.vuze.com/w/Announce - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV6}; use std::str::FromStr; use local_ip_address::local_ip; use reqwest::Response; + use tokio::net::TcpListener; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker::tracker::peer; use torrust_tracker_test_helpers::configuration; @@ -594,6 +595,13 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_connections_handled_in_statistics() { + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + .await + .is_err() + { + return; // we cannot bind to a ipv6 socket, so we will skip this test + } + let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) @@ -651,6 +659,13 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_of_tcp6_announce_requests_handled_in_statistics() { + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + .await + .is_err() + { + return; // we cannot bind to a ipv6 socket, so we will skip this test + } + let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; Client::bind(*test_env.bind_address(), IpAddr::from_str("::1").unwrap()) @@ -830,9 +845,10 @@ mod for_all_config_modes { // Vuze (bittorrent client) docs: // https://wiki.vuze.com/w/Scrape - use std::net::IpAddr; + use std::net::{IpAddr, Ipv6Addr, SocketAddrV6}; use std::str::FromStr; + use tokio::net::TcpListener; use torrust_tracker::shared::bit_torrent::info_hash::InfoHash; use torrust_tracker::tracker::peer; use torrust_tracker_test_helpers::configuration; @@ -1027,6 +1043,13 @@ mod for_all_config_modes { #[tokio::test] async fn should_increase_the_number_ot_tcp6_scrape_requests_handled_in_statistics() { + if TcpListener::bind(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + .await + .is_err() + { + return; // we cannot bind to a ipv6 socket, so we will skip this test + } + let test_env = running_test_environment::(configuration::ephemeral_ipv6()).await; let info_hash = InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap(); diff --git a/tests/servers/mod.rs b/tests/servers/mod.rs index c19f72020..7c30b6f40 100644 --- a/tests/servers/mod.rs +++ b/tests/servers/mod.rs @@ -1,5 +1,3 @@ -extern crate rand; - mod api; mod http; mod udp; diff --git a/tests/servers/udp/client.rs b/tests/servers/udp/client.rs index 75467055e..d267adaba 100644 --- a/tests/servers/udp/client.rs +++ b/tests/servers/udp/client.rs @@ -55,7 +55,7 @@ impl UdpTrackerClient { let mut cursor = Cursor::new(request_buffer); let request_data = match request.write(&mut cursor) { - Ok(_) => { + Ok(()) => { #[allow(clippy::cast_possible_truncation)] let position = cursor.position() as usize; let inner_request_buffer = cursor.get_ref();