Compare commits

..

1 Commits

Author SHA1 Message Date
strawberry a94bf2cf9f unfinished untested impl of room deletion
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-02-20 22:40:46 -05:00
173 changed files with 31788 additions and 29012 deletions
-15
View File
@@ -1,15 +0,0 @@
# EditorConfig is awesome: https://EditorConfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
tab_width = 4
indent_size = 4
indent_style = space
insert_final_newline = true
max_line_length = 120
[*.nix]
indent_size = 2
-3
View File
@@ -1,3 +0,0 @@
# .git-blame-ignore-revs
# adds a proper rustfmt.toml and formats the entire codebase
1d1ac065141181438e744e7d8abd0e45f75a2f91
+20 -43
View File
@@ -10,12 +10,6 @@ env:
# Required to make some things output color # Required to make some things output color
TERM: ansi TERM: ansi
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }} ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
CARGO_INCREMENTAL: 0
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
permissions:
packages: write
jobs: jobs:
ci: ci:
@@ -28,11 +22,11 @@ jobs:
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Install Nix (with flakes and nix-command enabled) - name: Install Nix (with flakes and nix-command enabled)
uses: cachix/install-nix-action@v26 uses: cachix/install-nix-action@v25
with: with:
nix_path: nixpkgs=channel:nixos-unstable nix_path: nixpkgs=channel:nixos-unstable
# Add `nix-community`, Crane, upstream Conduit, and conduwuit binary caches # Add the `nix-community` cachix to speed up things that leverage it
extra_nix_config: | extra_nix_config: |
experimental-features = nix-command flakes experimental-features = nix-command flakes
extra-substituters = https://nix-community.cachix.org extra-substituters = https://nix-community.cachix.org
@@ -46,12 +40,6 @@ jobs:
extra-substituters = https://attic.kennel.juneis.dog/conduwuit extra-substituters = https://attic.kennel.juneis.dog/conduwuit
extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw= extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
- name: Add alternative Nix binary caches if specified
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
run: |
echo "extra-substituters = ${{ env.ATTIC_ENDPOINT }}" >> /etc/nix/nix.conf
echo "extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}" >> /etc/nix/nix.conf
- name: Pop/push Magic Nix Cache - name: Pop/push Magic Nix Cache
uses: DeterminateSystems/magic-nix-cache-action@main uses: DeterminateSystems/magic-nix-cache-action@main
@@ -78,24 +66,14 @@ jobs:
- name: Populate `/nix/store` - name: Populate `/nix/store`
run: nix develop --command true run: nix develop --command true
- name: Allow direnv
run: direnv allow
- name: Cache x86_64 inputs for devShell
run: |
./bin/nix-build-and-cache .#devShells.x86_64-linux.default.inputDerivation
- name: Perform continuous integration - name: Perform continuous integration
run: direnv exec . engage run: |
direnv allow
direnv exec . engage
- name: Build static-x86_64-unknown-linux-musl
- name: Build static-x86_64-unknown-linux-musl and Create static deb-x86_64-unknown-linux-musl
run: | run: |
./bin/nix-build-and-cache .#static-x86_64-unknown-linux-musl ./bin/nix-build-and-cache .#static-x86_64-unknown-linux-musl
mkdir -p target/release
cp -v -f result/bin/conduit target/release
direnv exec . cargo deb --no-build
- name: Upload artifact static-x86_64-unknown-linux-musl - name: Upload artifact static-x86_64-unknown-linux-musl
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
@@ -104,14 +82,6 @@ jobs:
path: result/bin/conduit path: result/bin/conduit
if-no-files-found: error if-no-files-found: error
- name: Upload artifact deb-x86_64-unknown-linux-musl
uses: actions/upload-artifact@v4
with:
name: x86_64-unknown-linux-musl.deb
path: target/debian/*.deb
if-no-files-found: error
- name: Build static-aarch64-unknown-linux-musl - name: Build static-aarch64-unknown-linux-musl
run: | run: |
./bin/nix-build-and-cache .#static-aarch64-unknown-linux-musl ./bin/nix-build-and-cache .#static-aarch64-unknown-linux-musl
@@ -123,26 +93,23 @@ jobs:
path: result/bin/conduit path: result/bin/conduit
if-no-files-found: error if-no-files-found: error
- name: Build oci-image-x86_64-unknown-linux-gnu - name: Build oci-image-x86_64-unknown-linux-gnu
run: | run: |
./bin/nix-build-and-cache .#oci-image ./bin/nix-build-and-cache .#oci-image
cp -v -f result oci-image-amd64.tar.gz cp -f result oci-image-amd64.tar.gz
- name: Upload artifact oci-image-x86_64-unknown-linux-gnu - name: Upload artifact oci-image-x86_64-unknown-linux-gnu
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: oci-image-x86_64-unknown-linux-gnu name: oci-image-x86_64-unknown-linux-gnu
path: oci-image-amd64.tar.gz path: oci-image-amd64.tar.gz
if-no-files-found: error
# don't compress again # don't compress again
compression-level: 0 compression-level: 0
- name: Build oci-image-aarch64-unknown-linux-musl - name: Build oci-image-aarch64-unknown-linux-musl
run: | run: |
./bin/nix-build-and-cache .#oci-image-aarch64-unknown-linux-musl ./bin/nix-build-and-cache .#oci-image-aarch64-unknown-linux-musl
cp -v -f result oci-image-arm64v8.tar.gz cp -f result oci-image-arm64v8.tar.gz
- name: Upload artifact oci-image-aarch64-unknown-linux-musl - name: Upload artifact oci-image-aarch64-unknown-linux-musl
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
@@ -153,6 +120,18 @@ jobs:
# don't compress again # don't compress again
compression-level: 0 compression-level: 0
- name: Build deb-x86_64-unknown-linux-gnu
run: |
sudo apt-get update && sudo apt-get install -y --no-install-recommends libclang-dev
cargo install cargo-deb
cargo deb
- name: Upload artifact deb-x86_64-unknown-linux-gnu
uses: actions/upload-artifact@v4
with:
name: deb-x86_64-unknown-linux-gnu
path: target/debian/*.deb
if-no-files-found: error
- name: Extract metadata for Dockerhub - name: Extract metadata for Dockerhub
env: env:
@@ -172,7 +151,6 @@ jobs:
with: with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Login to Dockerhub - name: Login to Dockerhub
if: github.event_name != 'pull_request' if: github.event_name != 'pull_request'
uses: docker/login-action@v3 uses: docker/login-action@v3
@@ -190,7 +168,6 @@ jobs:
username: girlbossceo username: girlbossceo
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Publish to Dockerhub - name: Publish to Dockerhub
if: github.event_name != 'pull_request' if: github.event_name != 'pull_request'
env: env:
+2 -2
View File
@@ -24,7 +24,7 @@ jobs:
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Run Trivy code and vulnerability scanner on repo - name: Run Trivy code and vulnerability scanner on repo
uses: aquasecurity/trivy-action@0.18.0 uses: aquasecurity/trivy-action@0.17.0
with: with:
scan-type: repo scan-type: repo
format: sarif format: sarif
@@ -32,7 +32,7 @@ jobs:
severity: CRITICAL,HIGH,MEDIUM,LOW severity: CRITICAL,HIGH,MEDIUM,LOW
- name: Run Trivy code and vulnerability scanner on filesystem - name: Run Trivy code and vulnerability scanner on filesystem
uses: aquasecurity/trivy-action@0.18.0 uses: aquasecurity/trivy-action@0.17.0
with: with:
scan-type: fs scan-type: fs
format: sarif format: sarif
-3
View File
@@ -74,6 +74,3 @@ test-conduit.toml
# Gitlab CI cache # Gitlab CI cache
/.gitlab-ci.d /.gitlab-ci.d
# macOS
.DS_Store
+87 -89
View File
@@ -6,45 +6,22 @@ stages:
variables: variables:
# Makes some things print in color # Makes some things print in color
TERM: ansi TERM: ansi
NIX_CONFIG: |
# Avoid duplicate pipelines experimental-features = nix-command flake
# See: https://docs.gitlab.com/ee/ci/yaml/workflow.html#switch-between-branch-pipelines-and-merge-request-pipelines extra-substituters = https://nix.computer.surgery/conduit
workflow: extra-trusted-public-keys = conduit:ZGAf6P6LhNvnoJJ3Me3PRg7tlLSrPxcQ2RiE5LIppjo=
rules: extra-substituters = https://crane.cachix.org
- if: $CI_PIPELINE_SOURCE == "merge_request_event" extra-trusted-public-keys = crane.cachix.org-1:8Scfpmn9w+hGdXH/Q9tTLiYAE/2dnJYRJP7kl80GuRk=
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS extra-substituters = https://nix-community.cachix.org
when: never extra-trusted-public-keys = nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=
- if: $CI extra-substituters = https://attic.kennel.juneis.dog/conduit
extra-trusted-public-keys = conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
extra-substituters = https://attic.kennel.juneis.dog/conduwuit
extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
before_script: before_script:
# Enable nix-command and flakes
- if command -v nix > /dev/null; then echo "experimental-features = nix-command flakes" >> /etc/nix/nix.conf; fi
# Add conduwuit binary cache
- if command -v nix > /dev/null; then echo "extra-substituters = https://attic.kennel.juneis.dog/conduwuit" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-substituters = https://attic.kennel.juneis.dog/conduit" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=" >> /etc/nix/nix.conf; fi
# Add upstream Conduit binary cache
- if command -v nix > /dev/null; then echo "extra-substituters = https://nix.computer.surgery/conduit" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = conduit:ZGAf6P6LhNvnoJJ3Me3PRg7tlLSrPxcQ2RiE5LIppjo=" >> /etc/nix/nix.conf; fi
# Add alternate binary cache
- if command -v nix > /dev/null && [ -n "$ATTIC_ENDPOINT" ]; then echo "extra-substituters = $ATTIC_ENDPOINT" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null && [ -n "$ATTIC_PUBLIC_KEY" ]; then echo "extra-trusted-public-keys = $ATTIC_PUBLIC_KEY" >> /etc/nix/nix.conf; fi
# Add crane binary cache
- if command -v nix > /dev/null; then echo "extra-substituters = https://crane.cachix.org" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = crane.cachix.org-1:8Scfpmn9w+hGdXH/Q9tTLiYAE/2dnJYRJP7kl80GuRk=" >> /etc/nix/nix.conf; fi
# Add nix-community binary cache
- if command -v nix > /dev/null; then echo "extra-substituters = https://nix-community.cachix.org" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=" >> /etc/nix/nix.conf; fi
# Install direnv and nix-direnv # Install direnv and nix-direnv
- if command -v nix > /dev/null; then nix-env -iA nixpkgs.direnv nixpkgs.nix-direnv; fi - if command -v nix > /dev/null; then nix-env -iA nixpkgs.direnv nixpkgs.nix-direnv nixpkgs.engage; fi
# Allow .envrc # Allow .envrc
- if command -v nix > /dev/null; then direnv allow; fi - if command -v nix > /dev/null; then direnv allow; fi
@@ -54,82 +31,109 @@ before_script:
ci: ci:
stage: ci stage: ci
image: nixos/nix:2.21.0 image: nixos/nix:2.20.2
script: script:
# Cache the inputs required for the devShell
- ./bin/nix-build-and-cache .#devShells.x86_64-linux.default.inputDerivation
- direnv exec . engage - direnv exec . engage
cache: cache:
key: nix key: nix
paths: paths:
- target - target
- .gitlab-ci.d - .gitlab-ci.d
rules:
# CI on upstream runners (only available for maintainers)
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $IS_UPSTREAM_CI == "true"
# Manual CI on unprotected branches that are not MRs
- if: $CI_PIPELINE_SOURCE != "merge_request_event" && $CI_COMMIT_REF_PROTECTED == "false"
when: manual
# Manual CI on forks
- if: $IS_UPSTREAM_CI != "true"
when: manual
- if: $CI
interruptible: true
artifacts: static:x86_64-unknown-linux-musl:
stage: artifacts stage: artifacts
image: nixos/nix:2.21.0 image: nixos/nix:2.20.2
script: script:
# Push artifacts and build requirements to binary cache
- ./bin/nix-build-and-cache .#static-x86_64-unknown-linux-musl - ./bin/nix-build-and-cache .#static-x86_64-unknown-linux-musl
- cp result/bin/conduit x86_64-unknown-linux-musl
- mkdir -p target/release # Make the output less difficult to find
- cp result/bin/conduit target/release - cp result/bin/conduit conduit
- direnv exec . cargo deb --no-build artifacts:
- mv target/debian/*.deb x86_64-unknown-linux-musl.deb paths:
- conduit
static:aarch64-unknown-linux-musl:
stage: artifacts
image: nixos/nix:2.20.2
script:
# Push artifacts and build requirements to binary cache
- ./bin/nix-build-and-cache .#static-aarch64-unknown-linux-musl
# Make the output less difficult to find
- cp result/bin/conduit conduit
artifacts:
paths:
- conduit
# Note that although we have an `oci-image-x86_64-unknown-linux-musl` output,
# we don't build it because it would be largely redundant to this one since it's
# all containerized anyway.
oci-image:x86_64-unknown-linux-gnu:
stage: artifacts
image: nixos/nix:2.20.2
script:
# Push artifacts and build requirements to binary cache
#
# Since the OCI image package is based on the binary package, this has the # Since the OCI image package is based on the binary package, this has the
# fun side effect of uploading the normal binary too. Conduit users who are # fun side effect of uploading the normal binary too. Conduit users who are
# deploying with Nix can leverage this fact by adding our binary cache to # deploying with Nix can leverage this fact by adding our binary cache to
# their systems. # their systems.
#
# Note that although we have an `oci-image-x86_64-unknown-linux-musl`
# output, we don't build it because it would be largely redundant to this
# one since it's all containerized anyway.
- ./bin/nix-build-and-cache .#oci-image - ./bin/nix-build-and-cache .#oci-image
# Make the output less difficult to find
- cp result oci-image-amd64.tar.gz - cp result oci-image-amd64.tar.gz
artifacts:
paths:
- oci-image-amd64.tar.gz
- ./bin/nix-build-and-cache .#static-aarch64-unknown-linux-musl oci-image:aarch64-unknown-linux-musl:
- cp result/bin/conduit aarch64-unknown-linux-musl stage: artifacts
needs:
# Wait for the static binary job to finish before starting so we don't have
# to build that twice for no reason
- static:aarch64-unknown-linux-musl
image: nixos/nix:2.20.2
script:
# Push artifacts and build requirements to binary cache
- ./bin/nix-build-and-cache .#oci-image-aarch64-unknown-linux-musl - ./bin/nix-build-and-cache .#oci-image-aarch64-unknown-linux-musl
# Make the output less difficult to find
- cp result oci-image-arm64v8.tar.gz - cp result oci-image-arm64v8.tar.gz
artifacts: artifacts:
paths: paths:
- x86_64-unknown-linux-musl
- aarch64-unknown-linux-musl
- x86_64-unknown-linux-musl.deb
- oci-image-amd64.tar.gz
- oci-image-arm64v8.tar.gz - oci-image-arm64v8.tar.gz
rules:
# CI required for all MRs
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
# Optional CI on forks
- if: $IS_UPSTREAM_CI != "true"
when: manual
allow_failure: true
- if: $CI
interruptible: true
.push-oci-image: debian:x86_64-unknown-linux-gnu:
stage: artifacts
# See also `rust-toolchain.toml`
image: rust:1.75.0
script:
- cargo install cargo-deb
- cargo deb
# Make the output less difficult to find
- mv target/debian/*.deb conduit.deb
artifacts:
paths:
- conduit.deb
cache:
key: debian
paths:
- target
- .gitlab-ci.d
docker-publish:
stage: publish stage: publish
image: docker:25.0.4 image: docker:25.0.3
services: services:
- docker:25.0.4-dind - docker:25.0.3-dind
variables: variables:
IMAGE_NAME: $CI_REGISTRY_IMAGE/conduwuit
IMAGE_SUFFIX_AMD64: amd64 IMAGE_SUFFIX_AMD64: amd64
IMAGE_SUFFIX_ARM64V8: arm64v8 IMAGE_SUFFIX_ARM64V8: arm64v8
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
script: script:
- docker load -i oci-image-amd64.tar.gz - docker load -i oci-image-amd64.tar.gz
- IMAGE_ID_AMD64=$(docker images -q conduit:main) - IMAGE_ID_AMD64=$(docker images -q conduit:main)
@@ -153,14 +157,8 @@ artifacts:
docker manifest push $IMAGE_NAME:latest docker manifest push $IMAGE_NAME:latest
fi fi
dependencies: dependencies:
- artifacts - oci-image:x86_64-unknown-linux-gnu
- oci-image:aarch64-unknown-linux-musl
only: only:
- main - main
- tags - tags
oci-image:push-gitlab:
extends: .push-oci-image
variables:
IMAGE_NAME: $CI_REGISTRY_IMAGE/conduwuit
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
Generated
+205 -271
View File
File diff suppressed because it is too large Load Diff
+92 -357
View File
@@ -6,324 +6,124 @@ authors = ["strawberry <strawberry@puppygock.gay>", "timokoesters <timo@koesters
homepage = "https://puppygock.gay/conduwuit" homepage = "https://puppygock.gay/conduwuit"
repository = "https://gitlab.com/girlbossceo/conduwuit" repository = "https://gitlab.com/girlbossceo/conduwuit"
readme = "README.md" readme = "README.md"
version = "0.7.0-alpha+conduwuit-0.1.8" version = "0.7.0-alpha+conduwuit-0.1.3"
edition = "2021" edition = "2021"
# See also `rust-toolchain.toml` # See also `rust-toolchain.toml`
rust-version = "1.75.0" rust-version = "1.75.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
# Used for secure identifiers
rand = "0.8.5"
# Used for conduit::Error type
thiserror = "1.0.58"
# Used to encode server public key
base64 = "0.22.0"
# Used when hashing the state
ring = "0.17.8"
# Used when querying the SRV record of other servers
trust-dns-resolver = "0.23.2"
# Used to find matching events for appservices
regex = "1.10.3"
# Used to load forbidden room/user regex from config
serde_regex = "1.1.0"
itertools = "0.12.1"
# jwt jsonwebtokens
jsonwebtoken = "9.2.0"
lru-cache = "0.1.2"
# Used for ruma wrapper
serde_html_form = "0.2.5"
# used for TURN server authentication
hmac = "0.12.1"
sha-1 = "0.10.1"
async-trait = "0.1.78"
# used for checking if an IP is in specific subnets / CIDR ranges easier
ipaddress = "0.1.3"
# to encode/decode percent URIs when conduwuit is running without a reverse proxy
#urlencoding = "2.1.3"
# to get the client IP address of requests
#axum-client-ip = "0.4.2"
# to parse user-friendly time durations in admin commands
cyborgtime = "2.1.1"
# all the web/HTTP dependencies
# Used for the http request / response body type for Ruma endpoints used with reqwest
bytes = "1.5.0"
http = "0.2.12"
# Web framework # Web framework
[dependencies.axum] axum = { version = "0.6.20", default-features = false, features = ["form", "headers", "http1", "http2", "json", "matched-path"], optional = true }
version = "0.6.20" axum-server = { version = "0.5.1", features = ["tls-rustls"] }
default-features = false tower = { version = "0.4.13", features = ["util"] }
features = ["form", "headers", "http1", "http2", "json", "matched-path"] tower-http = { version = "0.4.4", features = ["add-extension", "cors", "sensitive-headers", "trace", "util", "compression-zstd"] }
optional = true
[dependencies.axum-server]
version = "0.5.1"
features = ["tls-rustls"]
[dependencies.tower]
version = "0.4.13"
features = ["util"]
[dependencies.tower-http]
version = "0.4.4"
features = [
"add-extension",
"cors",
"sensitive-headers",
"trace",
"util",
]
[dependencies.hyper]
version = "0.14"
features = [
"server",
"http1",
"http2",
]
[dependencies.reqwest]
version = "0.11.26"
default-features = false
features = [
"rustls-tls-native-roots",
"socks",
"trust-dns",
]
# all the serde stuff
# Used for pdu definition
[dependencies.serde]
version = "1.0.197"
features = ["rc"]
# Used for appservice registration files
[dependencies.serde_yaml]
version = "0.9.32"
# Used for ruma wrapper
[dependencies.serde_json]
version = "1.0.114"
features = ["raw_value"]
# Used for password hashing
[dependencies.argon2]
version = "0.5.3"
features = [
"alloc",
"rand",
]
default-features = false
# Used to generate thumbnails for images
[dependencies.image]
version = "0.25.0"
default-features = false
features = [
"jpeg",
"png",
"gif",
"webp",
]
# logging
[dependencies.tracing]
version = "0.1.40"
default-features = false
[dependencies.tracing-subscriber]
version = "0.3.18"
features = ["env-filter"]
# optional SHA256 media keys feature
[dependencies.sha2]
version = "0.10.8"
optional = true
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
[dependencies.opentelemetry]
version = "0.21.0"
optional = true
[dependencies.tracing-flame]
version = "0.2.0"
optional = true
[dependencies.tracing-opentelemetry]
version = "0.22.0"
optional = true
[dependencies.opentelemetry_sdk]
version = "0.21.2"
optional = true
features = ["rt-tokio"]
[dependencies.opentelemetry-jaeger]
version = "0.20.0"
optional = true
features = ["rt-tokio"]
# optional jemalloc usage
[dependencies.tikv-jemallocator]
version = "0.5.4"
optional = true
default-features = false
features = ["unprefixed_malloc_on_supported_platforms"]
[dependencies.tikv-jemalloc-ctl]
version = "0.5.4"
optional = true
default-features = false
features = ["use_std"]
# for URL previews
[dependencies.webpage]
version = "2.0"
default-features = false
# to support multiple variations of setting a config option
[dependencies.either]
version = "1.10.0"
features = ["serde"]
# to listen on both HTTP and HTTPS if listening on TLS dierctly from conduwuit for complement or sytest
[dependencies.axum-server-dual-protocol]
version = "0.5.2"
optional = true
# used for conduit's CLI and admin room command parsing
[dependencies.clap]
version = "4.5.3"
default-features = false
features = [
"std",
"derive",
"help",
"usage",
"error-context",
]
[dependencies.futures-util]
version = "0.3.30"
default-features = false
# Used for reading the configuration from conduit.toml & environment variables
[dependencies.figment]
version = "0.10.15"
features = [
"env",
"toml",
]
# Used for matrix spec type definitions and helpers # Used for matrix spec type definitions and helpers
#ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] } #ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { git = "https://github.com/ruma/ruma", rev = "4d9f754657a099df8e61533787b8eebd12946435", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified", "unstable-msc2870", "unstable-msc3061", "unstable-msc2867", "unstable-extensible-events"] } #ruma = { git = "https://github.com/ruma/ruma", rev = "4d9f754657a099df8e61533787b8eebd12946435", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified", "unstable-msc2870", "unstable-msc3061", "unstable-msc2867", "unstable-extensible-events"] }
ruma = { git = "https://github.com/girlbossceo/ruma", rev = "788ea6b00fab49b04a17d88caa0c840b7d74aa13", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified", "unstable-msc2870", "unstable-msc3061", "unstable-msc2867", "unstable-extensible-events"] }
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified" ] } #ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified" ] }
[dependencies.ruma]
git = "https://github.com/girlbossceo/ruma"
branch = "conduwuit-changes"
features = [
"compat",
"rand",
"appservice-api-c",
"client-api",
"federation-api",
"push-gateway-api-c",
"state-res",
"unstable-msc2448",
"unstable-msc3575",
"unstable-exhaustive-types",
"ring-compat",
"unstable-unspecified",
"unstable-msc2870",
"unstable-msc3061",
"unstable-msc2867",
"unstable-extensible-events",
]
[dependencies.rust-rocksdb] # Async runtime and utilities
git = "https://github.com/zaidoon1/rust-rocksdb" hyperlocal = { git = "https://github.com/softprops/hyperlocal", rev = "2ee4d149644600d326559af0d2b235c945b05c04", features = [
#branch = "master" "server",
rev = "3e4a0f632a8c0c2839c7d183725c53895110d907" ] }
optional = true hyper = { version = "0.14", features = ["server", "http1", "http2"] }
default-features = true tokio = { version = "1.36.0", features = ["fs", "macros", "signal", "sync"] }
features = [
"multi-threaded-cf",
"zstd",
]
[dependencies.rusqlite] # Used for the http request / response body type for Ruma endpoints used with reqwest
git = "https://github.com/rusqlite/rusqlite" bytes = "1.5.0"
branch = "master" http = "0.2.11"
#rev = "def8e9460d8376a5c0c9f4f9846d413a9cd4581a" # Used for ruma wrapper
optional = true serde_json = { version = "1.0.114", features = ["raw_value"] }
features = ["bundled"] # Used for appservice registration files
serde_yaml = "0.9.32"
# Used for pdu definition
serde = { version = "1.0.197", features = ["rc"] }
# Used for secure identifiers
rand = "0.8.5"
# Used to hash passwords
argon2 = "0.5.3"
reqwest = { version = "0.11.24", default-features = false, features = ["rustls-tls-native-roots", "socks"] }
# Used for conduit::Error type
thiserror = "1.0.57"
# Used to generate thumbnails for images
image = { version = "0.24.8", default-features = false, features = ["jpeg", "png", "gif", "webp"] }
# Used to encode server public key
base64 = "0.21.7"
# Used when hashing the state
ring = "0.17.8"
# Used when querying the SRV record of other servers
trust-dns-resolver = "0.23.2"
# Used to find matching events for appservices
regex = "1.10.3"
# Used to load forbidden room/user regex from config
serde_regex = "1.1.0"
itertools = "0.12.1"
# jwt jsonwebtokens
jsonwebtoken = "9.2.0"
# Performance measurements
tracing = { version = "0.1.40", features = [] }
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
tracing-flame = "0.2.0"
opentelemetry = "0.21.0"
opentelemetry_sdk = { version = "0.21.2", features = ["rt-tokio"] }
opentelemetry-jaeger = { version = "0.20.0", features = ["rt-tokio"] }
tracing-opentelemetry = "0.22.0"
lru-cache = "0.1.2"
rusqlite = { git = "https://github.com/rusqlite/rusqlite", rev = "ccfbc28ae1edc3090fb1b331fdc145f052ec73b9", optional = true, features = ["bundled"] }
parking_lot = { version = "0.12.1", optional = true }
num_cpus = "1.16.0"
threadpool = "1.8.1"
# Used for ruma wrapper
serde_html_form = "0.2.4"
# used only by rusqlite thread_local = "1.1.7"
[dependencies.parking_lot] # used for TURN server authentication
version = "0.12.1" hmac = "0.12.1"
optional = true sha-1 = "0.10.1"
sha2 = { version = "0.10.8" }
# used for conduit's CLI and admin room command parsing
clap = { version = "4.5.1", default-features = false, features = ["std", "derive", "help", "usage", "error-context"] }
futures-util = { version = "0.3.30", default-features = false }
# Used for reading the configuration from conduit.toml & environment variables
figment = { version = "0.10.14", features = ["env", "toml"] }
# used only by rusqlite tikv-jemalloc-ctl = { version = "0.5.4", features = ["use_std"], optional = true }
[dependencies.thread_local] tikv-jemallocator = { version = "0.5.4", features = ["unprefixed_malloc_on_supported_platforms"], optional = true }
version = "1.1.8" lazy_static = "1.4.0"
optional = true async-trait = "0.1.77"
# used only by rusqlite and rust-rocksdb # used for checking if an IP is in specific subnets / CIDR ranges
[dependencies.num_cpus] ipaddress = "0.1.3"
version = "1.16.0"
optional = true sd-notify = { version = "0.4.1", optional = true }
webpage = { version = "2.0", default-features = false }
rocksdb = { version = "0.22.0", default-features = true, features = ["multi-threaded-cf", "zstd"], optional = true }
[dependencies.tokio]
version = "1.36.0"
features = [
"fs",
"macros",
"sync",
"signal",
]
# *nix-specific dependencies
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
nix = { version = "0.28.0", features = ["resource"] } nix = { version = "0.27.1", features = ["resource"] }
sd-notify = { version = "0.4.1", optional = true } # systemd is only available/relevant on *nix platforms
hyperlocal = { git = "https://github.com/softprops/hyperlocal", rev = "2ee4d149644600d326559af0d2b235c945b05c04", features = ["server"] } # unix socket support
[features] [features]
default = ["conduit_bin", "backend_rocksdb", "systemd"] default = ["conduit_bin", "backend_rocksdb", "systemd", "zstd_compression"]
conduit_bin = ["axum"]
backend_sqlite = ["sqlite"] backend_sqlite = ["sqlite"]
backend_rocksdb = ["rocksdb"] backend_rocksdb = ["rocksdb"]
rocksdb = ["rust-rocksdb", "num_cpus"]
jemalloc = ["tikv-jemalloc-ctl", "tikv-jemallocator"] jemalloc = ["tikv-jemalloc-ctl", "tikv-jemallocator"]
sqlite = ["rusqlite", "parking_lot", "thread_local", "num_cpus"] sqlite = ["rusqlite", "parking_lot", "tokio/signal"]
conduit_bin = ["axum"]
systemd = ["sd-notify"] systemd = ["sd-notify"]
#gzip_compression = ["tower-http/compression-gzip"] #gzip_compression = ["tower-http/compression-gzip"]
zstd_compression = ["tower-http/compression-zstd"] zstd_compression = []
#brotli_compression = ["tower-http/compression-br"] #brotli_compression = ["tower-http/compression-br"]
#all_compression = ["tower-http/compression-full"] # all compression algos #compression = ["tower-http/compression-full"]
sha256_media = []
sha256_media = ["sha2"] io_uring = ["rocksdb/io-uring"]
io_uring = ["rust-rocksdb/io-uring"]
axum_dual_protocol = ["axum-server-dual-protocol"]
perf_measurements = ["opentelemetry", "tracing-flame", "tracing-opentelemetry", "opentelemetry_sdk", "opentelemetry-jaeger"]
[[bin]] [[bin]]
name = "conduit" name = "conduit"
@@ -348,7 +148,6 @@ assets = [
["debian/README.md", "usr/share/doc/matrix-conduit/README.Debian", "644"], ["debian/README.md", "usr/share/doc/matrix-conduit/README.Debian", "644"],
["README.md", "usr/share/doc/matrix-conduit/", "644"], ["README.md", "usr/share/doc/matrix-conduit/", "644"],
["target/release/conduit", "usr/sbin/matrix-conduit", "755"], ["target/release/conduit", "usr/sbin/matrix-conduit", "755"],
["conduwuit-example.toml", "etc/matrix-conduit/conduit.toml", "640"],
] ]
conf-files = [ conf-files = [
"/etc/matrix-conduit/conduit.toml" "/etc/matrix-conduit/conduit.toml"
@@ -356,20 +155,10 @@ conf-files = [
maintainer-scripts = "debian/" maintainer-scripts = "debian/"
systemd-units = { unit-name = "matrix-conduit" } systemd-units = { unit-name = "matrix-conduit" }
[profile.dev] [profile.dev]
debug = 0 debug = 0
lto = 'off' lto = 'off'
codegen-units = 512
incremental = true incremental = true
# seems to speed up continuous debug compilations
[profile.dev.build-override]
opt-level = 3
[profile.dev.package."*"] # external dependencies
opt-level = 1
[profile.dev.package."tokio"]
opt-level = 3
# default release profile # default release profile
[profile.release] [profile.release]
@@ -379,7 +168,6 @@ opt-level = 3
overflow-checks = true overflow-checks = true
strip = "symbols" strip = "symbols"
panic = "abort" panic = "abort"
control-flow-guard = true # Windows only
debug = 0 debug = 0
# high performance release profile which uses fat LTO across all crates, 1 codegen unit, max opt-level, and optimises across all crates # high performance release profile which uses fat LTO across all crates, 1 codegen unit, max opt-level, and optimises across all crates
@@ -399,8 +187,6 @@ debug = 0
opt-level = 3 opt-level = 3
codegen-units = 1 codegen-units = 1
[lints] [lints]
workspace = true workspace = true
@@ -413,30 +199,17 @@ explicit_outlives_requirements = "warn"
# unreachable_pub = "warn" # unreachable_pub = "warn"
unused_extern_crates = "warn" unused_extern_crates = "warn"
unused_import_braces = "warn" unused_import_braces = "warn"
unused_lifetimes = "warn" # unused_lifetimes = "warn"
unused_qualifications = "warn" unused_qualifications = "warn"
unused_macro_rules = "warn"
dead_code = "warn" dead_code = "warn"
elided_lifetimes_in_paths = "warn"
macro_use_extern_crate = "warn"
single_use_lifetimes = "warn"
unsafe_op_in_unsafe_fn = "warn"
# not in rust 1.75.0 (doesn't break CI but won't check for it)
unit_bindings = "warn"
# this seems to suggest broken code and is not working correctly
unused_braces = "allow"
[workspace.lints.clippy] [workspace.lints.clippy]
# pedantic = "warn"
suspicious = "warn" # assume deny in practice suspicious = "warn" # assume deny in practice
perf = "warn" # assume deny in practice perf = "warn" # assume deny in practice
redundant_clone = "warn" redundant_clone = "warn"
cloned_instead_of_copied = "warn" cloned_instead_of_copied = "warn"
expl_impl_clone_on_copy = "warn" expl_impl_clone_on_copy = "warn"
# pedantic = "warn"
unnecessary_cast = "warn" unnecessary_cast = "warn"
cast_lossless = "warn" cast_lossless = "warn"
ptr_as_ptr = "warn" ptr_as_ptr = "warn"
@@ -468,43 +241,5 @@ unseparated_literal_suffix = "warn"
# unwrap_used = "warn" # unwrap_used = "warn"
# expect_used = "warn" # expect_used = "warn"
wildcard_dependencies = "warn" wildcard_dependencies = "warn"
or_fun_call = "warn" # or_fun_call = "warn"
unnecessary_lazy_evaluations = "warn" unnecessary_lazy_evaluations = "warn"
# as_conversions = "warn"
assertions_on_result_states = "warn"
default_union_representation = "warn"
deref_by_slicing = "warn"
empty_drop = "warn"
# error_impl_error = "warn"
exit = "warn"
filetype_is_file = "warn"
float_cmp_const = "warn"
format_push_string = "warn"
impl_trait_in_params = "warn"
ref_to_mut = "warn"
# let_underscore_untyped = "warn"
lossy_float_literal = "warn"
mem_forget = "warn"
missing_assert_message = "warn"
# mod_module_files = "warn"
# multiple_inherent_impl = "warn"
mutex_atomic = "warn"
# same_name_method = "warn"
semicolon_outside_block = "warn"
fn_to_numeric_cast = "warn"
fn_to_numeric_cast_with_truncation = "warn"
string_lit_chars_any = "warn"
suspicious_xor_used_as_pow = "warn"
try_err = "warn"
unnecessary_safety_comment = "warn"
unnecessary_safety_doc = "warn"
unnecessary_self_imports = "warn"
verbose_file_reads = "warn"
# cast_precision_loss = "warn"
cast_possible_wrap = "warn"
# cast_possible_truncation = "warn"
redundant_closure_for_method_calls = "warn"
large_futures = "warn"
# not in rust 1.75.0 (breaks CI)
# infinite_loop = "warn"
+26 -3
View File
@@ -9,9 +9,32 @@
## Installing conduwuit ## Installing conduwuit
You may simply download the binary that fits your machine. Run `uname -m` to see what you need. You may simply download the binary that fits your machine. Run `uname -m` to see what you need. Now copy the appropriate URL:
Prebuilt binaries can be downloaded from the latest successful CI workflow on the main branch here: https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml?query=branch%3Amain+actor%3Agirlbossceo **Stable versions:**
| CPU Architecture | Download stable version |
| ------------------------------------------- | --------------------------------------------------------------- |
| x84_64 / amd64 (Most servers and computers) | [Binary][x84_64-glibc-master] / [.deb][x84_64-glibc-master-deb] |
| armv7 (e.g. Raspberry Pi by default) | [Binary][armv7-glibc-master] / [.deb][armv7-glibc-master-deb] |
| armv8 / aarch64 | [Binary][armv8-glibc-master] / [.deb][armv8-glibc-master-deb] |
[x84_64-glibc-master]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_amd64/conduit?job=docker:master
[armv7-glibc-master]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_arm_v7/conduit?job=docker:master
[armv8-glibc-master]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_arm64/conduit?job=docker:master
[x84_64-glibc-master-deb]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_amd64/conduit.deb?job=docker:master
[armv7-glibc-master-deb]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_arm_v7/conduit.deb?job=docker:master
[armv8-glibc-master-deb]: https://gitlab.com/famedly/conduit/-/jobs/artifacts/master/raw/build-output/linux_arm64/conduit.deb?job=docker:master
**Latest versions:**
| Target | Type | Download |
|-|-|-|
| `x86_64-unknown-linux-gnu` | Dynamically linked Debian package | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/conduit.deb?job=debian:x86_64-unknown-linux-gnu) |
| `x86_64-unknown-linux-musl` | Statically linked binary | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/conduit?job=static:x86_64-unknown-linux-musl) |
| `aarch64-unknown-linux-musl` | Statically linked binary | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/conduit?job=static:aarch64-unknown-linux-musl) |
| `x86_64-unknown-linux-musl` | OCI image | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/oci-image-amd64.tar.gz?job=oci-image:x86_64-unknown-linux-musl) |
| `aarch64-unknown-linux-musl` | OCI image | [link](https://gitlab.com/api/v4/projects/famedly%2Fconduit/jobs/artifacts/next/raw/oci-image-arm64v8.tar.gz?job=oci-image:aarch64-unknown-linux-musl) |
```bash ```bash
$ sudo wget -O /usr/local/bin/matrix-conduit <url> $ sudo wget -O /usr/local/bin/matrix-conduit <url>
@@ -225,7 +248,7 @@ server {
location /_matrix/ { location /_matrix/ {
# TCP # TCP
proxy_pass http://127.0.0.1:6167; proxy_pass http://127.0.0.1:6167$request_uri;
# UNIX socket # UNIX socket
#proxy_pass http://backend; #proxy_pass http://backend;
+11 -24
View File
@@ -2,7 +2,6 @@
- GitLab CI ported to GitHub Actions - GitLab CI ported to GitHub Actions
- Fixed every single clippy (default lints) and rustc warnings, including some that were performance related or potential safety issues / unsoundness - Fixed every single clippy (default lints) and rustc warnings, including some that were performance related or potential safety issues / unsoundness
- Add a **lot** of other clippy and rustc lints and a rustfmt.toml file
- Has Renovate and significantly updates all dependencies possible - Has Renovate and significantly updates all dependencies possible
- Uses proper argon2 crate instead of questionable rust-argon2 crate - Uses proper argon2 crate instead of questionable rust-argon2 crate
- Improved and cleaned up logging (less noisy dead server logging, registration attempts, more useful troubleshooting logging, etc) - Improved and cleaned up logging (less noisy dead server logging, registration attempts, more useful troubleshooting logging, etc)
@@ -11,14 +10,17 @@
- Configurable RocksDB logging (`LOG` files) with proper defaults (rotate, max size, verbosity, etc) to stop LOG files from accumulating so much - Configurable RocksDB logging (`LOG` files) with proper defaults (rotate, max size, verbosity, etc) to stop LOG files from accumulating so much
- Federated presence support and configurable local presence (via upstream MR) - Federated presence support and configurable local presence (via upstream MR)
- Concurrency support for key fetching for faster remote room joins and room joins that will error less frequently (via upstream MR) - Concurrency support for key fetching for faster remote room joins and room joins that will error less frequently (via upstream MR)
- Room version 11 support (via upstream MR) - Experimental room version 11 support (via upstream MR)
- Config option to allow guest registrations - Enabled all non-officially-supported room versions as experimental so we can at least attempt to join them
- Configurable guest registration including forbidding guest registrations if no admin user is created yet, respects allow registration setting, and an optional override setting with a default of no guest registrations allowed.
- Explicit startup error/warning if your configuration allows open registration without a token or such like Synapse - Explicit startup error/warning if your configuration allows open registration without a token or such like Synapse
- Improved RocksDB defaults to use new features that help with performance significantly, uses settings tailored to SSDs, various ways to tweak RocksDB, and a conduwuit setting to tell RocksDB to use settings that are tailored to HDDs or slow spinning rust storage. - Improved RocksDB defaults to use new features that help with performance significantly, uses settings tailored to SSDs, and a conduwuit setting to tell RocksDB to use settings that are tailored to HDDs or slow spinning rust storage.
- Updated Ruma to latest commit where possible, and add some unstable MSCs (some still require an implementation though) - Updated Ruma to latest commit where possible, and add some unstable MSCs (some still require an implementation though)
- conduwuit allows MXIDs with `+` in them (thanks to Ruma update)
- Revamped admin room infrastructure and commands (via upstream MR) - Revamped admin room infrastructure and commands (via upstream MR)
- Admin room commands to delete room aliases and unpublish rooms from our room directory (via upstream MR) - Admin room commands to delete room aliases and unpublish rooms from our room directory (via upstream MR)
- Make spaces/hierarchy cache use cache_capacity_modifier instead of hardcoded small value - Make spaces/hierarchy cache use cache_capacity_modifier instead of hardcoded small value
- Make PDU appending, building, etc asynchronous
- Add *optional* feature flag to use SHA256 key names for media instead of base64 to overcome filesystem file name length limitations (OS error file name too long) (via upstream MR) - Add *optional* feature flag to use SHA256 key names for media instead of base64 to overcome filesystem file name length limitations (OS error file name too long) (via upstream MR)
- Add *optional* feature flag to enable zstd HTTP body compression - Add *optional* feature flag to enable zstd HTTP body compression
- Add support for querying both Matrix SRV records, the deprecated `_matrix` record and `_matrix-fed` record if necessary - Add support for querying both Matrix SRV records, the deprecated `_matrix` record and `_matrix-fed` record if necessary
@@ -27,6 +29,7 @@
- Add config option for federating `/publicRooms` endpoint (room directory) to other servers with a default disabled for privacy - Add config option for federating `/publicRooms` endpoint (room directory) to other servers with a default disabled for privacy
- Add support for listening on a UNIX socket for performance and host security with proper default permissions (660) - Add support for listening on a UNIX socket for performance and host security with proper default permissions (660)
- Add missing `destination` key to all `X-Matrix` `Authorization` requests (spec compliance issue) - Add missing `destination` key to all `X-Matrix` `Authorization` requests (spec compliance issue)
- Fix spec compliance issue with servers being able to fetch remote user profiles over federation for users who don't belong to our server (`/_matrix/federation/v1/query/profile`)
- Use aggressive build-time performance optimisations for release builds (1 codegen unit, no debug, fat LTO, etc, and optimise all crates with same) - Use aggressive build-time performance optimisations for release builds (1 codegen unit, no debug, fat LTO, etc, and optimise all crates with same)
- Raise various hardcoded timeouts in codebase that were way too short, making some things like room joins and client bugs error less or none at all than they should - Raise various hardcoded timeouts in codebase that were way too short, making some things like room joins and client bugs error less or none at all than they should
- Add debug admin command to force update user device lists (could potentially resolve some E2EE flukes) (`ForceDeviceListUpdates`) - Add debug admin command to force update user device lists (could potentially resolve some E2EE flukes) (`ForceDeviceListUpdates`)
@@ -35,6 +38,7 @@
- Add non-standard sliding sync proxy health check (?) endpoint at `/client/server.json` that some clients such as Element Web query using the `well_known_client` or `well_known_server` config options - Add non-standard sliding sync proxy health check (?) endpoint at `/client/server.json` that some clients such as Element Web query using the `well_known_client` or `well_known_server` config options
- Send a User-Agent on all of our requests (`conduwuit/0.7.0-alpha+conduwuit-0.1.1`) which strangely was not done upstream since forever. Some providers consider no User-Agent suspicious and block said requests. - Send a User-Agent on all of our requests (`conduwuit/0.7.0-alpha+conduwuit-0.1.1`) which strangely was not done upstream since forever. Some providers consider no User-Agent suspicious and block said requests.
- Safer and cleaner shutdowns on both database side as we run cleanup on shutdown and exits database loop better (no potential hanging issues in database loop), overall cleaner shutdown logic - Safer and cleaner shutdowns on both database side as we run cleanup on shutdown and exits database loop better (no potential hanging issues in database loop), overall cleaner shutdown logic
- Basic binary commands like `conduwuit --version` work (interested in expanding it more)
- Allow HEAD HTTP requests in CORS for clients (despite not being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need to behave the same as GET requests, Synapse supports HEAD requests) - Allow HEAD HTTP requests in CORS for clients (despite not being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need to behave the same as GET requests, Synapse supports HEAD requests)
- Purge unmaintained/irrelevant/broken database backends (heed, sled, persy) - Purge unmaintained/irrelevant/broken database backends (heed, sled, persy)
- webp support for images - webp support for images
@@ -52,7 +56,7 @@
- Revamp example config, adding a lot of config options available (still some missing) - Revamp example config, adding a lot of config options available (still some missing)
- Return joined member count of rooms for push rules/conditions instead of a hardcoded value of 10 - Return joined member count of rooms for push rules/conditions instead of a hardcoded value of 10
- Respect *most* client parameters for `/media/` requests (`allow_redirect` still needs work) - Respect *most* client parameters for `/media/` requests (`allow_redirect` still needs work)
- Config option `ip_range_denylist` to support refusing to send requests (typically federation) to specific IP ranges, typically RFC 1918, non-routable, testnet, etc addresses like Synapse for security (note: this is not a guaranteed protection, and you should be using a firewall with zones if you want guaranteed protection as doing this on the application level is prone to bypasses). - Config option `ip_range_denylist` to support refusing to send requests (typically federation) to specific IP ranges, typically RFC 1918, non-routable, testnet, etc addresses like Synapse for security.
- Support for creating rooms with custom room IDs like Maunium Synapse (`room_id` request body field to `/createRoom`) - Support for creating rooms with custom room IDs like Maunium Synapse (`room_id` request body field to `/createRoom`)
- Assume well-knowns are broken if they exceed past 10000 characters. - Assume well-knowns are broken if they exceed past 10000 characters.
- Basic validation/checks on user-specified room aliases and custom room ID creations - Basic validation/checks on user-specified room aliases and custom room ID creations
@@ -62,23 +66,6 @@
- URL preview support (via upstream MR) with various improvements - URL preview support (via upstream MR) with various improvements
- Increased graceful shutdown timeout from a low 60 seconds to 180 seconds to avoid killing connections and let the remaining ones finish processing, and ask systemd for more time to shutdown if needed to prevent systemd's default [`TimeoutStopSec=`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#TimeoutStopSec=) of 90 seconds from killing conduwuit - Increased graceful shutdown timeout from a low 60 seconds to 180 seconds to avoid killing connections and let the remaining ones finish processing, and ask systemd for more time to shutdown if needed to prevent systemd's default [`TimeoutStopSec=`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#TimeoutStopSec=) of 90 seconds from killing conduwuit
- Bumped default max_concurrent_requests to 500 - Bumped default max_concurrent_requests to 500
- Add support for the deprecated `user` identifier field for all `/login` requests
- Query parameter `?format=event|content` for returning either the room state event's content (default) for the full room state event on ` /_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}]` requests (see https://github.com/matrix-org/matrix-spec/issues/1047) - Query parameter `?format=event|content` for returning either the room state event's content (default) for the full room state event on ` /_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}]` requests (see https://github.com/matrix-org/matrix-spec/issues/1047)
- Add admin commands for banning (blocking) room IDs from our local users joining (admins are always allowed) and evicts all our local users from that room, in addition to bulk room banning support, and blocks room invites (remote and local) to the banned room, as a moderation feature - Add admin commands for banning (blocking) room IDs from our local users joining (admins are always allowed) and evicts all our local users from that room, in addition to bulk room banning support, as a moderation feature
- Add admin command to delete media via a specific MXC. This deletes the MXC from our database, and the file locally.
- Replace the lightning bolt emoji option with support for setting any arbitrary text (e.g. another emoji) to suffix to all new user registrations
- Add admin command to bulk delete media via a codeblock list of MXC URLs.
- Add admin command to delete both the thumbnail and media MXC URLs from an event ID (e.g. from an abuse report)
- Add `!admin` as a way to call the Conduit admin bot
- Add support for listening on multiple TCP ports
- Add admin command to list all the rooms a local user is joined in
- Add admin command to delete all remote media in the past X minutes as a form of deleting media that you don't want on your server that a remote user posted in a room
- Config option to block non-admin users from sending room invites or receiving remote room invites. Admin users are still allowed.
- Startup check if conduwuit running in a container and is listening on 127.0.0.1
- Make `CONDUIT_CONFIG` optional, relevant for container users that configure only by environment variables and no longer need to set `CONDUIT_CONFIG` to an empty string.
- Config option to change Conduit's behaviour of homeserver key fetching (`query_trusted_key_servers_first`). This option sets whether conduwuit will query trusted notary key servers first before the individual homeserver(s), or vice versa.
- Implement database flush and cleanup Conduit operations when using RocksDB
- Implement legacy Matrix `/v1/` media endpoints that some clients and servers may still call
- Commandline argument to specify the path to a config file
- Admin debug command to fetch a PDU from a remote server and inserts it into our database/timeline
- Update rusqlite/sqlite (not that you should be using it)
- Disable update check by default as it's not useful for conduwuit
+24 -27
View File
@@ -1,12 +1,10 @@
# conduwuit # conduwuit
### a well maintained fork of [Conduit](https://conduit.rs/) ### a well maintained fork of [Conduit](https://conduit.rs/)
[![CI and Artifacts](https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml)
#### What is Matrix? #### What is Matrix?
[Matrix](https://matrix.org) is an open network for secure and decentralized [Matrix](https://matrix.org) is an open network for secure and decentralized
communication. Users from every Matrix homeserver can chat with users from all communication. Users from every Matrix homeserver can chat with users from all
other Matrix servers. You can even use bridges (also called Matrix Appservices) other Matrix servers. You can even use bridges (also called Matrix appservices)
to communicate with users outside of Matrix, like a community on Discord. to communicate with users outside of Matrix, like a community on Discord.
#### What is the goal? #### What is the goal?
@@ -17,13 +15,15 @@ friends or company.
#### Can I try it out? #### Can I try it out?
An official conduwuit server ran by me is available at transfem.dev ([element.transfem.dev](https://element.transfem.dev) / [cinny.transfem.dev](https://cinny.transfem.dev)) There are no public conduwuit homeservers available, however conduwuit is incredibly simple to install. It's just a binary, a config file, and a database path.
#### What is the current status? #### What is the current status?
conduwuit is a fork of Conduit which is in beta, meaning you can join and participate in most conduwuit is a fork of Conduit which is in beta, meaning you can join and participate in most
Matrix rooms, but not all features are supported and you might run into bugs Matrix rooms, but not all features are supported and you might run into bugs
from time to time. from time to time. conduwuit attempts to fix and improve the majority of upstream Conduit bugs
or UX issues that are taking too long to be resolved, or unnecessary Matrix or developer
politics halting simple things from being merged or fixed, and general inactivity.
There are still a few nice to have features missing that some users may notice: There are still a few nice to have features missing that some users may notice:
@@ -35,23 +35,23 @@ See [DIFFERENCES.md](DIFFERENCES.md)
#### Why does this fork exist? Why don't you contribute back upstream? #### Why does this fork exist? Why don't you contribute back upstream?
I now intend on contributing back as time and mental energy sees fit, but my fork still exists as a way to: I have tried, but:
- avoid unnecessary Matrix and general developer politics - unnecessary Matrix / developer politics
- avoid bikeshedding unnecessary or irrelevant things in upstream MRs - bikeshedding unnecessary or irrelevant things in MRs
- Fast tracked bug fixes, performance improvements, security improvements, and new features - disagreement with how the upstream project is maintained including the codebase
- Have early access to MRs that may not be suitable/acceptable for Conduit (e.g. too niche, too advanced for general users, only being blocked due to pending on contributor actions that we can fix ourselves downstream, pending Matrix spec stuff, etc) - upstream maintainer inactivity
- Support unspecced or WIP features - questionable community members
- Have official support for other OS's like Windows, macOS, and BSD. - lack of MR reviews or issue triaging and no upstream maintainer interest in receiving help
- Have a **stable** testing ground for some MRs or new features and bug fixes - severe bugs, including denial of service and other likely vulnerabilities, not being merged due to things mentioned above
- no interest in adding co-maintainers to help out
And various other reasons that may not be listed here. are what are keeping me from contributing. If the state of the upstream project improves, I'm
willing to start contributing again. As is, I think if folks want a more polished and well-kept version of Conduit, conduwuit exists for that.
#### How can I deploy my own? #### How can I deploy my own?
conduwuit officially supports Linux, macOS, BSD, and Windows.
- Simple install (this was tested the most): [DEPLOY.md](DEPLOY.md) - Simple install (this was tested the most): [DEPLOY.md](DEPLOY.md)
- Nix/NixOS (and binary cache): [nix/README.md](nix/README.md) - Nix/NixOS: [nix/README.md](nix/README.md)
If you want to connect an Appservice to Conduit, take a look at [APPSERVICES.md](APPSERVICES.md). If you want to connect an Appservice to Conduit, take a look at [APPSERVICES.md](APPSERVICES.md).
@@ -62,7 +62,8 @@ If you want to connect an Appservice to Conduit, take a look at [APPSERVICES.md]
2. Ask someone to assign the issue to you (comment on the issue or chat in 2. Ask someone to assign the issue to you (comment on the issue or chat in
[#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay)) [#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay))
3. Fork the repo and work on the issue. 3. Fork the repo and work on the issue.
4. Submit a PR (please keep contributions to the GitHub repo, main development is done here, not the GitLab repo which exists just as a mirror. If you are avoiding GitHub, feel free to join our Matrix chat to get your patch in.) 4. Submit a PR (please keep contributions to the GitHub repo, main development is done here,
not the GitLab repo which exists just as a mirror.)
#### Contact #### Contact
@@ -80,14 +81,10 @@ GitHub Sponsors: <https://github.com/sponsors/girlbossceo>
No official conduwuit logo exists. Repo and Matrix room picture is from bran (<3). No official conduwuit logo exists. Repo and Matrix room picture is from bran (<3).
#### Is it conduwuit or Conduwuit?
Both.
#### Mirrors of conduwuit #### Mirrors of conduwuit
GitHub: <https://github.com/girlbossceo/conduwuit>\ GitHub: https://github.com/girlbossceo/conduwuit
GitLab: <https://gitlab.com/girlbossceo/conduwuit>\ GitLab: https://gitlab.com/girlbossceo/conduwuit
git.gay: <https://git.gay/june/conduwuit>\ git.gay: https://git.gay/june/conduwuit
Codeberg: <https://codeberg.org/girlbossceo/conduwuit>\ Codeberg: https://codeberg.org/girlbossceo/conduwuit
sourcehut: <https://git.sr.ht/~girlbossceo/conduwuit> sourcehut: https://git.sr.ht/~girlbossceo/conduwuit
Executable → Regular
View File
+27 -18
View File
@@ -8,34 +8,43 @@ INSTALLABLE="$1"
# Build the installable and forward any other arguments too # Build the installable and forward any other arguments too
nix build -L "$@" nix build -L "$@"
if [ ! -z "$ATTIC_TOKEN" ]; then if [ ! -z ${ATTIC_TOKEN+x} ]; then
nix run --inputs-from . attic -- \
login \ nix run --inputs-from . attic -- login \
conduit \ conduit \
"${ATTIC_ENDPOINT:-https://attic.kennel.juneis.dog/conduit}" \ https://attic.kennel.juneis.dog/conduit \
"$ATTIC_TOKEN" "$ATTIC_TOKEN"
# Push the target installable and its build dependencies push_args=(
nix run --inputs-from . attic -- \ # Attic and its build dependencies
push \ "$(nix path-info --inputs-from . attic)"
conduit \ "$(nix path-info --inputs-from . attic --derivation)"
"$(nix path-info "$INSTALLABLE" --derivation)" \
"$(nix path-info "$INSTALLABLE")"
# The target installable and its build dependencies
"$(nix path-info "$INSTALLABLE" --derivation)"
"$(nix path-info "$INSTALLABLE")"
)
nix run --inputs-from . attic -- push conduit "${push_args[@]}"
# push to "conduwuit" too # push to "conduwuit" too
nix run --inputs-from . attic -- \ nix run --inputs-from . attic -- login \
login \
conduwuit \ conduwuit \
"${ATTIC_ENDPOINT:-https://attic.kennel.juneis.dog/conduwuit}" \ https://attic.kennel.juneis.dog/conduwuit \
"$ATTIC_TOKEN" "$ATTIC_TOKEN"
# Push the target installable and its build dependencies push_args=(
nix run --inputs-from . attic -- \ # Attic and its build dependencies
push \ "$(nix path-info --inputs-from . attic)"
conduwuit \ "$(nix path-info --inputs-from . attic --derivation)"
"$(nix path-info "$INSTALLABLE" --derivation)" \
# The target installable and its build dependencies
"$(nix path-info "$INSTALLABLE" --derivation)"
"$(nix path-info "$INSTALLABLE")" "$(nix path-info "$INSTALLABLE")"
)
nix run --inputs-from . attic -- push conduwuit "${push_args[@]}"
else else
echo "\$ATTIC_TOKEN is unset, skipping uploading to the binary cache" echo "\$ATTIC_TOKEN is unset, skipping uploading to the binary cache"
fi fi
+21 -39
View File
@@ -8,57 +8,39 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
COPY Cargo.toml Cargo.toml COPY Cargo.toml Cargo.toml
COPY Cargo.lock Cargo.lock COPY Cargo.lock Cargo.lock
COPY src src COPY src src
RUN cargo build --release --features=axum_dual_protocol \ RUN cargo build --release \
&& mv target/release/conduit conduit \ && mv target/release/conduit conduit \
&& rm -rf target && rm -rf target
COPY conduwuit-example.toml conduit.toml # Install caddy
RUN apt-get update \
&& apt-get install -y \
debian-keyring \
debian-archive-keyring \
apt-transport-https \
curl \
&& curl -1sLf 'https://dl.cloudsmith.io/public/caddy/testing/gpg.key' \
| gpg --dearmor -o /usr/share/keyrings/caddy-testing-archive-keyring.gpg \
&& curl -1sLf 'https://dl.cloudsmith.io/public/caddy/testing/debian.deb.txt' \
| tee /etc/apt/sources.list.d/caddy-testing.list \
&& apt-get update \
&& apt-get install -y caddy
COPY conduit-example.toml conduit.toml
COPY complement/caddy.json caddy.json
ENV SERVER_NAME=localhost ENV SERVER_NAME=localhost
ENV CONDUIT_CONFIG=/workdir/conduit.toml ENV CONDUIT_CONFIG=/workdir/conduit.toml
RUN sed -i "s/port = 6167/port = [8448, 8008]/g" conduit.toml RUN sed -i "s/port = 6167/port = 8008/g" conduit.toml
RUN sed -i "s/allow_registration = false/allow_registration = true/g" conduit.toml RUN echo "log = \"warn,_=off,sled=off\"" >> conduit.toml
RUN sed -i "s/registration_token/#registration_token/g" conduit.toml
RUN sed -i "s/allow_guest_registration = false/allow_guest_registration = true/g" conduit.toml
RUN sed -i "s/allow_public_room_directory_over_federation = false/allow_public_room_directory_over_federation = true/g" conduit.toml
RUN sed -i "s/allow_public_room_directory_without_auth = false/allow_public_room_directory_without_auth = true/g" conduit.toml
RUN sed -i "s/allow_device_name_federation = false/allow_device_name_federation = true/g" conduit.toml
RUN sed -i "/\"127.0.0.0/d" conduit.toml
RUN sed -i "/\"10.0.0.0/d" conduit.toml
RUN sed -i "/\"172.16.0.0/d" conduit.toml
RUN sed -i "/\"::1/d" conduit.toml
RUN sed -i "s/#log = \"warn\"/log = \"debug\"/g" conduit.toml
RUN sed -i 's/#\strusted_servers\s=\s\["matrix.org"\]/trusted_servers = []/g' conduit.toml
RUN sed -i 's/# `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` to/yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse = true/g' conduit.toml
RUN sed -i "s/allow_outgoing_presence = false/allow_outgoing_presence = true/g" conduit.toml
RUN sed -i "s/allow_incoming_presence = false/allow_incoming_presence = true/g" conduit.toml
RUN sed -i "s/allow_local_presence = false/allow_local_presence = true/g" conduit.toml
RUN sed -i "s/address = \"127.0.0.1\"/address = \"0.0.0.0\"/g" conduit.toml RUN sed -i "s/address = \"127.0.0.1\"/address = \"0.0.0.0\"/g" conduit.toml
# https://stackoverflow.com/questions/76049656/unexpected-notvalidforname-with-rusts-tonic-with-tls
RUN echo "authorityKeyIdentifier=keyid,issuer" >> extensions.ext
RUN echo "basicConstraints=CA:FALSE" >> extensions.ext
RUN echo 'subjectAltName = @alt_names' >> extensions.ext
RUN echo '[alt_names]' >> extensions.ext
RUN echo "DNS.1 = servername" >> extensions.ext
RUN echo "IP.1 = ipaddress" >> extensions.ext
EXPOSE 8008 8448 EXPOSE 8008 8448
CMD uname -a && \ CMD uname -a && \
cp -f -v /complement/ca/ca.crt /usr/local/share/ca-certificates/complement.crt && \
update-ca-certificates && \
sed -i "s/servername/${SERVER_NAME}/g" extensions.ext && \
sed -i "s/ipaddress/`hostname -i`/g" extensions.ext && \
openssl req -newkey rsa:2048 -noenc -subj "/C=US/ST=CA/O=MyOrg, Inc./CN=$SERVER_NAME" -keyout $SERVER_NAME.key -out $SERVER_NAME.csr && \
openssl x509 -signkey $SERVER_NAME.key -in $SERVER_NAME.csr -req -days 2 -out $SERVER_NAME.crt && \
openssl x509 -req -CA /complement/ca/ca.crt -CAkey /complement/ca/ca.key -in $SERVER_NAME.csr -out $SERVER_NAME.crt -days 2 -CAcreateserial -extfile extensions.ext && \
sed -i "s/#server_name = \"your.server.name\"/server_name = \"${SERVER_NAME}\"/g" conduit.toml && \ sed -i "s/#server_name = \"your.server.name\"/server_name = \"${SERVER_NAME}\"/g" conduit.toml && \
sed -i 's/#\s\[global.tls\]/\[global.tls\]/g' conduit.toml && \ sed -i "s/your.server.name/${SERVER_NAME}/g" caddy.json && \
sed -i "s/# certs = \"\/path\/to\/my\/certificate.crt\"/certs = \"${SERVER_NAME}.crt\"/g" conduit.toml && \ caddy start --config caddy.json > /dev/null && \
sed -i "s/# key = \"\/path\/to\/my\/private_key.key\"/key = \"${SERVER_NAME}.key\"/g" conduit.toml && \
sed -i "s/#dual_protocol = false/dual_protocol = true/g" conduit.toml && \
/workdir/conduit /workdir/conduit
+72
View File
@@ -0,0 +1,72 @@
{
"logging": {
"logs": {
"default": {
"level": "WARN"
}
}
},
"apps": {
"http": {
"https_port": 8448,
"servers": {
"srv0": {
"listen": [":8448"],
"routes": [{
"match": [{
"host": ["your.server.name"]
}],
"handle": [{
"handler": "subroute",
"routes": [{
"handle": [{
"handler": "reverse_proxy",
"upstreams": [{
"dial": "127.0.0.1:8008"
}]
}]
}]
}],
"terminal": true
}],
"tls_connection_policies": [{
"match": {
"sni": ["your.server.name"]
}
}]
}
}
},
"pki": {
"certificate_authorities": {
"local": {
"name": "Complement CA",
"root": {
"certificate": "/complement/ca/ca.crt",
"private_key": "/complement/ca/ca.key"
},
"intermediate": {
"certificate": "/complement/ca/ca.crt",
"private_key": "/complement/ca/ca.key"
}
}
}
},
"tls": {
"automation": {
"policies": [{
"subjects": ["your.server.name"],
"issuers": [{
"module": "internal"
}],
"on_demand": true
}, {
"issuers": [{
"module": "internal",
"ca": "local"
}]
}]
}
}
}
}
+20 -148
View File
@@ -22,14 +22,10 @@
# YOU NEED TO EDIT THIS # YOU NEED TO EDIT THIS
#server_name = "your.server.name" #server_name = "your.server.name"
# Servers listed here will be used to gather public keys of other servers (notary trusted key servers). # Servers listed here will be used to gather public keys of other servers.
# # Generally, copying this exactly should be enough. (Currently, conduwuit doesn't
# The default behaviour for conduwuit is to attempt to query trusted key servers before querying the individual servers. # support batched key requests, so this list should only contain Synapse
# This is done for performance reasons, but if you would like to query individual servers before the notary servers # servers.) Defaults to `matrix.org`
# configured below, set to
#
# (Currently, conduwuit doesn't support batched key requests, so this list should only contain Synapse servers)
# Defaults to `matrix.org`
# trusted_servers = ["matrix.org"] # trusted_servers = ["matrix.org"]
@@ -37,7 +33,7 @@
### Database configuration ### Database configuration
# This is the only directory where conduwuit will save its data, including media # This is the only directory where conduwuit will save its data, including media
database_path = "/var/lib/matrix-conduit/" database_path = "/var/lib/conduwuit/"
# Database backend: Only rocksdb and sqlite are supported. Please note that sqlite # Database backend: Only rocksdb and sqlite are supported. Please note that sqlite
# will perform significantly worse than rocksdb as it is not intended to be used the # will perform significantly worse than rocksdb as it is not intended to be used the
@@ -48,11 +44,10 @@ database_backend = "rocksdb"
### Network ### Network
# The port(s) conduwuit will be running on. You need to set up a reverse proxy such as # The port conduwuit will be running on. You need to set up a reverse proxy such as
# Caddy or Nginx so all requests to /_matrix on port 443 and 8448 will be # Caddy or Nginx so all requests to /_matrix on port 443 and 8448 will be
# forwarded to the conduwuit instance running on this port # forwarded to the conduwuit instance running on this port
# Docker users: Don't change this, you'll need to map an external port to this. # Docker users: Don't change this, you'll need to map an external port to this.
# To listen on multiple ports, specify a vector e.g. [8080, 8448]
port = 6167 port = 6167
# default address (IPv4 or IPv6) conduwuit will listen on. Generally you want this to be # default address (IPv4 or IPv6) conduwuit will listen on. Generally you want this to be
@@ -85,7 +80,6 @@ max_request_size = 20_000_000 # in bytes
#unix_socket_perms = 660 #unix_socket_perms = 660
# Set this to true for conduwuit to compress HTTP response bodies using zstd. # Set this to true for conduwuit to compress HTTP response bodies using zstd.
# This option does nothing if conduwuit was not built with `zstd_compression` feature.
# Please be aware that enabling HTTP compression may weaken or even defeat TLS. # Please be aware that enabling HTTP compression may weaken or even defeat TLS.
# Most users should not need to enable this. # Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this. # See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
@@ -95,7 +89,6 @@ zstd_compression = false
# Defaults to RFC1918, unroutable, loopback, multicast, and testnet addresses for security. # Defaults to RFC1918, unroutable, loopback, multicast, and testnet addresses for security.
# #
# To disable, set this to be an empty vector (`[]`). # To disable, set this to be an empty vector (`[]`).
# Please be aware that this is *not* a guarantee. You should be using a firewall with zones as doing this on the application layer may have bypasses.
# #
# Currently this does not account for proxies in use like Synapse does. # Currently this does not account for proxies in use like Synapse does.
ip_range_denylist = [ ip_range_denylist = [
@@ -132,7 +125,7 @@ allow_guest_registration = false
# No default. # No default.
# prevent_media_downloads_from = ["example.com", "example.local"] # prevent_media_downloads_from = ["example.com", "example.local"]
# Enables registration. If set to false, no users can register on this # Enables open registration. If set to false, no users can register on this
# server. # server.
# If set to true without a token configured, users can register with no form of 2nd- # If set to true without a token configured, users can register with no form of 2nd-
# step only if you set # step only if you set
@@ -158,23 +151,6 @@ registration_token = "change this token for something specific to your server"
# defaults to true # defaults to true
# allow_room_creation = true # allow_room_creation = true
# controls whether non-admin local users are forbidden from sending room invites (local and remote),
# and if non-admin users can receive remote room invites. admins are always allowed to send and receive all room invites.
# defaults to false
# block_non_admin_invites = false
# List of forbidden username patterns/strings. Values in this list are matched as *contains*.
# This is checked upon username availability check, registration, and startup as warnings if any local users in your database
# have a forbidden username.
# No default.
# forbidden_usernames = []
# List of forbidden room aliases and room IDs as patterns/strings. Values in this list are matched as *contains*.
# This is checked upon room alias creation, custom room ID creation if used, and startup as warnings if any room aliases
# in your database have a forbidden room alias/ID.
# No default.
# forbidden_room_names = []
# Set this to true to allow your server's public room directory to be federated. # Set this to true to allow your server's public room directory to be federated.
# Set this to false to protect against /publicRooms spiders, but will forbid external users # Set this to false to protect against /publicRooms spiders, but will forbid external users
# from viewing your server's public room directory. If federation is disabled entirely # from viewing your server's public room directory. If federation is disabled entirely
@@ -217,18 +193,20 @@ url_preview_check_root_domain = false
### Misc ### Misc
# max log level for conduwuit. allows debug, info, warn, or error # max log level for conduwuit. allows debug, info, warn, or error
# see also: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
# Defaults to "warn"
#log = "warn" #log = "warn"
# controls whether encrypted rooms and events are allowed (default true) # controls whether encrypted rooms and events are allowed (default true)
#allow_encryption = false #allow_encryption = false
# if enabled, conduwuit will send a simple GET request periodically to `https://pupbrain.dev/check-for-updates/stable` # conduwuit will send a simple GET request periodically to `https://pupbrain.dev/check-for-updates/stable`
# for any new announcements made. Despite the name, this is not an update check # for any new announcements made. Despite the name, this is not an update check
# endpoint, it is simply an announcement check endpoint. # endpoint, it is simply an announcement check endpoint. I don't plan on using
# Defaults to false. # this so feel free to disable it.
#allow_check_for_updates = false allow_check_for_updates = true
# Enables adding the lightning bolt emoji (⚡️) to all newly registered users'
# initial display names.
enable_lightning_bolt = false
# If you are using delegation via well-known files and you cannot serve them from your reverse proxy, you can # If you are using delegation via well-known files and you cannot serve them from your reverse proxy, you can
# uncomment these to serve them directly from conduwuit. This requires proxying all requests to conduwuit, not just `/_matrix` to work. # uncomment these to serve them directly from conduwuit. This requires proxying all requests to conduwuit, not just `/_matrix` to work.
@@ -237,36 +215,10 @@ url_preview_check_root_domain = false
# Note that whatever you put will show up in the well-known JSON values. # Note that whatever you put will show up in the well-known JSON values.
# Set to false to disable users from joining or creating room versions that aren't 100% officially supported by conduwuit. # Set to false to disable users from joining or creating room versions that aren't 100% officially supported by conduwuit.
# conduwuit officially supports room versions 6 - 10. conduwuit has experimental/unstable support for 3 - 5, and 11. # conduwuit officially supports room versions 6 - 10. conduwuit has experimental/unstable support for 1 - 5, and 11.
# Defaults to true. # Defaults to true.
#allow_unstable_room_versions = true #allow_unstable_room_versions = true
# Option to control adding arbitrary text to the end of the user's displayname upon registration with a space before the text.
# This was the lightning bolt emoji option, just replaced with support for adding your own custom text or emojis.
# To disable, set this to "" (an empty string)
# Defaults to "🏳️‍⚧️" (trans pride flag)
#new_user_displayname_suffix = "🏳️‍⚧️"
# Option to control whether conduwuit will query your list of trusted notary key servers (`trusted_servers`) for
# remote homeserver signing keys it doesn't know *first*, or query the individual servers first before falling back to the trusted
# key servers.
#
# The former/default behaviour makes federated/remote rooms joins generally faster because we're querying a single (or list of) server
# that we know works, is reasonably fast, and is reliable for just about all the homeserver signing keys in the room. Querying individual
# servers may take longer depending on the general infrastructure of everyone in there, how many dead servers there are, etc.
#
# However, this does create an increased reliance on one single or multiple large entities as `trusted_servers` should generally
# contain long-term and large servers who know a very large number of homeservers.
#
# If you don't know what any of this means, leave this and `trusted_servers` alone to their defaults.
#
# Defaults to true as this is the fastest option for federation.
#query_trusted_key_servers_first = true
### Generic database options
# Set this to any float value to multiply conduwuit's in-memory LRU caches with. # Set this to any float value to multiply conduwuit's in-memory LRU caches with.
# May be useful if you have significant memory to spare to increase performance. # May be useful if you have significant memory to spare to increase performance.
# Defaults to 1.0. # Defaults to 1.0.
@@ -277,33 +229,16 @@ url_preview_check_root_domain = false
# Defaults to 300.0 # Defaults to 300.0
#db_cache_capacity_mb = 300.0 #db_cache_capacity_mb = 300.0
# Interval in seconds when conduwuit will run database cleanup operations.
#
# For SQLite: this will flush the WAL by executing `PRAGMA wal_checkpoint(RESTART)` (https://www.sqlite.org/pragma.html#pragma_wal_checkpoint)
# For RocksDB: this will run `flush_opt` to flush database memtables to SST files on disk (https://docs.rs/rocksdb/latest/rocksdb/struct.DBCommon.html#method.flush_opt)
# These operations always run on shutdown.
#
# Defaults to 30 minutes (1800 seconds) to avoid IO amplification from too frequent cleanups
#cleanup_second_interval = 1800
### RocksDB options ### RocksDB options
# Set this to true to use RocksDB config options that are tailored to HDDs (slower device storage) # Set this to true to use RocksDB config options that are tailored to HDDs (slower device storage)
#
# It is worth noting that by default, conduwuit will use RocksDB with Direct IO enabled. *Generally* speaking this improves performance as it bypasses buffered I/O (system page cache).
# However there is a potential chance that Direct IO may cause issues with database operations if your setup is uncommon. This has been observed with FUSE filesystems, and possibly ZFS filesystem.
# RocksDB generally deals/corrects these issues but it cannot account for all setups.
# If you experience any weird RocksDB issues, try enabling this option as it turns off Direct IO and feel free to report in the conduwuit Matrix room if this option fixes your DB issues.
# See https://github.com/facebook/rocksdb/wiki/Direct-IO for more information.
#
# Defaults to false
#rocksdb_optimize_for_spinning_disks = false #rocksdb_optimize_for_spinning_disks = false
# RocksDB log level. This is not the same as conduwuit's log level. This is the log level for the RocksDB engine/library # RocksDB log level. This is not the same as conduwuit's log level. This is the log level for RocksDB itself
# which show up in your database folder/path as `LOG` files. Defaults to error. conduwuit will typically log RocksDB errors as normal. # which show up in your database folder/path as `LOG` files. Defaults to warn. conduwuit will typically log RocksDB errors.
#rocksdb_log_level = "error" #rocksdb_log_level = "warn"
# Max RocksDB `LOG` file size before rotating in bytes. Defaults to 4MB. # Max RocksDB `LOG` file size before rotating in bytes. Defaults to 4MB.
#rocksdb_max_log_file_size = 4194304 #rocksdb_max_log_file_size = 4194304
@@ -311,53 +246,9 @@ url_preview_check_root_domain = false
# Time in seconds before RocksDB will forcibly rotate logs. Defaults to 0. # Time in seconds before RocksDB will forcibly rotate logs. Defaults to 0.
#rocksdb_log_time_to_roll = 0 #rocksdb_log_time_to_roll = 0
# Amount of threads that RocksDB will use for parallelism. Set to 0 to use all your physical cores.
# Conduit eagerly spawns threads mainly for federation, so it may not be desirable to use all your cores / logical threads.
#
# Defaults to your CPU physical core count (not logical threads) count divided by 2 (half)
#rocksdb_parallelism_threads = 0
# Maximum number of LOG files RocksDB will keep. This must *not* be set to 0. It must be at least 1.
# Defaults to 3 as these are not very useful.
#rocksdb_max_log_files = 3
# Type of RocksDB database compression to use.
# Available options are "zstd", "zlib", "bz2" and "lz4"
# It is best to use ZSTD as an overall good balance between speed/performance, storage, IO amplification, and CPU usage.
# For more performance but less compression (more storage used) and less CPU usage, use LZ4.
# See https://github.com/facebook/rocksdb/wiki/Compression for more details.
#
# Defaults to "zstd"
#rocksdb_compression_algo = "zstd"
# Level of compression the specified compression algorithm for RocksDB to use.
# Default is 32767, which is internally read by RocksDB as the default magic number and
# translated to the library's default compression level as they all differ.
# See their `kDefaultCompressionLevel`.
#
#rocksdb_compression_level = 32767
# Level of compression the specified compression algorithm for the bottommost level/data for RocksDB to use.
# Default is 32767, which is internally read by RocksDB as the default magic number and
# translated to the library's default compression level as they all differ.
# See their `kDefaultCompressionLevel`.
#
# Since this is the bottommost level (generally old and least used data), it may be desirable to have a very
# high compression level here as it's lesss likely for this data to be used. Research your chosen compression algorithm.
#
#rocksdb_bottommost_compression_level = 32767
# Whether to enable RocksDB "bottommost_compression".
# At the expense of more CPU usage, this will further compress the database to reduce more storage.
# It is recommended to use ZSTD compression with this for best compression results.
# See https://github.com/facebook/rocksdb/wiki/Compression for more details.
#
# Defaults to false as this uses more CPU when compressing.
#rocksdb_bottommost_compression = false
### Presence
### Presence / Typing Indicators / Read Receipts
# Config option to control local (your server only) presence updates/requests. Defaults to false. # Config option to control local (your server only) presence updates/requests. Defaults to false.
# Note that presence on conduwuit is very fast unlike Synapse's. # Note that presence on conduwuit is very fast unlike Synapse's.
@@ -384,22 +275,3 @@ url_preview_check_root_domain = false
# Config option to control how many seconds before presence updates that you are offline. Defaults to 30 minutes. # Config option to control how many seconds before presence updates that you are offline. Defaults to 30 minutes.
#presence_offline_timeout_s = 1800 #presence_offline_timeout_s = 1800
# Config option to control whether we should receive remote incoming read receipts.
# Defaults to true.
#allow_incoming_read_receipts = true
# Other options not in [global]:
#
#
# Enables running conduwuit with direct TLS support
# It is strongly recommended you use a reverse proxy instead. This is primarily relevant for test suites like complement that require a private CA setup.
# [global.tls]
# certs = "/path/to/my/certificate.crt"
# key = "/path/to/my/private_key.key"
#
# Whether to listen and allow for HTTP and HTTPS connections (insecure!)
# This config option is only available if conduwuit was built with `axum_dual_protocol` feature (not default feature)
# Defaults to false
#dual_protocol = false
+1 -4
View File
@@ -1,5 +1,5 @@
[Unit] [Unit]
Description=conduwuit Matrix homeserver Description=Conduit Matrix homeserver
After=network-online.target After=network-online.target
[Service] [Service]
@@ -50,9 +50,6 @@ ExecStart=/usr/sbin/matrix-conduit
Restart=on-failure Restart=on-failure
RestartSec=5 RestartSec=5
TimeoutStopSec=4m
TimeoutStartSec=4m
StartLimitInterval=1m StartLimitInterval=1m
StartLimitBurst=5 StartLimitBurst=5
+295 -3
View File
@@ -3,17 +3,18 @@ set -e
. /usr/share/debconf/confmodule . /usr/share/debconf/confmodule
CONDUIT_CONFIG_PATH=/etc/matrix-conduit
CONDUIT_CONFIG_FILE="${CONDUIT_CONFIG_PATH}/conduit.toml"
CONDUIT_DATABASE_PATH=/var/lib/matrix-conduit/ CONDUIT_DATABASE_PATH=/var/lib/matrix-conduit/
case "$1" in case "$1" in
configure) configure)
# Create the `_matrix-conduit` user if it does not exist yet. # Create the `_matrix-conduit` user if it does not exist yet.
if ! getent passwd _matrix-conduit > /dev/null ; then if ! getent passwd _matrix-conduit > /dev/null ; then
echo 'Adding system user for the Conduwuit Matrix homeserver' 1>&2 echo 'Adding system user for the Conduit Matrix homeserver' 1>&2
adduser --system --group --quiet \ adduser --system --group --quiet \
--home "$CONDUIT_DATABASE_PATH" \ --home "$CONDUIT_DATABASE_PATH" \
--disabled-login \ --disabled-login \
--shell "/usr/sbin/nologin" \
--force-badname \ --force-badname \
_matrix-conduit _matrix-conduit
fi fi
@@ -21,8 +22,299 @@ case "$1" in
# Create the database path if it does not exist yet and fix up ownership # Create the database path if it does not exist yet and fix up ownership
# and permissions. # and permissions.
mkdir -p "$CONDUIT_DATABASE_PATH" mkdir -p "$CONDUIT_DATABASE_PATH"
chown _matrix-conduit:_matrix-conduit -R "$CONDUIT_DATABASE_PATH" chown _matrix-conduit "$CONDUIT_DATABASE_PATH"
chmod 700 "$CONDUIT_DATABASE_PATH" chmod 700 "$CONDUIT_DATABASE_PATH"
if [ ! -e "$CONDUIT_CONFIG_FILE" ]; then
# Write the debconf values in the config.
db_get matrix-conduit/hostname
CONDUIT_SERVER_NAME="$RET"
db_get matrix-conduit/address
CONDUIT_ADDRESS="$RET"
db_get matrix-conduit/port
CONDUIT_PORT="$RET"
mkdir -p "$CONDUIT_CONFIG_PATH"
cat > "$CONDUIT_CONFIG_FILE" << EOF
# =============================================================================
# This is the official example config for conduwuit.
# If you use it for your server, you will need to adjust it to your own needs.
# At the very least, change the server_name field!
# =============================================================================
[global]
# The server_name is the pretty name of this server. It is used as a suffix for user
# and room ids. Examples: matrix.org, conduit.rs
# The Conduit server needs all /_matrix/ requests to be reachable at
# https://your.server.name/ on port 443 (client-server) and 8448 (federation).
# If that's not possible for you, you can create /.well-known files to redirect
# requests (delegation). See
# https://spec.matrix.org/latest/client-server-api/#getwell-knownmatrixclient
# and
# https://spec.matrix.org/v1.9/server-server-api/#getwell-knownmatrixserver
# for more information
# YOU NEED TO EDIT THIS
server_name = "${CONDUIT_SERVER_NAME}"
# Servers listed here will be used to gather public keys of other servers.
# Generally, copying this exactly should be enough. (Currently, conduwuit doesn't
# support batched key requests, so this list should only contain Synapse
# servers.) Defaults to `matrix.org`
# trusted_servers = ["matrix.org"]
### Database configuration
# This is the only directory where conduwuit will save its data, including media
database_path = "${CONDUIT_DATABASE_PATH}"
# Database backend: Only rocksdb and sqlite are supported. Please note that sqlite
# will perform significantly worse than rocksdb as it is not intended to be used the
# way it is by conduwuit. sqlite only exists for historical reasons.
database_backend = "rocksdb"
### Network
# The port conduwuit will be running on. You need to set up a reverse proxy such as
# Caddy or Nginx so all requests to /_matrix on port 443 and 8448 will be
# forwarded to the conduwuit instance running on this port
# Docker users: Don't change this, you'll need to map an external port to this.
port = ${CONDUIT_PORT}
# default address (IPv4 or IPv6) conduwuit will listen on. Generally you want this to be
# localhost (127.0.0.1 / ::1). If you are using Docker or a container NAT networking setup, you
# likely need this to be 0.0.0.0.
address = "${CONDUIT_ADDRESS}"
# How many requests conduwuit sends to other servers at the same time concurrently. Default is 500
# Note that because conduwuit is very fast unlike other homeserver implementations, setting this too
# high could inadvertently result in ratelimits kicking in, or overloading lower-end homeservers out there.
#
# A valid use-case for enabling this is if you have a significant amount of overall federation activity
# such as many rooms joined/tracked, and many servers in the true destination cache caused by that. Upon
# rebooting conduwuit, depending on how fast your resources are, client and incoming federation requests
# may timeout or be "stalled" for a period of time due to hitting the max concurrent requests limit from
# refreshing federation/destination caches and such.
#
# If you have a lot of active users on your homeserver, you will definitely need to raise this.
#
# No this will not speed up room joins.
#max_concurrent_requests = 500
# Max request size for file uploads
max_request_size = 20_000_000 # in bytes
# Uncomment unix_socket_path to listen on a UNIX socket at the specified path.
# If listening on a UNIX socket, you must remove/comment the 'address' key if defined and add your
# reverse proxy to the 'conduwuit' group, unless world RW permissions are specified with unix_socket_perms (666 minimum).
#unix_socket_path = "/run/conduwuit/conduwuit.sock"
#unix_socket_perms = 660
# Set this to true for conduwuit to compress HTTP response bodies using zstd.
# Please be aware that enabling HTTP compression may weaken or even defeat TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
zstd_compression = false
# Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you do not want conduwuit to send outbound requests to.
# Defaults to RFC1918, unroutable, loopback, multicast, and testnet addresses for security.
#
# To disable, set this to be an empty vector (`[]`).
#
# Currently this does not account for proxies in use like Synapse does.
ip_range_denylist = [
"127.0.0.0/8",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"100.64.0.0/10",
"192.0.0.0/24",
"169.254.0.0/16",
"192.88.99.0/24",
"198.18.0.0/15",
"192.0.2.0/24",
"198.51.100.0/24",
"203.0.113.0/24",
"224.0.0.0/4",
"::1/128",
"fe80::/10",
"fc00::/7",
"2001:db8::/32",
"ff00::/8",
"fec0::/10",
]
### Moderation / Privacy / Security
# Set to true to allow user type "guest" registrations. Element attempts to register guest users automatically.
# For private homeservers, this is best at false.
allow_guest_registration = false
# Vector list of servers that conduwuit will refuse to download remote media from.
# No default.
# prevent_media_downloads_from = ["example.com", "example.local"]
# Enables open registration. If set to false, no users can register on this
# server.
# If set to true without a token configured, users can register with no form of 2nd-
# step only if you set
# `yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` to
# true in your config. If you would like
# registration only via token reg, please configure the `registration_token` key.
allow_registration = false
# Please note that an open registration homeserver with no second-step verification
# is highly prone to abuse and potential defederation by homeservers, including
# matrix.org.
# A static registration token that new users will have to provide when creating
# an account. If unset and `allow_registration` is true, registration is open
# without any condition. YOU NEED TO EDIT THIS.
registration_token = "change this token for something specific to your server"
# controls whether federation is allowed or not
# defaults to true
# allow_federation = true
# controls whether users are allowed to create rooms.
# appservices and admins are always allowed to create rooms
# defaults to true
# allow_room_creation = true
# Set this to true to allow your server's public room directory to be federated.
# Set this to false to protect against /publicRooms spiders, but will forbid external users
# from viewing your server's public room directory. If federation is disabled entirely
# (`allow_federation`), this is inherently false.
allow_public_room_directory_over_federation = false
# Set this to true to allow your server's public room directory to be queried without client
# authentication (access token) through the Client APIs. Set this to false to protect against /publicRooms spiders.
allow_public_room_directory_without_auth = false
# Set this to true to allow federating device display names / allow external users to see your device display name.
# If federation is disabled entirely (`allow_federation`), this is inherently false. For privacy, this is best disabled.
allow_device_name_federation = false
# Vector list of domains allowed to send requests to for URL previews. Defaults to none.
# Note: this is a *contains* match, not an explicit match. Putting "google.com" will match "https://google.com" and "http://mymaliciousdomainexamplegoogle.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_domain_contains_allowlist = []
# Vector list of explicit domains allowed to send requests to for URL previews. Defaults to none.
# Note: This is an *explicit* match, not a ccontains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_domain_explicit_allowlist = []
# Vector list of URLs allowed to send requests to for URL previews. Defaults to none.
# Note that this is a *contains* match, not an explicit match. Putting "google.com" will match "https://google.com/", "https://google.com/url?q=https://mymaliciousdomainexample.com", and "https://mymaliciousdomainexample.com/hi/google.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_url_contains_allowlist = []
# Maximum amount of bytes allowed in a URL preview body size when spidering. Defaults to 1MB (1_000_000 bytes)
url_preview_max_spider_size = 1_000_000
# Option to decide whether you would like to run the domain allowlist checks (contains and explicit) on the root domain or not. Does not apply to URL contains allowlist. Defaults to false.
# Example: If this is enabled and you have "wikipedia.org" allowed in the explicit and/or contains domain allowlist, it will allow all subdomains under "wikipedia.org" such as "en.m.wikipedia.org" as the root domain is checked and matched.
# Useful if the domain contains allowlist is still too broad for you but you still want to allow all the subdomains under a root domain.
url_preview_check_root_domain = false
### Misc
# max log level for conduwuit. allows debug, info, warn, or error
#log = "warn"
# controls whether encrypted rooms and events are allowed (default true)
#allow_encryption = false
# conduwuit will send a simple GET request periodically to `https://pupbrain.dev/check-for-updates/stable`
# for any new announcements made. Despite the name, this is not an update check
# endpoint, it is simply an announcement check endpoint. I don't plan on using
# this so feel free to disable it.
allow_check_for_updates = true
# Enables adding the lightning bolt emoji (⚡️) to all newly registered users'
# initial display names.
enable_lightning_bolt = false
# If you are using delegation via well-known files and you cannot serve them from your reverse proxy, you can
# uncomment these to serve them directly from conduwuit. This requires proxying all requests to conduwuit, not just `/_matrix` to work.
#well_known_server = "matrix.example.com:443"
#well_known_client = "https://matrix.example.com"
# Note that whatever you put will show up in the well-known JSON values.
# Set to false to disable users from joining or creating room versions that aren't 100% officially supported by conduwuit.
# conduwuit officially supports room versions 6 - 10. conduwuit has experimental/unstable support for 1 - 5, and 11.
# Defaults to true.
#allow_unstable_room_versions = true
# Set this to any float value to multiply conduwuit's in-memory LRU caches with.
# May be useful if you have significant memory to spare to increase performance.
# Defaults to 1.0.
#conduit_cache_capacity_modifier = 1.0
# Set this to any float value in megabytes for conduwuit to tell the database engine that this much memory is available for database-related caches.
# May be useful if you have significant memory to spare to increase performance.
# Defaults to 900.0
#db_cache_capacity_mb = 900.0
### RocksDB options
# Set this to true to use RocksDB config options that are tailored to HDDs (slower device storage)
#rocksdb_optimize_for_spinning_disks = false
# RocksDB log level. This is not the same as conduwuit's log level. This is the log level for RocksDB itself
# which show up in your database folder/path as `LOG` files. Defaults to warn. conduwuit will typically log RocksDB errors.
#rocksdb_log_level = "warn"
# Max RocksDB `LOG` file size before rotating in bytes. Defaults to 4MB.
#rocksdb_max_log_file_size = 4194304
# Time in seconds before RocksDB will forcibly rotate logs. Defaults to 0.
#rocksdb_log_time_to_roll = 0
### Presence
# Config option to control local (your server only) presence updates/requests. Defaults to false.
# Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, this MUST be enabled.
#allow_local_presence = false
# Config option to control incoming federated presence updates/requests. Defaults to false.
# This option receives presence updates from other servers, but does not send any unless `allow_outgoing_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's.
#allow_incoming_presence = false
# Config option to control outgoing presence updates/requests. Defaults to false.
# This option sends presence updates to other servers, but does not receive any unless `allow_incoming_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, you MUST enable `allow_local_presence` as well.
#
# Warning: Outgoing federated presence is not spec compliant due to relying on PDUs and EDUs combined.
# Outgoing presence will not be very reliable due to this and any issues with federated outgoing presence are very likely attributed to this issue.
# Incoming presence and local presence are unaffected.
#allow_outgoing_presence = false
# Config option to control how many seconds before presence updates that you are idle. Defaults to 5 minutes.
#presence_idle_timeout_s = 300
# Config option to control how many seconds before presence updates that you are offline. Defaults to 30 minutes.
#presence_offline_timeout_s = 1800
EOF
fi
;; ;;
esac esac
+2 -2
View File
@@ -70,7 +70,7 @@ docker run -d -p 8448:6167 \
or you can use [docker-compose](#docker-compose). or you can use [docker-compose](#docker-compose).
The `-d` flag lets the container run in detached mode. You now need to supply a `conduit.toml` config file, an example can be found [here](../conduwuit-example.toml). The `-d` flag lets the container run in detached mode. You now need to supply a `conduit.toml` config file, an example can be found [here](../conduit-example.toml).
You can pass in different env vars to change config values on the fly. You can even configure Conduit completely by using env vars, but for that you need You can pass in different env vars to change config values on the fly. You can even configure Conduit completely by using env vars, but for that you need
to pass `-e CONDUIT_CONFIG=""` into your container. For an overview of possible values, please take a look at the `docker-compose.yml` file. to pass `-e CONDUIT_CONFIG=""` into your container. For an overview of possible values, please take a look at the `docker-compose.yml` file.
@@ -131,7 +131,7 @@ So...step by step:
1. Copy [`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml) (or 1. Copy [`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml) (or
[`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)) and [`docker-compose.override.yml`](docker-compose.override.yml) from the repository and remove `.for-traefik` (or `.with-traefik`) from the filename. [`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)) and [`docker-compose.override.yml`](docker-compose.override.yml) from the repository and remove `.for-traefik` (or `.with-traefik`) from the filename.
2. Open both files and modify/adjust them to your needs. Meaning, change the `CONDUIT_SERVER_NAME` and the volume host mappings according to your needs. 2. Open both files and modify/adjust them to your needs. Meaning, change the `CONDUIT_SERVER_NAME` and the volume host mappings according to your needs.
3. Create the `conduit.toml` config file, an example can be found [here](../conduwuit-example.toml), or set `CONDUIT_CONFIG=""` and configure Conduit per env vars. 3. Create the `conduit.toml` config file, an example can be found [here](../conduit-example.toml), or set `CONDUIT_CONFIG=""` and configure Conduit per env vars.
4. Uncomment the `element-web` service if you want to host your own Element Web Client and create a `element_config.json`. 4. Uncomment the `element-web` service if you want to host your own Element Web Client and create a `element_config.json`.
5. Create the files needed by the `well-known` service. 5. Create the files needed by the `well-known` service.
+4 -6
View File
@@ -1,5 +1,5 @@
# Conduit - Behind Traefik Reverse Proxy # Conduit - Behind Traefik Reverse Proxy
version: '2.4' # uses '2.4' for cpuset version: '3'
services: services:
homeserver: homeserver:
@@ -18,13 +18,12 @@ services:
# GIT_REF: origin/master # GIT_REF: origin/master
restart: unless-stopped restart: unless-stopped
volumes: volumes:
- db:/var/lib/matrix-conduit - db:/var/lib/matrix-conduit/
#- ./conduwuit.toml:/etc/conduit.toml
networks: networks:
- proxy - proxy
environment: environment:
CONDUIT_SERVER_NAME: your.server.name # EDIT THIS CONDUIT_SERVER_NAME: your.server.name # EDIT THIS
CONDUIT_DATABASE_PATH: /var/lib/matrix-conduit CONDUIT_DATABASE_PATH: /var/lib/matrix-conduit/
CONDUIT_DATABASE_BACKEND: rocksdb CONDUIT_DATABASE_BACKEND: rocksdb
CONDUIT_PORT: 6167 CONDUIT_PORT: 6167
CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB
@@ -35,8 +34,7 @@ services:
#CONDUIT_MAX_CONCURRENT_REQUESTS: 100 #CONDUIT_MAX_CONCURRENT_REQUESTS: 100
#CONDUIT_LOG: warn,state_res=warn #CONDUIT_LOG: warn,state_res=warn
CONDUIT_ADDRESS: 0.0.0.0 CONDUIT_ADDRESS: 0.0.0.0
#CONDUIT_CONFIG: './conduwuit.toml' # Uncomment if you mapped config toml above CONDUIT_CONFIG: '' # Ignore this
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
# We need some way to server the client and server .well-known json. The simplest way is to use a nginx container # We need some way to server the client and server .well-known json. The simplest way is to use a nginx container
# to serve those two as static files. If you want to use a different way, delete or comment the below service, here # to serve those two as static files. If you want to use a different way, delete or comment the below service, here
+1 -1
View File
@@ -1,5 +1,5 @@
# Conduit - Traefik Reverse Proxy Labels # Conduit - Traefik Reverse Proxy Labels
version: '2.4' # uses '2.4' for cpuset version: '3'
services: services:
homeserver: homeserver:
+6 -5
View File
@@ -1,5 +1,5 @@
# Conduit - Behind Traefik Reverse Proxy # Conduit - Behind Traefik Reverse Proxy
version: '2.4' # uses '2.4' for cpuset version: '3'
services: services:
homeserver: homeserver:
@@ -19,17 +19,19 @@ services:
restart: unless-stopped restart: unless-stopped
volumes: volumes:
- db:/srv/conduit/.local/share/conduit - db:/srv/conduit/.local/share/conduit
#- ./conduwuit.toml:/etc/conduit.toml ### Uncomment if you want to use conduit.toml to configure Conduit
### Note: Set env vars will override conduit.toml values
# - ./conduit.toml:/srv/conduit/conduit.toml
networks: networks:
- proxy - proxy
environment: environment:
CONDUIT_SERVER_NAME: your.server.name # EDIT THIS CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]' CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
CONDUIT_ALLOW_REGISTRATION : 'true' CONDUIT_ALLOW_REGISTRATION : 'true'
#CONDUIT_CONFIG: './conduwuit.toml' # Uncomment if you mapped config toml above
### Uncomment and change values as desired ### Uncomment and change values as desired
# CONDUIT_ADDRESS: 0.0.0.0 # CONDUIT_ADDRESS: 0.0.0.0
# CONDUIT_PORT: 6167 # CONDUIT_PORT: 6167
# CONDUIT_CONFIG: '/srv/conduit/conduit.toml' # if you want to configure purely by env vars, set this to an empty string ''
# Available levels are: error, warn, info, debug, trace - more info at: https://docs.rs/env_logger/*/env_logger/#enabling-logging # Available levels are: error, warn, info, debug, trace - more info at: https://docs.rs/env_logger/*/env_logger/#enabling-logging
# CONDUIT_LOG: info # default is: "warn,state_res=warn" # CONDUIT_LOG: info # default is: "warn,state_res=warn"
# CONDUIT_ALLOW_JAEGER: 'false' # CONDUIT_ALLOW_JAEGER: 'false'
@@ -39,7 +41,6 @@ services:
# CONDUIT_DATABASE_PATH: /srv/conduit/.local/share/conduit # CONDUIT_DATABASE_PATH: /srv/conduit/.local/share/conduit
# CONDUIT_WORKERS: 10 # CONDUIT_WORKERS: 10
# CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB # CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
# We need some way to server the client and server .well-known json. The simplest way is to use a nginx container # We need some way to server the client and server .well-known json. The simplest way is to use a nginx container
# to serve those two as static files. If you want to use a different way, delete or comment the below service, here # to serve those two as static files. If you want to use a different way, delete or comment the below service, here
+4 -6
View File
@@ -1,5 +1,5 @@
# Conduit # Conduit
version: '2.4' # uses '2.4' for cpuset version: '3'
services: services:
homeserver: homeserver:
@@ -20,11 +20,10 @@ services:
ports: ports:
- 8448:6167 - 8448:6167
volumes: volumes:
- db:/var/lib/matrix-conduit - db:/var/lib/matrix-conduit/
#- ./conduwuit.toml:/etc/conduit.toml
environment: environment:
CONDUIT_SERVER_NAME: your.server.name # EDIT THIS CONDUIT_SERVER_NAME: your.server.name # EDIT THIS
CONDUIT_DATABASE_PATH: /var/lib/matrix-conduit CONDUIT_DATABASE_PATH: /var/lib/matrix-conduit/
CONDUIT_DATABASE_BACKEND: rocksdb CONDUIT_DATABASE_BACKEND: rocksdb
CONDUIT_PORT: 6167 CONDUIT_PORT: 6167
CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB CONDUIT_MAX_REQUEST_SIZE: 20_000_000 # in bytes, ~20 MB
@@ -35,8 +34,7 @@ services:
#CONDUIT_MAX_CONCURRENT_REQUESTS: 400 #CONDUIT_MAX_CONCURRENT_REQUESTS: 400
#CONDUIT_LOG: warn,state_res=warn #CONDUIT_LOG: warn,state_res=warn
CONDUIT_ADDRESS: 0.0.0.0 CONDUIT_ADDRESS: 0.0.0.0
#CONDUIT_CONFIG: './conduwuit.toml' # Uncomment if you mapped config toml above CONDUIT_CONFIG: '' # Ignore this
#cpuset: "0-4" # Uncomment to limit to specific CPU cores
# #
### Uncomment if you want to use your own Element-Web App. ### Uncomment if you want to use your own Element-Web App.
### Note: You need to provide a config.json for Element and you also need a second ### Note: You need to provide a config.json for Element and you also need a second
+6 -18
View File
@@ -40,21 +40,6 @@ name = "cargo-clippy"
group = "versions" group = "versions"
script = "cargo clippy -- --version" script = "cargo clippy -- --version"
[[task]]
name = "cargo-audit"
group = "versions"
script = "cargo audit --version"
[[task]]
name = "cargo-deb"
group = "versions"
script = "cargo deb --version"
[[task]]
name = "cargo-audit"
group = "security"
script = "cargo audit -D warnings -D unmaintained -D unsound -D yanked"
[[task]] [[task]]
name = "cargo-fmt" name = "cargo-fmt"
group = "lints" group = "lints"
@@ -66,7 +51,6 @@ group = "lints"
script = """ script = """
RUSTDOCFLAGS="-D warnings" cargo doc \ RUSTDOCFLAGS="-D warnings" cargo doc \
--workspace \ --workspace \
--all-features \
--no-deps \ --no-deps \
--document-private-items \ --document-private-items \
--color always --color always
@@ -75,7 +59,7 @@ RUSTDOCFLAGS="-D warnings" cargo doc \
[[task]] [[task]]
name = "cargo-clippy" name = "cargo-clippy"
group = "lints" group = "lints"
script = "cargo clippy --workspace --all-targets --all-features --color=always -- -D warnings" script = "cargo clippy --workspace --all-targets --color=always -- -D warnings"
[[task]] [[task]]
name = "cargo" name = "cargo"
@@ -84,8 +68,12 @@ script = """
cargo test \ cargo test \
--workspace \ --workspace \
--all-targets \ --all-targets \
--all-features \
--color=always \ --color=always \
-- \ -- \
--color=always --color=always
""" """
[[task]]
name = "cargo-audit"
group = "security"
script = "cargo audit -D warnings -D unmaintained -D unsound -D yanked"
Generated
+13 -13
View File
@@ -60,8 +60,8 @@
}, },
"original": { "original": {
"owner": "ipetkov", "owner": "ipetkov",
"ref": "master",
"repo": "crane", "repo": "crane",
"rev": "2c653e4478476a52c6aa3ac0495e4dea7449ea0e",
"type": "github" "type": "github"
} }
}, },
@@ -73,11 +73,11 @@
"rust-analyzer-src": "rust-analyzer-src" "rust-analyzer-src": "rust-analyzer-src"
}, },
"locked": { "locked": {
"lastModified": 1709619709, "lastModified": 1707891749,
"narHash": "sha256-l6EPVJfwfelWST7qWQeP6t/TDK3HHv5uUB1b2vw4mOQ=", "narHash": "sha256-SeikNYElHgv8uVMbiA9/pU3Cce7ssIsiM8CnEiwd1Nc=",
"owner": "nix-community", "owner": "nix-community",
"repo": "fenix", "repo": "fenix",
"rev": "c8943ea9e98d41325ff57d4ec14736d330b321b2", "rev": "3115aab064ef38cccd792c45429af8df43d6d277",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -138,11 +138,11 @@
"systems": "systems" "systems": "systems"
}, },
"locked": { "locked": {
"lastModified": 1709126324, "lastModified": 1705309234,
"narHash": "sha256-q6EQdSeUZOG26WelxqkmR7kArjgWCdw5sfJVHPH/7j8=", "narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide", "owner": "numtide",
"repo": "flake-utils", "repo": "flake-utils",
"rev": "d465f4819400de7c8d874d50b982301f28a84605", "rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -200,11 +200,11 @@
}, },
"nixpkgs_2": { "nixpkgs_2": {
"locked": { "locked": {
"lastModified": 1709479366, "lastModified": 1707689078,
"narHash": "sha256-n6F0n8UV6lnTZbYPl1A9q1BS0p4hduAv1mGAP17CVd0=", "narHash": "sha256-UUGmRa84ZJHpGZ1WZEBEUOzaPOWG8LZ0yPg1pdDF/yM=",
"owner": "NixOS", "owner": "NixOS",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "b8697e57f10292a6165a20f03d2f42920dfaf973", "rev": "f9d39fb9aff0efee4a3d5f4a6d7c17701d38a1d8",
"type": "github" "type": "github"
}, },
"original": { "original": {
@@ -228,11 +228,11 @@
"rust-analyzer-src": { "rust-analyzer-src": {
"flake": false, "flake": false,
"locked": { "locked": {
"lastModified": 1709571018, "lastModified": 1707849817,
"narHash": "sha256-ISFrxHxE0J5g7lDAscbK88hwaT5uewvWoma9TlFmRzM=", "narHash": "sha256-If6T0MDErp3/z7DBlpG4bV46IPP+7BWSlgTI88cmbw0=",
"owner": "rust-lang", "owner": "rust-lang",
"repo": "rust-analyzer", "repo": "rust-analyzer",
"rev": "9f14343f9ee24f53f17492c5f9b653427e2ad15e", "rev": "a02a219773629686bd8ff123ca1aa995fa50d976",
"type": "github" "type": "github"
}, },
"original": { "original": {
+11 -24
View File
@@ -13,12 +13,7 @@
inputs.nixpkgs.follows = "nixpkgs"; inputs.nixpkgs.follows = "nixpkgs";
}; };
crane = { crane = {
# Pin latest crane that's not affected by the following bugs: url = "github:ipetkov/crane?ref=master";
#
# * <https://github.com/ipetkov/crane/issues/527#issuecomment-1978079140>
# * <https://github.com/toml-rs/toml/issues/691>
# * <https://github.com/toml-rs/toml/issues/267>
url = "github:ipetkov/crane?rev=2c653e4478476a52c6aa3ac0495e4dea7449ea0e";
inputs.nixpkgs.follows = "nixpkgs"; inputs.nixpkgs.follows = "nixpkgs";
}; };
attic.url = "github:zhaofengli/attic?ref=main"; attic.url = "github:zhaofengli/attic?ref=main";
@@ -37,17 +32,13 @@
let let
pkgsHost = nixpkgs.legacyPackages.${system}; pkgsHost = nixpkgs.legacyPackages.${system};
rocksdb' = pkgs: rocksdb' = pkgs: pkgs.rocksdb.overrideAttrs (old:
let {
version = "8.11.3";
in
pkgs.rocksdb.overrideAttrs (old: {
inherit version;
src = pkgs.fetchFromGitHub { src = pkgs.fetchFromGitHub {
owner = "facebook"; owner = "facebook";
repo = "rocksdb"; repo = "rocksdb";
rev = "v${version}"; rev = "v8.10.0";
hash = "sha256-OpEiMwGxZuxb9o3RQuSrwZMQGLhe9xLT1aa3HpI4KPs="; hash = "sha256-KGsYDBc1fz/90YYNGwlZ0LUKXYsP1zyhP29TnRQwgjQ=";
}; };
}); });
@@ -69,7 +60,7 @@
# bindgen needs the build platform's libclang. Apparently due to # bindgen needs the build platform's libclang. Apparently due to
# "splicing weirdness", pkgs.rustPlatform.bindgenHook on its own doesn't # "splicing weirdness", pkgs.rustPlatform.bindgenHook on its own doesn't
# quite do the right thing here. # quite do the right thing here.
pkgs.pkgsBuildHost.rustPlatform.bindgenHook pkgs.buildPackages.rustPlatform.bindgenHook
]; ];
env = pkgs: { env = pkgs: {
@@ -97,7 +88,7 @@
# these flags when using a different linker. Don't ask me why, # these flags when using a different linker. Don't ask me why,
# though, because I don't know. All I know is it breaks otherwise. # though, because I don't know. All I know is it breaks otherwise.
# #
# [0]: https://github.com/NixOS/nixpkgs/blob/5cdb38bb16c6d0a38779db14fcc766bc1b2394d6/pkgs/build-support/rust/lib/default.nix#L37-L40 # [0]: https://github.com/NixOS/nixpkgs/blob/612f97239e2cc474c13c9dafa0df378058c5ad8d/pkgs/build-support/rust/lib/default.nix#L36-L39
( (
# Nixpkgs doesn't check for x86_64 here but we do, because I # Nixpkgs doesn't check for x86_64 here but we do, because I
# observed a failure building statically for x86_64 without # observed a failure building statically for x86_64 without
@@ -121,7 +112,7 @@
# even covers the case of build scripts that need native code compiled and # even covers the case of build scripts that need native code compiled and
# run on the build platform (I think). # run on the build platform (I think).
# #
# [0]: https://github.com/NixOS/nixpkgs/blob/5cdb38bb16c6d0a38779db14fcc766bc1b2394d6/pkgs/build-support/rust/lib/default.nix#L57-L80 # [0]: https://github.com/NixOS/nixpkgs/blob/612f97239e2cc474c13c9dafa0df378058c5ad8d/pkgs/build-support/rust/lib/default.nix#L64-L78
// ( // (
let let
inherit (pkgs.rust.lib) envVars; inherit (pkgs.rust.lib) envVars;
@@ -159,11 +150,10 @@
"CC_${cargoEnvVarTarget}" = envVars.ccForBuild; "CC_${cargoEnvVarTarget}" = envVars.ccForBuild;
"CXX_${cargoEnvVarTarget}" = envVars.cxxForBuild; "CXX_${cargoEnvVarTarget}" = envVars.cxxForBuild;
"CARGO_TARGET_${cargoEnvVarTarget}_LINKER" = envVars.linkerForBuild; "CARGO_TARGET_${cargoEnvVarTarget}_LINKER" = envVars.linkerForBuild;
HOST_CC = "${pkgs.pkgsBuildHost.stdenv.cc}/bin/cc"; HOST_CC = "${pkgs.buildPackages.stdenv.cc}/bin/cc";
HOST_CXX = "${pkgs.pkgsBuildHost.stdenv.cc}/bin/c++"; HOST_CXX = "${pkgs.buildPackages.stdenv.cc}/bin/c++";
} }
) ));
);
package = pkgs: builder pkgs { package = pkgs: builder pkgs {
src = nix-filter { src = nix-filter {
@@ -267,9 +257,6 @@
] ++ (with pkgsHost; [ ] ++ (with pkgsHost; [
engage engage
# Needed for producing Debian packages
cargo-deb
# Needed for Complement # Needed for Complement
go go
olm olm
+5 -15
View File
@@ -5,18 +5,8 @@ This guide assumes you have a recent version of Nix (^2.4) installed.
Since Conduit ships as a Nix flake, you'll first need to [enable Since Conduit ships as a Nix flake, you'll first need to [enable
flakes][enable_flakes]. flakes][enable_flakes].
A binary cache for conduwuit that the CI/CD publishes to is available at the You can now use the usual Nix commands to interact with Conduit's flake. For
following places (both are the same just different names): example, `nix run gitlab:famedly/conduit` will run Conduit (though you'll need
```
https://attic.kennel.juneis.dog/conduit
conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
https://attic.kennel.juneis.dog/conduwuit
conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
```
You can now use the usual Nix commands to interact with conduwuit's flake. For
example, `nix run github:girlbossceo/conduwuit` will run conduwuit (though you'll need
to provide configuration and such manually as usual). to provide configuration and such manually as usual).
If your NixOS configuration is defined as a flake, you can depend on this flake If your NixOS configuration is defined as a flake, you can depend on this flake
@@ -25,7 +15,7 @@ add the following to your `inputs`:
```nix ```nix
conduit = { conduit = {
url = "github:girlbossceo/conduwuit"; url = "gitlab:famedly/conduit";
# Assuming you have an input for nixpkgs called `nixpkgs`. If you experience # Assuming you have an input for nixpkgs called `nixpkgs`. If you experience
# build failures while using this, try commenting/deleting this line. This # build failures while using this, try commenting/deleting this line. This
@@ -38,7 +28,7 @@ Next, make sure you're passing your flake inputs to the `specialArgs` argument
of `nixpkgs.lib.nixosSystem` [as explained here][specialargs]. This guide will of `nixpkgs.lib.nixosSystem` [as explained here][specialargs]. This guide will
assume you've named the group `flake-inputs`. assume you've named the group `flake-inputs`.
Now you can configure conduwuit and a reverse proxy for it. Add the following to Now you can configure Conduit and a reverse proxy for it. Add the following to
a new Nix file and include it in your configuration: a new Nix file and include it in your configuration:
```nix ```nix
@@ -144,7 +134,7 @@ in
]; ];
locations."/_matrix/" = { locations."/_matrix/" = {
proxyPass = "http://backend_conduit"; proxyPass = "http://backend_conduit$request_uri";
proxyWebsockets = true; proxyWebsockets = true;
extraConfig = '' extraConfig = ''
proxy_set_header Host $host; proxy_set_header Host $host;
-1
View File
@@ -3,7 +3,6 @@
# Other files that need upkeep when this changes: # Other files that need upkeep when this changes:
# #
# * `.gitlab-ci.yml` # * `.gitlab-ci.yml`
# * `.github/workflows/ci.yml`
# * `Cargo.toml` # * `Cargo.toml`
# * `flake.nix` # * `flake.nix`
# #
+1 -26
View File
@@ -1,27 +1,2 @@
edition = "2021" unstable_features = true
condense_wildcard_suffixes = true
format_code_in_doc_comments = true
format_macro_bodies = true
format_macro_matchers = true
format_strings = true
hex_literal_case = "Upper"
max_width = 120
tab_spaces = 4
array_width = 80
comment_width = 80
wrap_comments = true
fn_params_layout = "Compressed"
fn_call_width = 80
fn_single_line = true
hard_tabs = true
match_block_trailing_comma = true
imports_granularity="Crate" imports_granularity="Crate"
normalize_comments = false
reorder_impl_items = true
reorder_imports = true
group_imports = "StdExternalCrate"
newline_style = "Unix"
use_field_init_shorthand = true
use_small_heuristics = "Off"
use_try_shorthand = true
+40 -20
View File
@@ -1,18 +1,20 @@
use std::{fmt::Debug, mem, time::Duration};
use bytes::BytesMut;
use ruma::api::{appservice::Registration, IncomingResponse, MatrixVersion, OutgoingRequest, SendAccessToken};
use tracing::warn;
use crate::{services, utils, Error, Result}; use crate::{services, utils, Error, Result};
use bytes::BytesMut;
use ruma::api::{
appservice::Registration, IncomingResponse, MatrixVersion, OutgoingRequest, SendAccessToken,
};
use std::{fmt::Debug, mem, time::Duration};
use tracing::warn;
/// Sends a request to an appservice /// Sends a request to an appservice
/// ///
/// Only returns None if there is no url specified in the appservice /// Only returns None if there is no url specified in the appservice registration file
/// registration file pub(crate) async fn send_request<T: OutgoingRequest>(
pub(crate) async fn send_request<T>(registration: Registration, request: T) -> Option<Result<T::IncomingResponse>> registration: Registration,
request: T,
) -> Option<Result<T::IncomingResponse>>
where where
T: OutgoingRequest + Debug, T: Debug,
{ {
if let Some(destination) = registration.url { if let Some(destination) = registration.url {
let hs_token = registration.hs_token.as_str(); let hs_token = registration.hs_token.as_str();
@@ -28,7 +30,7 @@ where
Error::BadServerResponse("Invalid destination") Error::BadServerResponse("Invalid destination")
}) })
.unwrap() .unwrap()
.map(BytesMut::freeze); .map(|body| body.freeze());
let mut parts = http_request.uri().clone().into_parts(); let mut parts = http_request.uri().clone().into_parts();
let old_path_and_query = parts.path_and_query.unwrap().as_str().to_owned(); let old_path_and_query = parts.path_and_query.unwrap().as_str().to_owned();
@@ -38,16 +40,25 @@ where
"?" "?"
}; };
parts.path_and_query = Some((old_path_and_query + symbol + "access_token=" + hs_token).parse().unwrap()); parts.path_and_query = Some(
(old_path_and_query + symbol + "access_token=" + hs_token)
.parse()
.unwrap(),
);
*http_request.uri_mut() = parts.try_into().expect("our manipulation is always valid"); *http_request.uri_mut() = parts.try_into().expect("our manipulation is always valid");
let mut reqwest_request = let mut reqwest_request = reqwest::Request::try_from(http_request)
reqwest::Request::try_from(http_request).expect("all http requests are valid reqwest requests"); .expect("all http requests are valid reqwest requests");
*reqwest_request.timeout_mut() = Some(Duration::from_secs(120)); *reqwest_request.timeout_mut() = Some(Duration::from_secs(120));
let url = reqwest_request.url().clone(); let url = reqwest_request.url().clone();
let mut response = match services().globals.default_client().execute(reqwest_request).await { let mut response = match services()
.globals
.default_client()
.execute(reqwest_request)
.await
{
Ok(r) => r, Ok(r) => r,
Err(e) => { Err(e) => {
warn!( warn!(
@@ -55,15 +66,19 @@ where
registration.id, destination, e registration.id, destination, e
); );
return Some(Err(e.into())); return Some(Err(e.into()));
}, }
}; };
// reqwest::Response -> http::Response conversion // reqwest::Response -> http::Response conversion
let status = response.status(); let status = response.status();
let mut http_response_builder = http::Response::builder().status(status).version(response.version()); let mut http_response_builder = http::Response::builder()
.status(status)
.version(response.version());
mem::swap( mem::swap(
response.headers_mut(), response.headers_mut(),
http_response_builder.headers_mut().expect("http::response::Builder is usable"), http_response_builder
.headers_mut()
.expect("http::response::Builder is usable"),
); );
let body = response.bytes().await.unwrap_or_else(|e| { let body = response.bytes().await.unwrap_or_else(|e| {
@@ -82,10 +97,15 @@ where
} }
let response = T::IncomingResponse::try_from_http_response( let response = T::IncomingResponse::try_from_http_response(
http_response_builder.body(body).expect("reqwest body is valid http body"), http_response_builder
.body(body)
.expect("reqwest body is valid http body"),
); );
Some(response.map_err(|_| { Some(response.map_err(|_| {
warn!("Appservice returned invalid response bytes {}\n{}", destination, url); warn!(
"Appservice returned invalid response bytes {}\n{}",
destination, url
);
Error::BadServerResponse("Server returned bad response.") Error::BadServerResponse("Server returned bad response.")
})) }))
} else { } else {
+150 -103
View File
@@ -1,10 +1,11 @@
use register::RegistrationKind; use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
use crate::{api::client_server, services, utils, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::{ api::client::{
account::{ account::{
change_password, deactivate, get_3pids, get_username_availability, register, change_password, deactivate, get_3pids, get_username_availability, register,
request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn, whoami, request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn,
ThirdPartyIdRemovalStatus, whoami, ThirdPartyIdRemovalStatus,
}, },
error::ErrorKind, error::ErrorKind,
uiaa::{AuthFlow, AuthType, UiaaInfo}, uiaa::{AuthFlow, AuthType, UiaaInfo},
@@ -14,8 +15,7 @@ use ruma::{
}; };
use tracing::{info, warn}; use tracing::{info, warn};
use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH}; use register::RegistrationKind;
use crate::{api::client_server, services, utils, Error, Result, Ruma};
const RANDOM_USER_ID_LENGTH: usize = 10; const RANDOM_USER_ID_LENGTH: usize = 10;
@@ -28,109 +28,130 @@ const RANDOM_USER_ID_LENGTH: usize = 10;
/// - The server name of the user id matches this server /// - The server name of the user id matches this server
/// - No user or appservice on this server already claimed this username /// - No user or appservice on this server already claimed this username
/// ///
/// Note: This will not reserve the username, so the username might become /// Note: This will not reserve the username, so the username might become invalid when trying to register
/// invalid when trying to register
pub async fn get_register_available_route( pub async fn get_register_available_route(
body: Ruma<get_username_availability::v3::Request>, body: Ruma<get_username_availability::v3::Request>,
) -> Result<get_username_availability::v3::Response> { ) -> Result<get_username_availability::v3::Response> {
// Validate user id // Validate user id
let user_id = UserId::parse_with_server_name(body.username.to_lowercase(), services().globals.server_name()) let user_id = UserId::parse_with_server_name(
body.username.to_lowercase(),
services().globals.server_name(),
)
.ok() .ok()
.filter(|user_id| !user_id.is_historical() && user_id.server_name() == services().globals.server_name()) .filter(|user_id| {
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?; !user_id.is_historical() && user_id.server_name() == services().globals.server_name()
})
.ok_or(Error::BadRequest(
ErrorKind::InvalidUsername,
"Username is invalid.",
))?;
// Check if username is creative enough // Check if username is creative enough
if services().users.exists(&user_id)? { if services().users.exists(&user_id)? {
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken.")); return Err(Error::BadRequest(
ErrorKind::UserInUse,
"Desired user ID is already taken.",
));
} }
if services().globals.forbidden_usernames().is_match(user_id.localpart()) { if services()
return Err(Error::BadRequest(ErrorKind::Unknown, "Username is forbidden.")); .globals
.forbidden_usernames()
.is_match(user_id.localpart())
{
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Username is forbidden.",
));
} }
// TODO add check for appservice namespaces // TODO add check for appservice namespaces
// If no if check is true we have an username that's available to be used. // If no if check is true we have an username that's available to be used.
Ok(get_username_availability::v3::Response { Ok(get_username_availability::v3::Response { available: true })
available: true,
})
} }
/// # `POST /_matrix/client/v3/register` /// # `POST /_matrix/client/v3/register`
/// ///
/// Register an account on this homeserver. /// Register an account on this homeserver.
/// ///
/// You can use [`GET /// You can use [`GET /_matrix/client/v3/register/available`](fn.get_register_available_route.html)
/// /_matrix/client/v3/register/available`](fn.get_register_available_route. /// to check if the user id is valid and available.
/// html) to check if the user id is valid and available.
/// ///
/// - Only works if registration is enabled /// - Only works if registration is enabled
/// - If type is guest: ignores all parameters except /// - If type is guest: ignores all parameters except initial_device_display_name
/// initial_device_display_name
/// - If sender is not appservice: Requires UIAA (but we only use a dummy stage) /// - If sender is not appservice: Requires UIAA (but we only use a dummy stage)
/// - If type is not guest and no username is given: Always fails after UIAA /// - If type is not guest and no username is given: Always fails after UIAA check
/// check
/// - Creates a new account and populates it with default account data /// - Creates a new account and populates it with default account data
/// - If `inhibit_login` is false: Creates a device and returns device id and /// - If `inhibit_login` is false: Creates a device and returns device id and access_token
/// access_token
pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<register::v3::Response> { pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<register::v3::Response> {
if !services().globals.allow_registration() && !body.from_appservice { if !services().globals.allow_registration() && !body.from_appservice {
info!( info!("Registration disabled and request not from known appservice, rejecting registration attempt for username {:?}", body.username);
"Registration disabled and request not from known appservice, rejecting registration attempt for username \ return Err(Error::BadRequest(
{:?}", ErrorKind::Forbidden,
body.username "Registration has been disabled.",
); ));
return Err(Error::BadRequest(ErrorKind::Forbidden, "Registration has been disabled."));
} }
let is_guest = body.kind == RegistrationKind::Guest; let is_guest = body.kind == RegistrationKind::Guest;
if is_guest if is_guest
&& (!services().globals.allow_guest_registration() && (!services().globals.allow_guest_registration()
|| (services().globals.allow_registration() && services().globals.config.registration_token.is_some())) || (services().globals.allow_registration()
&& services().globals.config.registration_token.is_some()))
{ {
info!( info!("Guest registration disabled / registration enabled with token configured, rejecting guest registration, initial device name: {:?}", body.initial_device_display_name);
"Guest registration disabled / registration enabled with token configured, rejecting guest registration, \
initial device name: {:?}",
body.initial_device_display_name
);
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::GuestAccessForbidden, ErrorKind::GuestAccessForbidden,
"Guest registration is disabled.", "Guest registration is disabled.",
)); ));
} }
// forbid guests from registering if there is not a real admin user yet. give // forbid guests from registering if there is not a real admin user yet. give generic user error.
// generic user error.
if is_guest && services().users.count()? < 2 { if is_guest && services().users.count()? < 2 {
warn!( warn!("Guest account attempted to register before a real admin user has been registered, rejecting registration. Guest's initial device name: {:?}", body.initial_device_display_name);
"Guest account attempted to register before a real admin user has been registered, rejecting \ return Err(Error::BadRequest(
registration. Guest's initial device name: {:?}", ErrorKind::Forbidden,
body.initial_device_display_name "Registration temporarily disabled.",
); ));
return Err(Error::BadRequest(ErrorKind::Forbidden, "Registration temporarily disabled."));
} }
let user_id = match (&body.username, is_guest) { let user_id = match (&body.username, is_guest) {
(Some(username), false) => { (Some(username), false) => {
let proposed_user_id = let proposed_user_id = UserId::parse_with_server_name(
UserId::parse_with_server_name(username.to_lowercase(), services().globals.server_name()) username.to_lowercase(),
services().globals.server_name(),
)
.ok() .ok()
.filter(|user_id| { .filter(|user_id| {
!user_id.is_historical() && user_id.server_name() == services().globals.server_name() !user_id.is_historical()
&& user_id.server_name() == services().globals.server_name()
}) })
.ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?; .ok_or(Error::BadRequest(
ErrorKind::InvalidUsername,
"Username is invalid.",
))?;
if services().users.exists(&proposed_user_id)? { if services().users.exists(&proposed_user_id)? {
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken.")); return Err(Error::BadRequest(
ErrorKind::UserInUse,
"Desired user ID is already taken.",
));
} }
if services().globals.forbidden_usernames().is_match(proposed_user_id.localpart()) { if services()
return Err(Error::BadRequest(ErrorKind::Unknown, "Username is forbidden.")); .globals
.forbidden_usernames()
.is_match(proposed_user_id.localpart())
{
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Username is forbidden.",
));
} }
proposed_user_id proposed_user_id
}, }
_ => loop { _ => loop {
let proposed_user_id = UserId::parse_with_server_name( let proposed_user_id = UserId::parse_with_server_name(
utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(), utils::random_string(RANDOM_USER_ID_LENGTH).to_lowercase(),
@@ -153,7 +174,7 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
stages: vec![AuthType::RegistrationToken], stages: vec![AuthType::RegistrationToken],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
@@ -165,7 +186,7 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
stages: vec![AuthType::Dummy], stages: vec![AuthType::Dummy],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
@@ -175,7 +196,8 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
if !skip_auth { if !skip_auth {
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth( let (worked, uiaainfo) = services().uiaa.try_auth(
&UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid"), &UserId::parse_with_server_name("", services().globals.server_name())
.expect("we know this is valid"),
"".into(), "".into(),
auth, auth,
&uiaainfo, &uiaainfo,
@@ -187,7 +209,8 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
} else if let Some(json) = body.json_body { } else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create( services().uiaa.create(
&UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid"), &UserId::parse_with_server_name("", services().globals.server_name())
.expect("we know this is valid"),
"".into(), "".into(),
&uiaainfo, &uiaainfo,
&json, &json,
@@ -210,13 +233,15 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
// Default to pretty displayname // Default to pretty displayname
let mut displayname = user_id.localpart().to_owned(); let mut displayname = user_id.localpart().to_owned();
// If `new_user_displayname_suffix` is set, registration will push whatever // If enabled append lightning bolt to display name (default true)
// content is set to the user's display name with a space before it if services().globals.enable_lightning_bolt() {
if !services().globals.new_user_displayname_suffix().is_empty() { displayname.push_str(" ⚡️");
displayname.push_str(&(" ".to_owned() + services().globals.new_user_displayname_suffix()));
} }
services().users.set_displayname(&user_id, Some(displayname.clone())).await?; services()
.users
.set_displayname(&user_id, Some(displayname.clone()))
.await?;
// Initial account data // Initial account data
services().account_data.update( services().account_data.update(
@@ -254,36 +279,44 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
let token = utils::random_string(TOKEN_LENGTH); let token = utils::random_string(TOKEN_LENGTH);
// Create device for this account // Create device for this account
services().users.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?; services().users.create_device(
&user_id,
&device_id,
&token,
body.initial_device_display_name.clone(),
)?;
info!("New user \"{}\" registered on this server.", user_id); info!("New user \"{}\" registered on this server.", user_id);
// log in conduit admin channel if a non-guest user registered // log in conduit admin channel if a non-guest user registered
if !body.from_appservice && !is_guest { if !body.from_appservice && !is_guest {
services().admin.send_message(RoomMessageEventContent::notice_plain(format!( services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"New user \"{user_id}\" registered on this server." "New user \"{user_id}\" registered on this server."
))); )));
} }
// log in conduit admin channel if a guest registered // log in conduit admin channel if a guest registered
if !body.from_appservice && is_guest { if !body.from_appservice && is_guest {
services().admin.send_message(RoomMessageEventContent::notice_plain(format!( services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with device display name `{:?}` registered on this server.", "Guest user \"{user_id}\" with device display name `{:?}` registered on this server.",
body.initial_device_display_name body.initial_device_display_name
))); )));
} }
// If this is the first real user, grant them admin privileges except for guest // If this is the first real user, grant them admin privileges except for guest users
// users Note: the server user, @conduit:servername, is generated first // Note: the server user, @conduit:servername, is generated first
if !is_guest { if services().users.count()? == 2 && !is_guest {
if let Some(admin_room) = services().admin.get_admin_room()? { services()
if services().rooms.state_cache.room_joined_count(&admin_room)? == Some(1) { .admin
services().admin.make_user_admin(&user_id, displayname).await?; .make_user_admin(&user_id, displayname)
.await?;
warn!("Granting {} admin privileges as the first user", user_id); warn!("Granting {} admin privileges as the first user", user_id);
} }
}
}
Ok(register::v3::Response { Ok(register::v3::Response {
access_token: Some(token), access_token: Some(token),
@@ -300,18 +333,17 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
/// ///
/// - Requires UIAA to verify user password /// - Requires UIAA to verify user password
/// - Changes the password of the sender user /// - Changes the password of the sender user
/// - The password hash is calculated using argon2 with 32 character salt, the /// - The password hash is calculated using argon2 with 32 character salt, the plain password is
/// plain password is
/// not saved /// not saved
/// ///
/// If logout_devices is true it does the following for each device except the /// If logout_devices is true it does the following for each device except the sender device:
/// sender device:
/// - Invalidates access token /// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, /// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
pub async fn change_password_route(body: Ruma<change_password::v3::Request>) -> Result<change_password::v3::Response> { pub async fn change_password_route(
body: Ruma<change_password::v3::Request>,
) -> Result<change_password::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@@ -320,33 +352,40 @@ pub async fn change_password_route(body: Ruma<change_password::v3::Request>) ->
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?; let (worked, uiaainfo) =
services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { } else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?; services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { } else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
} }
services().users.set_password(sender_user, Some(&body.new_password))?; services()
.users
.set_password(sender_user, Some(&body.new_password))?;
if body.logout_devices { if body.logout_devices {
// Logout all devices except the current one // Logout all devices except the current one
for id in services() for id in services()
.users .users
.all_device_ids(sender_user) .all_device_ids(sender_user)
.filter_map(std::result::Result::ok) .filter_map(|id| id.ok())
.filter(|id| id != sender_device) .filter(|id| id != sender_device)
{ {
services().users.remove_device(sender_user, &id)?; services().users.remove_device(sender_user, &id)?;
@@ -354,7 +393,9 @@ pub async fn change_password_route(body: Ruma<change_password::v3::Request>) ->
} }
info!("User {} changed their password.", sender_user); info!("User {} changed their password.", sender_user);
services().admin.send_message(RoomMessageEventContent::notice_plain(format!( services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"User {sender_user} changed their password." "User {sender_user} changed their password."
))); )));
@@ -368,7 +409,7 @@ pub async fn change_password_route(body: Ruma<change_password::v3::Request>) ->
/// Note: Also works for Application Services /// Note: Also works for Application Services
pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3::Response> { pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let device_id = body.sender_device.clone(); let device_id = body.sender_device.as_ref().cloned();
Ok(whoami::v3::Response { Ok(whoami::v3::Response {
user_id: sender_user.clone(), user_id: sender_user.clone(),
@@ -383,12 +424,13 @@ pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3:
/// ///
/// - Leaves all rooms and rejects all invitations /// - Leaves all rooms and rejects all invitations
/// - Invalidates all access tokens /// - Invalidates all access tokens
/// - Deletes all device metadata (device id, device display name, last seen ip, /// - Deletes all device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets all to-device events /// - Forgets all to-device events
/// - Triggers device list updates /// - Triggers device list updates
/// - Removes ability to log in again /// - Removes ability to log in again
pub async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Result<deactivate::v3::Response> { pub async fn deactivate_route(
body: Ruma<deactivate::v3::Request>,
) -> Result<deactivate::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@@ -397,20 +439,25 @@ pub async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Result<dea
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?; let (worked, uiaainfo) =
services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { } else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?; services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { } else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
@@ -423,7 +470,9 @@ pub async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Result<dea
services().users.deactivate_account(sender_user)?; services().users.deactivate_account(sender_user)?;
info!("User {} deactivated their account.", sender_user); info!("User {} deactivated their account.", sender_user);
services().admin.send_message(RoomMessageEventContent::notice_plain(format!( services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"User {sender_user} deactivated their account." "User {sender_user} deactivated their account."
))); )));
@@ -437,7 +486,9 @@ pub async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Result<dea
/// Get a list of third party identifiers associated with this account. /// Get a list of third party identifiers associated with this account.
/// ///
/// - Currently always returns empty list /// - Currently always returns empty list
pub async fn third_party_route(body: Ruma<get_3pids::v3::Request>) -> Result<get_3pids::v3::Response> { pub async fn third_party_route(
body: Ruma<get_3pids::v3::Request>,
) -> Result<get_3pids::v3::Response> {
let _sender_user = body.sender_user.as_ref().expect("user is authenticated"); let _sender_user = body.sender_user.as_ref().expect("user is authenticated");
Ok(get_3pids::v3::Response::new(Vec::new())) Ok(get_3pids::v3::Response::new(Vec::new()))
@@ -445,11 +496,9 @@ pub async fn third_party_route(body: Ruma<get_3pids::v3::Request>) -> Result<get
/// # `POST /_matrix/client/v3/account/3pid/email/requestToken` /// # `POST /_matrix/client/v3/account/3pid/email/requestToken`
/// ///
/// "This API should be used to request validation tokens when adding an email /// "This API should be used to request validation tokens when adding an email address to an account"
/// address to an account"
/// ///
/// - 403 signals that The homeserver does not allow the third party identifier /// - 403 signals that The homeserver does not allow the third party identifier as a contact option.
/// as a contact option.
pub async fn request_3pid_management_token_via_email_route( pub async fn request_3pid_management_token_via_email_route(
_body: Ruma<request_3pid_management_token_via_email::v3::Request>, _body: Ruma<request_3pid_management_token_via_email::v3::Request>,
) -> Result<request_3pid_management_token_via_email::v3::Response> { ) -> Result<request_3pid_management_token_via_email::v3::Response> {
@@ -461,11 +510,9 @@ pub async fn request_3pid_management_token_via_email_route(
/// # `POST /_matrix/client/v3/account/3pid/msisdn/requestToken` /// # `POST /_matrix/client/v3/account/3pid/msisdn/requestToken`
/// ///
/// "This API should be used to request validation tokens when adding an phone /// "This API should be used to request validation tokens when adding an phone number to an account"
/// number to an account"
/// ///
/// - 403 signals that The homeserver does not allow the third party identifier /// - 403 signals that The homeserver does not allow the third party identifier as a contact option.
/// as a contact option.
pub async fn request_3pid_management_token_via_msisdn_route( pub async fn request_3pid_management_token_via_msisdn_route(
_body: Ruma<request_3pid_management_token_via_msisdn::v3::Request>, _body: Ruma<request_3pid_management_token_via_msisdn::v3::Request>,
) -> Result<request_3pid_management_token_via_msisdn::v3::Response> { ) -> Result<request_3pid_management_token_via_msisdn::v3::Response> {
+104 -29
View File
@@ -1,4 +1,6 @@
use crate::{services, Error, Result, Ruma};
use rand::seq::SliceRandom; use rand::seq::SliceRandom;
use regex::Regex;
use ruma::{ use ruma::{
api::{ api::{
appservice, appservice,
@@ -11,25 +13,45 @@ use ruma::{
OwnedRoomAliasId, OwnedServerName, OwnedRoomAliasId, OwnedServerName,
}; };
use crate::{services, Error, Result, Ruma};
/// # `PUT /_matrix/client/v3/directory/room/{roomAlias}` /// # `PUT /_matrix/client/v3/directory/room/{roomAlias}`
/// ///
/// Creates a new room alias on this server. /// Creates a new room alias on this server.
pub async fn create_alias_route(body: Ruma<create_alias::v3::Request>) -> Result<create_alias::v3::Response> { pub async fn create_alias_route(
body: Ruma<create_alias::v3::Request>,
) -> Result<create_alias::v3::Response> {
if body.room_alias.server_name() != services().globals.server_name() { if body.room_alias.server_name() != services().globals.server_name() {
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server.")); return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Alias is from another server.",
));
} }
if services().globals.forbidden_room_names().is_match(body.room_alias.alias()) { if services()
return Err(Error::BadRequest(ErrorKind::Unknown, "Room alias is forbidden.")); .globals
.forbidden_room_names()
.is_match(body.room_alias.alias())
{
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Room alias is forbidden.",
));
} }
if services().rooms.alias.resolve_local_alias(&body.room_alias)?.is_some() { if services()
.rooms
.alias
.resolve_local_alias(&body.room_alias)?
.is_some()
{
return Err(Error::Conflict("Alias already exists.")); return Err(Error::Conflict("Alias already exists."));
} }
if services().rooms.alias.set_alias(&body.room_alias, &body.room_id).is_err() { if services()
.rooms
.alias
.set_alias(&body.room_alias, &body.room_id)
.is_err()
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Invalid room alias. Alias must be in the form of '#localpart:server_name'", "Invalid room alias. Alias must be in the form of '#localpart:server_name'",
@@ -45,16 +67,34 @@ pub async fn create_alias_route(body: Ruma<create_alias::v3::Request>) -> Result
/// ///
/// - TODO: additional access control checks /// - TODO: additional access control checks
/// - TODO: Update canonical alias event /// - TODO: Update canonical alias event
pub async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) -> Result<delete_alias::v3::Response> { pub async fn delete_alias_route(
body: Ruma<delete_alias::v3::Request>,
) -> Result<delete_alias::v3::Response> {
if body.room_alias.server_name() != services().globals.server_name() { if body.room_alias.server_name() != services().globals.server_name() {
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server.")); return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Alias is from another server.",
));
} }
if services().rooms.alias.resolve_local_alias(&body.room_alias)?.is_none() { if services()
return Err(Error::BadRequest(ErrorKind::NotFound, "Alias does not exist.")); .rooms
.alias
.resolve_local_alias(&body.room_alias)?
.is_none()
{
return Err(Error::BadRequest(
ErrorKind::NotFound,
"Alias does not exist.",
));
} }
if services().rooms.alias.remove_alias(&body.room_alias).is_err() { if services()
.rooms
.alias
.remove_alias(&body.room_alias)
.is_err()
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Invalid room alias. Alias must be in the form of '#localpart:server_name'", "Invalid room alias. Alias must be in the form of '#localpart:server_name'",
@@ -69,18 +109,22 @@ pub async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) -> Result
/// # `GET /_matrix/client/v3/directory/room/{roomAlias}` /// # `GET /_matrix/client/v3/directory/room/{roomAlias}`
/// ///
/// Resolve an alias locally or over federation. /// Resolve an alias locally or over federation.
pub async fn get_alias_route(body: Ruma<get_alias::v3::Request>) -> Result<get_alias::v3::Response> { pub async fn get_alias_route(
body: Ruma<get_alias::v3::Request>,
) -> Result<get_alias::v3::Response> {
get_alias_helper(body.body.room_alias).await get_alias_helper(body.body.room_alias).await
} }
pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get_alias::v3::Response> { pub(crate) async fn get_alias_helper(
room_alias: OwnedRoomAliasId,
) -> Result<get_alias::v3::Response> {
if room_alias.server_name() != services().globals.server_name() { if room_alias.server_name() != services().globals.server_name() {
let response = services() let response = services()
.sending .sending
.send_federation_request( .send_federation_request(
room_alias.server_name(), room_alias.server_name(),
federation::query::get_room_information::v1::Request { federation::query::get_room_information::v1::Request {
room_alias: room_alias.clone(), room_alias: room_alias.to_owned(),
}, },
) )
.await?; .await?;
@@ -90,13 +134,20 @@ pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get
let mut servers = response.servers; let mut servers = response.servers;
// find active servers in room state cache to suggest // find active servers in room state cache to suggest
for extra_servers in services().rooms.state_cache.room_servers(&room_id).filter_map(std::result::Result::ok) { for extra_servers in services()
.rooms
.state_cache
.room_servers(&room_id)
.filter_map(|r| r.ok())
{
servers.push(extra_servers); servers.push(extra_servers);
} }
// insert our server as the very first choice if in list // insert our server as the very first choice if in list
if let Some(server_index) = if let Some(server_index) = servers
servers.clone().into_iter().position(|server| server == services().globals.server_name()) .clone()
.into_iter()
.position(|server| server == services().globals.server_name())
{ {
servers.remove(server_index); servers.remove(server_index);
servers.insert(0, services().globals.server_name().to_owned()); servers.insert(0, services().globals.server_name().to_owned());
@@ -115,12 +166,21 @@ pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get
match services().rooms.alias.resolve_local_alias(&room_alias)? { match services().rooms.alias.resolve_local_alias(&room_alias)? {
Some(r) => room_id = Some(r), Some(r) => room_id = Some(r),
None => { None => {
for appservice in services().appservice.registration_info.read().await.values() { for (_id, registration) in services().appservice.all()? {
if appservice.aliases.is_match(room_alias.as_str()) let aliases = registration
.namespaces
.aliases
.iter()
.filter_map(|alias| Regex::new(alias.regex.as_str()).ok())
.collect::<Vec<_>>();
if aliases
.iter()
.any(|aliases| aliases.is_match(room_alias.as_str()))
&& if let Some(opt_result) = services() && if let Some(opt_result) = services()
.sending .sending
.send_appservice_request( .send_appservice_request(
appservice.registration.clone(), registration,
appservice::query::query_room_alias::v1::Request { appservice::query::query_room_alias::v1::Request {
room_alias: room_alias.clone(), room_alias: room_alias.clone(),
}, },
@@ -130,35 +190,50 @@ pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get
opt_result.is_ok() opt_result.is_ok()
} else { } else {
false false
} { }
{
room_id = Some( room_id = Some(
services() services()
.rooms .rooms
.alias .alias
.resolve_local_alias(&room_alias)? .resolve_local_alias(&room_alias)?
.ok_or_else(|| Error::bad_config("Room does not exist."))?, .ok_or_else(|| {
Error::bad_config("Appservice lied to us. Room does not exist.")
})?,
); );
break; break;
} }
} }
}, }
}; };
let room_id = match room_id { let room_id = match room_id {
Some(room_id) => room_id, Some(room_id) => room_id,
None => return Err(Error::BadRequest(ErrorKind::NotFound, "Room with alias not found.")), None => {
return Err(Error::BadRequest(
ErrorKind::NotFound,
"Room with alias not found.",
))
}
}; };
let mut servers: Vec<OwnedServerName> = Vec::new(); let mut servers: Vec<OwnedServerName> = Vec::new();
// find active servers in room state cache to suggest // find active servers in room state cache to suggest
for extra_servers in services().rooms.state_cache.room_servers(&room_id).filter_map(std::result::Result::ok) { for extra_servers in services()
.rooms
.state_cache
.room_servers(&room_id)
.filter_map(|r| r.ok())
{
servers.push(extra_servers); servers.push(extra_servers);
} }
// insert our server as the very first choice if in list // insert our server as the very first choice if in list
if let Some(server_index) = if let Some(server_index) = servers
servers.clone().into_iter().position(|server| server == services().globals.server_name()) .clone()
.into_iter()
.position(|server| server == services().globals.server_name())
{ {
servers.remove(server_index); servers.remove(server_index);
servers.insert(0, services().globals.server_name().to_owned()); servers.insert(0, services().globals.server_name().to_owned());
+152 -65
View File
@@ -1,15 +1,15 @@
use crate::{services, Error, Result, Ruma};
use ruma::api::client::{ use ruma::api::client::{
backup::{ backup::{
add_backup_keys, add_backup_keys_for_room, add_backup_keys_for_session, create_backup_version, add_backup_keys, add_backup_keys_for_room, add_backup_keys_for_session,
delete_backup_keys, delete_backup_keys_for_room, delete_backup_keys_for_session, delete_backup_version, create_backup_version, delete_backup_keys, delete_backup_keys_for_room,
get_backup_info, get_backup_keys, get_backup_keys_for_room, get_backup_keys_for_session, delete_backup_keys_for_session, delete_backup_version, get_backup_info, get_backup_keys,
get_latest_backup_info, update_backup_version, get_backup_keys_for_room, get_backup_keys_for_session, get_latest_backup_info,
update_backup_version,
}, },
error::ErrorKind, error::ErrorKind,
}; };
use crate::{services, Error, Result, Ruma};
/// # `POST /_matrix/client/r0/room_keys/version` /// # `POST /_matrix/client/r0/room_keys/version`
/// ///
/// Creates a new backup. /// Creates a new backup.
@@ -17,22 +17,23 @@ pub async fn create_backup_version_route(
body: Ruma<create_backup_version::v3::Request>, body: Ruma<create_backup_version::v3::Request>,
) -> Result<create_backup_version::v3::Response> { ) -> Result<create_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let version = services().key_backups.create_backup(sender_user, &body.algorithm)?; let version = services()
.key_backups
.create_backup(sender_user, &body.algorithm)?;
Ok(create_backup_version::v3::Response { Ok(create_backup_version::v3::Response { version })
version,
})
} }
/// # `PUT /_matrix/client/r0/room_keys/version/{version}` /// # `PUT /_matrix/client/r0/room_keys/version/{version}`
/// ///
/// Update information about an existing backup. Only `auth_data` can be /// Update information about an existing backup. Only `auth_data` can be modified.
/// modified.
pub async fn update_backup_version_route( pub async fn update_backup_version_route(
body: Ruma<update_backup_version::v3::Request>, body: Ruma<update_backup_version::v3::Request>,
) -> Result<update_backup_version::v3::Response> { ) -> Result<update_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.update_backup(sender_user, &body.version, &body.algorithm)?; services()
.key_backups
.update_backup(sender_user, &body.version, &body.algorithm)?;
Ok(update_backup_version::v3::Response {}) Ok(update_backup_version::v3::Response {})
} }
@@ -48,7 +49,10 @@ pub async fn get_latest_backup_info_route(
let (version, algorithm) = services() let (version, algorithm) = services()
.key_backups .key_backups
.get_latest_backup(sender_user)? .get_latest_backup(sender_user)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Key backup does not exist.",
))?;
Ok(get_latest_backup_info::v3::Response { Ok(get_latest_backup_info::v3::Response {
algorithm, algorithm,
@@ -61,18 +65,28 @@ pub async fn get_latest_backup_info_route(
/// # `GET /_matrix/client/r0/room_keys/version` /// # `GET /_matrix/client/r0/room_keys/version`
/// ///
/// Get information about an existing backup. /// Get information about an existing backup.
pub async fn get_backup_info_route(body: Ruma<get_backup_info::v3::Request>) -> Result<get_backup_info::v3::Response> { pub async fn get_backup_info_route(
body: Ruma<get_backup_info::v3::Request>,
) -> Result<get_backup_info::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let algorithm = services() let algorithm = services()
.key_backups .key_backups
.get_backup(sender_user, &body.version)? .get_backup(sender_user, &body.version)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Key backup does not exist."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Key backup does not exist.",
))?;
Ok(get_backup_info::v3::Response { Ok(get_backup_info::v3::Response {
algorithm, algorithm,
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(), count: (services()
etag: services().key_backups.get_etag(sender_user, &body.version)?, .key_backups
version: body.version.clone(), .count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
version: body.version.to_owned(),
}) })
} }
@@ -80,14 +94,15 @@ pub async fn get_backup_info_route(body: Ruma<get_backup_info::v3::Request>) ->
/// ///
/// Delete an existing key backup. /// Delete an existing key backup.
/// ///
/// - Deletes both information about the backup, as well as all key data related /// - Deletes both information about the backup, as well as all key data related to the backup
/// to the backup
pub async fn delete_backup_version_route( pub async fn delete_backup_version_route(
body: Ruma<delete_backup_version::v3::Request>, body: Ruma<delete_backup_version::v3::Request>,
) -> Result<delete_backup_version::v3::Response> { ) -> Result<delete_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.delete_backup(sender_user, &body.version)?; services()
.key_backups
.delete_backup(sender_user, &body.version)?;
Ok(delete_backup_version::v3::Response {}) Ok(delete_backup_version::v3::Response {})
} }
@@ -96,14 +111,20 @@ pub async fn delete_backup_version_route(
/// ///
/// Add the received backup keys to the database. /// Add the received backup keys to the database.
/// ///
/// - Only manipulating the most recently created version of the backup is /// - Only manipulating the most recently created version of the backup is allowed
/// allowed
/// - Adds the keys to the backup /// - Adds the keys to the backup
/// - Returns the new number of keys in this backup and the etag /// - Returns the new number of keys in this backup and the etag
pub async fn add_backup_keys_route(body: Ruma<add_backup_keys::v3::Request>) -> Result<add_backup_keys::v3::Response> { pub async fn add_backup_keys_route(
body: Ruma<add_backup_keys::v3::Request>,
) -> Result<add_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if Some(&body.version) != services().key_backups.get_latest_backup_version(sender_user)?.as_ref() { if Some(&body.version)
!= services()
.key_backups
.get_latest_backup_version(sender_user)?
.as_ref()
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.", "You may only manipulate the most recently created version of the backup.",
@@ -112,13 +133,24 @@ pub async fn add_backup_keys_route(body: Ruma<add_backup_keys::v3::Request>) ->
for (room_id, room) in &body.rooms { for (room_id, room) in &body.rooms {
for (session_id, key_data) in &room.sessions { for (session_id, key_data) in &room.sessions {
services().key_backups.add_key(sender_user, &body.version, room_id, session_id, key_data)?; services().key_backups.add_key(
sender_user,
&body.version,
room_id,
session_id,
key_data,
)?
} }
} }
Ok(add_backup_keys::v3::Response { Ok(add_backup_keys::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(), count: (services()
etag: services().key_backups.get_etag(sender_user, &body.version)?, .key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
}) })
} }
@@ -126,8 +158,7 @@ pub async fn add_backup_keys_route(body: Ruma<add_backup_keys::v3::Request>) ->
/// ///
/// Add the received backup keys to the database. /// Add the received backup keys to the database.
/// ///
/// - Only manipulating the most recently created version of the backup is /// - Only manipulating the most recently created version of the backup is allowed
/// allowed
/// - Adds the keys to the backup /// - Adds the keys to the backup
/// - Returns the new number of keys in this backup and the etag /// - Returns the new number of keys in this backup and the etag
pub async fn add_backup_keys_for_room_route( pub async fn add_backup_keys_for_room_route(
@@ -135,7 +166,12 @@ pub async fn add_backup_keys_for_room_route(
) -> Result<add_backup_keys_for_room::v3::Response> { ) -> Result<add_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if Some(&body.version) != services().key_backups.get_latest_backup_version(sender_user)?.as_ref() { if Some(&body.version)
!= services()
.key_backups
.get_latest_backup_version(sender_user)?
.as_ref()
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.", "You may only manipulate the most recently created version of the backup.",
@@ -143,12 +179,23 @@ pub async fn add_backup_keys_for_room_route(
} }
for (session_id, key_data) in &body.sessions { for (session_id, key_data) in &body.sessions {
services().key_backups.add_key(sender_user, &body.version, &body.room_id, session_id, key_data)?; services().key_backups.add_key(
sender_user,
&body.version,
&body.room_id,
session_id,
key_data,
)?
} }
Ok(add_backup_keys_for_room::v3::Response { Ok(add_backup_keys_for_room::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(), count: (services()
etag: services().key_backups.get_etag(sender_user, &body.version)?, .key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
}) })
} }
@@ -156,8 +203,7 @@ pub async fn add_backup_keys_for_room_route(
/// ///
/// Add the received backup key to the database. /// Add the received backup key to the database.
/// ///
/// - Only manipulating the most recently created version of the backup is /// - Only manipulating the most recently created version of the backup is allowed
/// allowed
/// - Adds the keys to the backup /// - Adds the keys to the backup
/// - Returns the new number of keys in this backup and the etag /// - Returns the new number of keys in this backup and the etag
pub async fn add_backup_keys_for_session_route( pub async fn add_backup_keys_for_session_route(
@@ -165,32 +211,48 @@ pub async fn add_backup_keys_for_session_route(
) -> Result<add_backup_keys_for_session::v3::Response> { ) -> Result<add_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if Some(&body.version) != services().key_backups.get_latest_backup_version(sender_user)?.as_ref() { if Some(&body.version)
!= services()
.key_backups
.get_latest_backup_version(sender_user)?
.as_ref()
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.", "You may only manipulate the most recently created version of the backup.",
)); ));
} }
services().key_backups.add_key(sender_user, &body.version, &body.room_id, &body.session_id, &body.session_data)?; services().key_backups.add_key(
sender_user,
&body.version,
&body.room_id,
&body.session_id,
&body.session_data,
)?;
Ok(add_backup_keys_for_session::v3::Response { Ok(add_backup_keys_for_session::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(), count: (services()
etag: services().key_backups.get_etag(sender_user, &body.version)?, .key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
}) })
} }
/// # `GET /_matrix/client/r0/room_keys/keys` /// # `GET /_matrix/client/r0/room_keys/keys`
/// ///
/// Retrieves all keys from the backup. /// Retrieves all keys from the backup.
pub async fn get_backup_keys_route(body: Ruma<get_backup_keys::v3::Request>) -> Result<get_backup_keys::v3::Response> { pub async fn get_backup_keys_route(
body: Ruma<get_backup_keys::v3::Request>,
) -> Result<get_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let rooms = services().key_backups.get_all(sender_user, &body.version)?; let rooms = services().key_backups.get_all(sender_user, &body.version)?;
Ok(get_backup_keys::v3::Response { Ok(get_backup_keys::v3::Response { rooms })
rooms,
})
} }
/// # `GET /_matrix/client/r0/room_keys/keys/{roomId}` /// # `GET /_matrix/client/r0/room_keys/keys/{roomId}`
@@ -201,11 +263,11 @@ pub async fn get_backup_keys_for_room_route(
) -> Result<get_backup_keys_for_room::v3::Response> { ) -> Result<get_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sessions = services().key_backups.get_room(sender_user, &body.version, &body.room_id)?; let sessions = services()
.key_backups
.get_room(sender_user, &body.version, &body.room_id)?;
Ok(get_backup_keys_for_room::v3::Response { Ok(get_backup_keys_for_room::v3::Response { sessions })
sessions,
})
} }
/// # `GET /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}` /// # `GET /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
@@ -216,14 +278,15 @@ pub async fn get_backup_keys_for_session_route(
) -> Result<get_backup_keys_for_session::v3::Response> { ) -> Result<get_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let key_data = let key_data = services()
services().key_backups.get_session(sender_user, &body.version, &body.room_id, &body.session_id)?.ok_or( .key_backups
Error::BadRequest(ErrorKind::NotFound, "Backup key not found for this user's session."), .get_session(sender_user, &body.version, &body.room_id, &body.session_id)?
)?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Backup key not found for this user's session.",
))?;
Ok(get_backup_keys_for_session::v3::Response { Ok(get_backup_keys_for_session::v3::Response { key_data })
key_data,
})
} }
/// # `DELETE /_matrix/client/r0/room_keys/keys` /// # `DELETE /_matrix/client/r0/room_keys/keys`
@@ -234,11 +297,18 @@ pub async fn delete_backup_keys_route(
) -> Result<delete_backup_keys::v3::Response> { ) -> Result<delete_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.delete_all_keys(sender_user, &body.version)?; services()
.key_backups
.delete_all_keys(sender_user, &body.version)?;
Ok(delete_backup_keys::v3::Response { Ok(delete_backup_keys::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(), count: (services()
etag: services().key_backups.get_etag(sender_user, &body.version)?, .key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
}) })
} }
@@ -250,11 +320,18 @@ pub async fn delete_backup_keys_for_room_route(
) -> Result<delete_backup_keys_for_room::v3::Response> { ) -> Result<delete_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.delete_room_keys(sender_user, &body.version, &body.room_id)?; services()
.key_backups
.delete_room_keys(sender_user, &body.version, &body.room_id)?;
Ok(delete_backup_keys_for_room::v3::Response { Ok(delete_backup_keys_for_room::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(), count: (services()
etag: services().key_backups.get_etag(sender_user, &body.version)?, .key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
}) })
} }
@@ -266,10 +343,20 @@ pub async fn delete_backup_keys_for_session_route(
) -> Result<delete_backup_keys_for_session::v3::Response> { ) -> Result<delete_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.delete_room_key(sender_user, &body.version, &body.room_id, &body.session_id)?; services().key_backups.delete_room_key(
sender_user,
&body.version,
&body.room_id,
&body.session_id,
)?;
Ok(delete_backup_keys_for_session::v3::Response { Ok(delete_backup_keys_for_session::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(), count: (services()
etag: services().key_backups.get_etag(sender_user, &body.version)?, .key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
}) })
} }
+4 -9
View File
@@ -1,15 +1,12 @@
use std::collections::BTreeMap; use crate::{services, Result, Ruma};
use ruma::api::client::discovery::get_capabilities::{ use ruma::api::client::discovery::get_capabilities::{
self, Capabilities, RoomVersionStability, RoomVersionsCapability, self, Capabilities, RoomVersionStability, RoomVersionsCapability,
}; };
use std::collections::BTreeMap;
use crate::{services, Result, Ruma};
/// # `GET /_matrix/client/r0/capabilities` /// # `GET /_matrix/client/r0/capabilities`
/// ///
/// Get information on the supported feature set and other relevent capabilities /// Get information on the supported feature set and other relevent capabilities of this server.
/// of this server.
pub async fn get_capabilities_route( pub async fn get_capabilities_route(
_body: Ruma<get_capabilities::v3::Request>, _body: Ruma<get_capabilities::v3::Request>,
) -> Result<get_capabilities::v3::Response> { ) -> Result<get_capabilities::v3::Response> {
@@ -27,7 +24,5 @@ pub async fn get_capabilities_route(
available, available,
}; };
Ok(get_capabilities::v3::Response { Ok(get_capabilities::v3::Response { capabilities })
capabilities,
})
} }
+7 -9
View File
@@ -1,6 +1,10 @@
use crate::{services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::{ api::client::{
config::{get_global_account_data, get_room_account_data, set_global_account_data, set_room_account_data}, config::{
get_global_account_data, get_room_account_data, set_global_account_data,
set_room_account_data,
},
error::ErrorKind, error::ErrorKind,
}, },
events::{AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent}, events::{AnyGlobalAccountDataEventContent, AnyRoomAccountDataEventContent},
@@ -9,8 +13,6 @@ use ruma::{
use serde::Deserialize; use serde::Deserialize;
use serde_json::{json, value::RawValue as RawJsonValue}; use serde_json::{json, value::RawValue as RawJsonValue};
use crate::{services, Error, Result, Ruma};
/// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}` /// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`
/// ///
/// Sets some account data for the sender user. /// Sets some account data for the sender user.
@@ -80,9 +82,7 @@ pub async fn get_global_account_data_route(
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content; .content;
Ok(get_global_account_data::v3::Response { Ok(get_global_account_data::v3::Response { account_data })
account_data,
})
} }
/// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}` /// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`
@@ -102,9 +102,7 @@ pub async fn get_room_account_data_route(
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content; .content;
Ok(get_room_account_data::v3::Response { Ok(get_room_account_data::v3::Response { account_data })
account_data,
})
} }
#[derive(Deserialize)] #[derive(Deserialize)]
+61 -29
View File
@@ -1,21 +1,20 @@
use std::collections::HashSet; use crate::{services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::{context::get_context, error::ErrorKind, filter::LazyLoadOptions}, api::client::{context::get_context, error::ErrorKind, filter::LazyLoadOptions},
events::StateEventType, events::StateEventType,
}; };
use std::collections::HashSet;
use tracing::error; use tracing::error;
use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/r0/rooms/{roomId}/context` /// # `GET /_matrix/client/r0/rooms/{roomId}/context`
/// ///
/// Allows loading room history around an event. /// Allows loading room history around an event.
/// ///
/// - Only works if the user is joined (TODO: always allow, but only show events /// - Only works if the user is joined (TODO: always allow, but only show events if the user was
/// if the user was
/// joined, depending on history_visibility) /// joined, depending on history_visibility)
pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<get_context::v3::Response> { pub async fn get_context_route(
body: Ruma<get_context::v3::Request>,
) -> Result<get_context::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@@ -23,7 +22,7 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
LazyLoadOptions::Enabled { LazyLoadOptions::Enabled {
include_redundant_members, include_redundant_members,
} => (true, *include_redundant_members), } => (true, *include_redundant_members),
LazyLoadOptions::Disabled => (false, false), _ => (false, false),
}; };
let mut lazy_loaded = HashSet::new(); let mut lazy_loaded = HashSet::new();
@@ -32,17 +31,28 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
.rooms .rooms
.timeline .timeline
.get_pdu_count(&body.event_id)? .get_pdu_count(&body.event_id)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Base event id not found."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Base event id not found.",
))?;
let base_event = services() let base_event =
services()
.rooms .rooms
.timeline .timeline
.get_pdu(&body.event_id)? .get_pdu(&body.event_id)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Base event not found."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Base event not found.",
))?;
let room_id = base_event.room_id.clone(); let room_id = base_event.room_id.clone();
if !services().rooms.state_accessor.user_can_see_event(sender_user, &room_id, &body.event_id)? { if !services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &room_id, &body.event_id)?
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"You don't have permission to view this event.", "You don't have permission to view this event.",
@@ -69,7 +79,7 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
.timeline .timeline
.pdus_until(sender_user, &room_id, base_token)? .pdus_until(sender_user, &room_id, base_token)?
.take(limit / 2) .take(limit / 2)
.filter_map(std::result::Result::ok) // Remove buggy events .filter_map(|r| r.ok()) // Remove buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
@@ -91,17 +101,22 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
} }
} }
let start_token = let start_token = events_before
events_before.last().map(|(count, _)| count.stringify()).unwrap_or_else(|| base_token.stringify()); .last()
.map(|(count, _)| count.stringify())
.unwrap_or_else(|| base_token.stringify());
let events_before: Vec<_> = events_before.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect(); let events_before: Vec<_> = events_before
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
let events_after: Vec<_> = services() let events_after: Vec<_> = services()
.rooms .rooms
.timeline .timeline
.pdus_after(sender_user, &room_id, base_token)? .pdus_after(sender_user, &room_id, base_token)?
.take(limit / 2) .take(limit / 2)
.filter_map(std::result::Result::ok) // Remove buggy events .filter_map(|r| r.ok()) // Remove buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
@@ -123,25 +138,42 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
} }
} }
let shortstatehash = match services() let shortstatehash = match services().rooms.state_accessor.pdu_shortstatehash(
.rooms events_after
.state_accessor .last()
.pdu_shortstatehash(events_after.last().map_or(&*body.event_id, |(_, e)| &*e.event_id))? .map_or(&*body.event_id, |(_, e)| &*e.event_id),
{ )? {
Some(s) => s, Some(s) => s,
None => services().rooms.state.get_room_shortstatehash(&room_id)?.expect("All rooms have state"), None => services()
.rooms
.state
.get_room_shortstatehash(&room_id)?
.expect("All rooms have state"),
}; };
let state_ids = services().rooms.state_accessor.state_full_ids(shortstatehash).await?; let state_ids = services()
.rooms
.state_accessor
.state_full_ids(shortstatehash)
.await?;
let end_token = events_after.last().map(|(count, _)| count.stringify()).unwrap_or_else(|| base_token.stringify()); let end_token = events_after
.last()
.map(|(count, _)| count.stringify())
.unwrap_or_else(|| base_token.stringify());
let events_after: Vec<_> = events_after.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect(); let events_after: Vec<_> = events_after
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
let mut state = Vec::new(); let mut state = Vec::new();
for (shortstatekey, id) in state_ids { for (shortstatekey, id) in state_ids {
let (event_type, state_key) = services().rooms.short.get_statekey_from_short(shortstatekey)?; let (event_type, state_key) = services()
.rooms
.short
.get_statekey_from_short(shortstatekey)?;
if event_type != StateEventType::RoomMember { if event_type != StateEventType::RoomMember {
let pdu = match services().rooms.timeline.get_pdu(&id)? { let pdu = match services().rooms.timeline.get_pdu(&id)? {
@@ -149,7 +181,7 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
None => { None => {
error!("Pdu in state not found: {}", id); error!("Pdu in state not found: {}", id);
continue; continue;
}, }
}; };
state.push(pdu.to_state_event()); state.push(pdu.to_state_event());
} else if !lazy_load_enabled || lazy_loaded.contains(&state_key) { } else if !lazy_load_enabled || lazy_loaded.contains(&state_key) {
@@ -158,7 +190,7 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
None => { None => {
error!("Pdu in state not found: {}", id); error!("Pdu in state not found: {}", id);
continue; continue;
}, }
}; };
state.push(pdu.to_state_event()); state.push(pdu.to_state_event());
} }
+45 -27
View File
@@ -1,3 +1,4 @@
use crate::{services, utils, Error, Result, Ruma};
use ruma::api::client::{ use ruma::api::client::{
device::{self, delete_device, delete_devices, get_device, get_devices, update_device}, device::{self, delete_device, delete_devices, get_device, get_devices, update_device},
error::ErrorKind, error::ErrorKind,
@@ -5,29 +6,30 @@ use ruma::api::client::{
}; };
use super::SESSION_ID_LENGTH; use super::SESSION_ID_LENGTH;
use crate::{services, utils, Error, Result, Ruma};
/// # `GET /_matrix/client/r0/devices` /// # `GET /_matrix/client/r0/devices`
/// ///
/// Get metadata on all devices of the sender user. /// Get metadata on all devices of the sender user.
pub async fn get_devices_route(body: Ruma<get_devices::v3::Request>) -> Result<get_devices::v3::Response> { pub async fn get_devices_route(
body: Ruma<get_devices::v3::Request>,
) -> Result<get_devices::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let devices: Vec<device::Device> = services() let devices: Vec<device::Device> = services()
.users .users
.all_devices_metadata(sender_user) .all_devices_metadata(sender_user)
.filter_map(std::result::Result::ok) // Filter out buggy devices .filter_map(|r| r.ok()) // Filter out buggy devices
.collect(); .collect();
Ok(get_devices::v3::Response { Ok(get_devices::v3::Response { devices })
devices,
})
} }
/// # `GET /_matrix/client/r0/devices/{deviceId}` /// # `GET /_matrix/client/r0/devices/{deviceId}`
/// ///
/// Get metadata on a single device of the sender user. /// Get metadata on a single device of the sender user.
pub async fn get_device_route(body: Ruma<get_device::v3::Request>) -> Result<get_device::v3::Response> { pub async fn get_device_route(
body: Ruma<get_device::v3::Request>,
) -> Result<get_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let device = services() let device = services()
@@ -35,15 +37,15 @@ pub async fn get_device_route(body: Ruma<get_device::v3::Request>) -> Result<get
.get_device_metadata(sender_user, &body.body.device_id)? .get_device_metadata(sender_user, &body.body.device_id)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?;
Ok(get_device::v3::Response { Ok(get_device::v3::Response { device })
device,
})
} }
/// # `PUT /_matrix/client/r0/devices/{deviceId}` /// # `PUT /_matrix/client/r0/devices/{deviceId}`
/// ///
/// Updates the metadata on a given device of the sender user. /// Updates the metadata on a given device of the sender user.
pub async fn update_device_route(body: Ruma<update_device::v3::Request>) -> Result<update_device::v3::Response> { pub async fn update_device_route(
body: Ruma<update_device::v3::Request>,
) -> Result<update_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mut device = services() let mut device = services()
@@ -51,9 +53,11 @@ pub async fn update_device_route(body: Ruma<update_device::v3::Request>) -> Resu
.get_device_metadata(sender_user, &body.device_id)? .get_device_metadata(sender_user, &body.device_id)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Device not found."))?;
device.display_name.clone_from(&body.display_name); device.display_name = body.display_name.clone();
services().users.update_device_metadata(sender_user, &body.device_id, &device)?; services()
.users
.update_device_metadata(sender_user, &body.device_id, &device)?;
Ok(update_device::v3::Response {}) Ok(update_device::v3::Response {})
} }
@@ -64,11 +68,12 @@ pub async fn update_device_route(body: Ruma<update_device::v3::Request>) -> Resu
/// ///
/// - Requires UIAA to verify user password /// - Requires UIAA to verify user password
/// - Invalidates access token /// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, /// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
pub async fn delete_device_route(body: Ruma<delete_device::v3::Request>) -> Result<delete_device::v3::Response> { pub async fn delete_device_route(
body: Ruma<delete_device::v3::Request>,
) -> Result<delete_device::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@@ -78,26 +83,33 @@ pub async fn delete_device_route(body: Ruma<delete_device::v3::Request>) -> Resu
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?; let (worked, uiaainfo) =
services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { } else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?; services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { } else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
} }
services().users.remove_device(sender_user, &body.device_id)?; services()
.users
.remove_device(sender_user, &body.device_id)?;
Ok(delete_device::v3::Response {}) Ok(delete_device::v3::Response {})
} }
@@ -110,11 +122,12 @@ pub async fn delete_device_route(body: Ruma<delete_device::v3::Request>) -> Resu
/// ///
/// For each device: /// For each device:
/// - Invalidates access token /// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, /// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
pub async fn delete_devices_route(body: Ruma<delete_devices::v3::Request>) -> Result<delete_devices::v3::Response> { pub async fn delete_devices_route(
body: Ruma<delete_devices::v3::Request>,
) -> Result<delete_devices::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
@@ -124,27 +137,32 @@ pub async fn delete_devices_route(body: Ruma<delete_devices::v3::Request>) -> Re
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?; let (worked, uiaainfo) =
services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { } else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?; services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { } else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
} }
for device_id in &body.devices { for device_id in &body.devices {
services().users.remove_device(sender_user, device_id)?; services().users.remove_device(sender_user, device_id)?
} }
Ok(delete_devices::v3::Response {}) Ok(delete_devices::v3::Response {})
+62 -19
View File
@@ -1,7 +1,11 @@
use crate::{services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::{ api::{
client::{ client::{
directory::{get_public_rooms, get_public_rooms_filtered, get_room_visibility, set_room_visibility}, directory::{
get_public_rooms, get_public_rooms_filtered, get_room_visibility,
set_room_visibility,
},
error::ErrorKind, error::ErrorKind,
room, room,
}, },
@@ -24,8 +28,6 @@ use ruma::{
}; };
use tracing::{error, info, warn}; use tracing::{error, info, warn};
use crate::{services, Error, Result, Ruma};
/// # `POST /_matrix/client/v3/publicRooms` /// # `POST /_matrix/client/v3/publicRooms`
/// ///
/// Lists the public rooms on this server. /// Lists the public rooms on this server.
@@ -34,7 +36,11 @@ use crate::{services, Error, Result, Ruma};
pub async fn get_public_rooms_filtered_route( pub async fn get_public_rooms_filtered_route(
body: Ruma<get_public_rooms_filtered::v3::Request>, body: Ruma<get_public_rooms_filtered::v3::Request>,
) -> Result<get_public_rooms_filtered::v3::Response> { ) -> Result<get_public_rooms_filtered::v3::Response> {
if !services().globals.config.allow_public_room_directory_without_auth { if !services()
.globals
.config
.allow_public_room_directory_without_auth
{
let _sender_user = body.sender_user.as_ref().expect("user is authenticated"); let _sender_user = body.sender_user.as_ref().expect("user is authenticated");
} }
@@ -56,7 +62,11 @@ pub async fn get_public_rooms_filtered_route(
pub async fn get_public_rooms_route( pub async fn get_public_rooms_route(
body: Ruma<get_public_rooms::v3::Request>, body: Ruma<get_public_rooms::v3::Request>,
) -> Result<get_public_rooms::v3::Response> { ) -> Result<get_public_rooms::v3::Response> {
if !services().globals.config.allow_public_room_directory_without_auth { if !services()
.globals
.config
.allow_public_room_directory_without_auth
{
let _sender_user = body.sender_user.as_ref().expect("user is authenticated"); let _sender_user = body.sender_user.as_ref().expect("user is authenticated");
} }
@@ -96,14 +106,14 @@ pub async fn set_room_visibility_route(
room::Visibility::Public => { room::Visibility::Public => {
services().rooms.directory.set_public(&body.room_id)?; services().rooms.directory.set_public(&body.room_id)?;
info!("{} made {} public", sender_user, body.room_id); info!("{} made {} public", sender_user, body.room_id);
}, }
room::Visibility::Private => services().rooms.directory.set_not_public(&body.room_id)?, room::Visibility::Private => services().rooms.directory.set_not_public(&body.room_id)?,
_ => { _ => {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Room visibility type is not supported.", "Room visibility type is not supported.",
)); ));
}, }
} }
Ok(set_room_visibility::v3::Response {}) Ok(set_room_visibility::v3::Response {})
@@ -130,9 +140,15 @@ pub async fn get_room_visibility_route(
} }
pub(crate) async fn get_public_rooms_filtered_helper( pub(crate) async fn get_public_rooms_filtered_helper(
server: Option<&ServerName>, limit: Option<UInt>, since: Option<&str>, filter: &Filter, _network: &RoomNetwork, server: Option<&ServerName>,
limit: Option<UInt>,
since: Option<&str>,
filter: &Filter,
_network: &RoomNetwork,
) -> Result<get_public_rooms_filtered::v3::Response> { ) -> Result<get_public_rooms_filtered::v3::Response> {
if let Some(other_server) = server.filter(|server| *server != services().globals.server_name().as_str()) { if let Some(other_server) =
server.filter(|server| *server != services().globals.server_name().as_str())
{
let response = services() let response = services()
.sending .sending
.send_federation_request( .send_federation_request(
@@ -165,7 +181,12 @@ pub(crate) async fn get_public_rooms_filtered_helper(
let backwards = match characters.next() { let backwards = match characters.next() {
Some('n') => false, Some('n') => false,
Some('p') => true, Some('p') => true,
_ => return Err(Error::BadRequest(ErrorKind::InvalidParam, "Invalid `since` token")), _ => {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid `since` token",
))
}
}; };
num_since = characters num_since = characters
@@ -193,7 +214,9 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.map_or(Ok(None), |s| { .map_or(Ok(None), |s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomCanonicalAliasEventContent| c.alias) .map(|c: RoomCanonicalAliasEventContent| c.alias)
.map_err(|_| Error::bad_database("Invalid canonical alias event in database.")) .map_err(|_| {
Error::bad_database("Invalid canonical alias event in database.")
})
})?, })?,
name: services().rooms.state_accessor.get_name(&room_id)?, name: services().rooms.state_accessor.get_name(&room_id)?,
num_joined_members: services() num_joined_members: services()
@@ -228,7 +251,11 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.map(|c: RoomHistoryVisibilityEventContent| { .map(|c: RoomHistoryVisibilityEventContent| {
c.history_visibility == HistoryVisibility::WorldReadable c.history_visibility == HistoryVisibility::WorldReadable
}) })
.map_err(|_| Error::bad_database("Invalid room history visibility event in database.")) .map_err(|_| {
Error::bad_database(
"Invalid room history visibility event in database.",
)
})
})?, })?,
guest_can_join: services() guest_can_join: services()
.rooms .rooms
@@ -236,8 +263,12 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.room_state_get(&room_id, &StateEventType::RoomGuestAccess, "")? .room_state_get(&room_id, &StateEventType::RoomGuestAccess, "")?
.map_or(Ok(false), |s| { .map_or(Ok(false), |s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomGuestAccessEventContent| c.guest_access == GuestAccess::CanJoin) .map(|c: RoomGuestAccessEventContent| {
.map_err(|_| Error::bad_database("Invalid room guest access event in database.")) c.guest_access == GuestAccess::CanJoin
})
.map_err(|_| {
Error::bad_database("Invalid room guest access event in database.")
})
})?, })?,
avatar_url: services() avatar_url: services()
.rooms .rooms
@@ -246,7 +277,9 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.map(|s| { .map(|s| {
serde_json::from_str(s.content.get()) serde_json::from_str(s.content.get())
.map(|c: RoomAvatarEventContent| c.url) .map(|c: RoomAvatarEventContent| c.url)
.map_err(|_| Error::bad_database("Invalid room avatar event in database.")) .map_err(|_| {
Error::bad_database("Invalid room avatar event in database.")
})
}) })
.transpose()? .transpose()?
// url is now an Option<String> so we must flatten // url is now an Option<String> so we must flatten
@@ -275,10 +308,12 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.state_accessor .state_accessor
.room_state_get(&room_id, &StateEventType::RoomCreate, "")? .room_state_get(&room_id, &StateEventType::RoomCreate, "")?
.map(|s| { .map(|s| {
serde_json::from_str::<RoomCreateEventContent>(s.content.get()).map_err(|e| { serde_json::from_str::<RoomCreateEventContent>(s.content.get()).map_err(
|e| {
error!("Invalid room create event in database: {}", e); error!("Invalid room create event in database: {}", e);
Error::BadDatabase("Invalid room create event in database.") Error::BadDatabase("Invalid room create event in database.")
}) },
)
}) })
.transpose()? .transpose()?
.and_then(|e| e.room_type), .and_then(|e| e.room_type),
@@ -288,7 +323,11 @@ pub(crate) async fn get_public_rooms_filtered_helper(
}) })
.filter_map(|r: Result<_>| r.ok()) // Filter out buggy rooms .filter_map(|r: Result<_>| r.ok()) // Filter out buggy rooms
.filter(|chunk| { .filter(|chunk| {
if let Some(query) = filter.generic_search_term.as_ref().map(|q| q.to_lowercase()) { if let Some(query) = filter
.generic_search_term
.as_ref()
.map(|q| q.to_lowercase())
{
if let Some(name) = &chunk.name { if let Some(name) = &chunk.name {
if name.as_str().to_lowercase().contains(&query) { if name.as_str().to_lowercase().contains(&query) {
return true; return true;
@@ -320,7 +359,11 @@ pub(crate) async fn get_public_rooms_filtered_helper(
let total_room_count_estimate = (all_rooms.len() as u32).into(); let total_room_count_estimate = (all_rooms.len() as u32).into();
let chunk: Vec<_> = all_rooms.into_iter().skip(num_since as usize).take(limit as usize).collect(); let chunk: Vec<_> = all_rooms
.into_iter()
.skip(num_since as usize)
.take(limit as usize)
.collect();
let prev_batch = if num_since == 0 { let prev_batch = if num_since == 0 {
None None
+7 -4
View File
@@ -1,16 +1,17 @@
use crate::{services, Error, Result, Ruma};
use ruma::api::client::{ use ruma::api::client::{
error::ErrorKind, error::ErrorKind,
filter::{create_filter, get_filter}, filter::{create_filter, get_filter},
}; };
use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/r0/user/{userId}/filter/{filterId}` /// # `GET /_matrix/client/r0/user/{userId}/filter/{filterId}`
/// ///
/// Loads a filter that was previously created. /// Loads a filter that was previously created.
/// ///
/// - A user can only access their own filters /// - A user can only access their own filters
pub async fn get_filter_route(body: Ruma<get_filter::v3::Request>) -> Result<get_filter::v3::Response> { pub async fn get_filter_route(
body: Ruma<get_filter::v3::Request>,
) -> Result<get_filter::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let filter = match services().users.get_filter(sender_user, &body.filter_id)? { let filter = match services().users.get_filter(sender_user, &body.filter_id)? {
Some(filter) => filter, Some(filter) => filter,
@@ -23,7 +24,9 @@ pub async fn get_filter_route(body: Ruma<get_filter::v3::Request>) -> Result<get
/// # `PUT /_matrix/client/r0/user/{userId}/filter` /// # `PUT /_matrix/client/r0/user/{userId}/filter`
/// ///
/// Creates a new filter to be used by other endpoints. /// Creates a new filter to be used by other endpoints.
pub async fn create_filter_route(body: Ruma<create_filter::v3::Request>) -> Result<create_filter::v3::Response> { pub async fn create_filter_route(
body: Ruma<create_filter::v3::Request>,
) -> Result<create_filter::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
Ok(create_filter::v3::Response::new( Ok(create_filter::v3::Response::new(
services().users.create_filter(sender_user, &body.filter)?, services().users.create_filter(sender_user, &body.filter)?,
+156 -66
View File
@@ -1,14 +1,14 @@
use std::{ use super::SESSION_ID_LENGTH;
collections::{hash_map, BTreeMap, HashMap, HashSet}, use crate::{services, utils, Error, Result, Ruma};
time::{Duration, Instant},
};
use futures_util::{stream::FuturesUnordered, StreamExt}; use futures_util::{stream::FuturesUnordered, StreamExt};
use ruma::{ use ruma::{
api::{ api::{
client::{ client::{
error::ErrorKind, error::ErrorKind,
keys::{claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures, upload_signing_keys}, keys::{
claim_keys, get_key_changes, get_keys, upload_keys, upload_signatures,
upload_signing_keys,
},
uiaa::{AuthFlow, AuthType, UiaaInfo}, uiaa::{AuthFlow, AuthType, UiaaInfo},
}, },
federation, federation,
@@ -17,36 +17,48 @@ use ruma::{
DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId, DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
}; };
use serde_json::json; use serde_json::json;
use std::{
collections::{hash_map, BTreeMap, HashMap, HashSet},
time::{Duration, Instant},
};
use tracing::{debug, error}; use tracing::{debug, error};
use super::SESSION_ID_LENGTH;
use crate::{services, utils, Error, Result, Ruma};
/// # `POST /_matrix/client/r0/keys/upload` /// # `POST /_matrix/client/r0/keys/upload`
/// ///
/// Publish end-to-end encryption keys for the sender device. /// Publish end-to-end encryption keys for the sender device.
/// ///
/// - Adds one time keys /// - Adds one time keys
/// - If there are no device keys yet: Adds device keys (TODO: merge with /// - If there are no device keys yet: Adds device keys (TODO: merge with existing keys?)
/// existing keys?) pub async fn upload_keys_route(
pub async fn upload_keys_route(body: Ruma<upload_keys::v3::Request>) -> Result<upload_keys::v3::Response> { body: Ruma<upload_keys::v3::Request>,
) -> Result<upload_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated");
for (key_key, key_value) in &body.one_time_keys { for (key_key, key_value) in &body.one_time_keys {
services().users.add_one_time_key(sender_user, sender_device, key_key, key_value)?; services()
.users
.add_one_time_key(sender_user, sender_device, key_key, key_value)?;
} }
if let Some(device_keys) = &body.device_keys { if let Some(device_keys) = &body.device_keys {
// TODO: merge this and the existing event? // TODO: merge this and the existing event?
// This check is needed to assure that signatures are kept // This check is needed to assure that signatures are kept
if services().users.get_device_keys(sender_user, sender_device)?.is_none() { if services()
services().users.add_device_keys(sender_user, sender_device, device_keys)?; .users
.get_device_keys(sender_user, sender_device)?
.is_none()
{
services()
.users
.add_device_keys(sender_user, sender_device, device_keys)?;
} }
} }
Ok(upload_keys::v3::Response { Ok(upload_keys::v3::Response {
one_time_key_counts: services().users.count_one_time_keys(sender_user, sender_device)?, one_time_key_counts: services()
.users
.count_one_time_keys(sender_user, sender_device)?,
}) })
} }
@@ -56,8 +68,7 @@ pub async fn upload_keys_route(body: Ruma<upload_keys::v3::Request>) -> Result<u
/// ///
/// - Always fetches users from other servers over federation /// - Always fetches users from other servers over federation
/// - Gets master keys, self-signing keys, user signing keys and device keys. /// - Gets master keys, self-signing keys, user signing keys and device keys.
/// - The master and self-signing keys contain signatures that the user is /// - The master and self-signing keys contain signatures that the user is allowed to see
/// allowed to see
pub async fn get_keys_route(body: Ruma<get_keys::v3::Request>) -> Result<get_keys::v3::Response> { pub async fn get_keys_route(body: Ruma<get_keys::v3::Request>) -> Result<get_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@@ -75,7 +86,9 @@ pub async fn get_keys_route(body: Ruma<get_keys::v3::Request>) -> Result<get_key
/// # `POST /_matrix/client/r0/keys/claim` /// # `POST /_matrix/client/r0/keys/claim`
/// ///
/// Claims one-time keys /// Claims one-time keys
pub async fn claim_keys_route(body: Ruma<claim_keys::v3::Request>) -> Result<claim_keys::v3::Response> { pub async fn claim_keys_route(
body: Ruma<claim_keys::v3::Request>,
) -> Result<claim_keys::v3::Response> {
let response = claim_keys_helper(&body.one_time_keys).await?; let response = claim_keys_helper(&body.one_time_keys).await?;
Ok(response) Ok(response)
@@ -98,20 +111,25 @@ pub async fn upload_signing_keys_route(
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Box::default(), params: Default::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
if let Some(auth) = &body.auth { if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?; let (worked, uiaainfo) =
services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked { if !worked {
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} }
// Success! // Success!
} else if let Some(json) = body.json_body { } else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?; services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo)); return Err(Error::Uiaa(uiaainfo));
} else { } else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json.")); return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
@@ -145,11 +163,20 @@ pub async fn upload_signatures_route(
for signature in key for signature in key
.get("signatures") .get("signatures")
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Missing signatures field."))? .ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Missing signatures field.",
))?
.get(sender_user.to_string()) .get(sender_user.to_string())
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid user in signatures field."))? .ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid user in signatures field.",
))?
.as_object() .as_object()
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid signature."))? .ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid signature.",
))?
.clone() .clone()
.into_iter() .into_iter()
{ {
@@ -159,10 +186,15 @@ pub async fn upload_signatures_route(
signature signature
.1 .1
.as_str() .as_str()
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid signature value."))? .ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid signature value.",
))?
.to_owned(), .to_owned(),
); );
services().users.sign_key(user_id, key_id, signature, sender_user)?; services()
.users
.sign_key(user_id, key_id, signature, sender_user)?;
} }
} }
} }
@@ -174,11 +206,12 @@ pub async fn upload_signatures_route(
/// # `POST /_matrix/client/r0/keys/changes` /// # `POST /_matrix/client/r0/keys/changes`
/// ///
/// Gets a list of users who have updated their device identity keys since the /// Gets a list of users who have updated their device identity keys since the previous sync token.
/// previous sync token.
/// ///
/// - TODO: left users /// - TODO: left users
pub async fn get_key_changes_route(body: Ruma<get_key_changes::v3::Request>) -> Result<get_key_changes::v3::Response> { pub async fn get_key_changes_route(
body: Ruma<get_key_changes::v3::Request>,
) -> Result<get_key_changes::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mut device_list_updates = HashSet::new(); let mut device_list_updates = HashSet::new();
@@ -188,22 +221,37 @@ pub async fn get_key_changes_route(body: Ruma<get_key_changes::v3::Request>) ->
.users .users
.keys_changed( .keys_changed(
sender_user.as_str(), sender_user.as_str(),
body.from.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?, body.from
Some(body.to.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?), .parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?,
Some(
body.to
.parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?,
),
) )
.filter_map(std::result::Result::ok), .filter_map(|r| r.ok()),
); );
for room_id in services().rooms.state_cache.rooms_joined(sender_user).filter_map(std::result::Result::ok) { for room_id in services()
.rooms
.state_cache
.rooms_joined(sender_user)
.filter_map(|r| r.ok())
{
device_list_updates.extend( device_list_updates.extend(
services() services()
.users .users
.keys_changed( .keys_changed(
room_id.as_ref(), room_id.as_ref(),
body.from.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?, body.from.parse().map_err(|_| {
Some(body.to.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?), Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`.")
})?,
Some(body.to.parse().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`.")
})?),
) )
.filter_map(std::result::Result::ok), .filter_map(|r| r.ok()),
); );
} }
Ok(get_key_changes::v3::Response { Ok(get_key_changes::v3::Response {
@@ -213,7 +261,9 @@ pub async fn get_key_changes_route(body: Ruma<get_key_changes::v3::Request>) ->
} }
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>( pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
sender_user: Option<&UserId>, device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>, allowed_signatures: F, sender_user: Option<&UserId>,
device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
allowed_signatures: F,
include_display_names: bool, include_display_names: bool,
) -> Result<get_keys::v3::Response> { ) -> Result<get_keys::v3::Response> {
let mut master_keys = BTreeMap::new(); let mut master_keys = BTreeMap::new();
@@ -227,7 +277,10 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
let user_id: &UserId = user_id; let user_id: &UserId = user_id;
if user_id.server_name() != services().globals.server_name() { if user_id.server_name() != services().globals.server_name() {
get_over_federation.entry(user_id.server_name()).or_insert_with(Vec::new).push((user_id, device_ids)); get_over_federation
.entry(user_id.server_name())
.or_insert_with(Vec::new)
.push((user_id, device_ids));
continue; continue;
} }
@@ -239,7 +292,9 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
let metadata = services() let metadata = services()
.users .users
.get_device_metadata(user_id, &device_id)? .get_device_metadata(user_id, &device_id)?
.ok_or_else(|| Error::bad_database("all_device_keys contained nonexistent device."))?; .ok_or_else(|| {
Error::bad_database("all_device_keys contained nonexistent device.")
})?;
add_unsigned_device_display_name(&mut keys, metadata, include_display_names) add_unsigned_device_display_name(&mut keys, metadata, include_display_names)
.map_err(|_| Error::bad_database("invalid device keys in database"))?; .map_err(|_| Error::bad_database("invalid device keys in database"))?;
@@ -252,9 +307,13 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
for device_id in device_ids { for device_id in device_ids {
let mut container = BTreeMap::new(); let mut container = BTreeMap::new();
if let Some(mut keys) = services().users.get_device_keys(user_id, device_id)? { if let Some(mut keys) = services().users.get_device_keys(user_id, device_id)? {
let metadata = services().users.get_device_metadata(user_id, device_id)?.ok_or( let metadata = services()
Error::BadRequest(ErrorKind::InvalidParam, "Tried to get keys for nonexistent device."), .users
)?; .get_device_metadata(user_id, device_id)?
.ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Tried to get keys for nonexistent device.",
))?;
add_unsigned_device_display_name(&mut keys, metadata, include_display_names) add_unsigned_device_display_name(&mut keys, metadata, include_display_names)
.map_err(|_| Error::bad_database("invalid device keys in database"))?; .map_err(|_| Error::bad_database("invalid device keys in database"))?;
@@ -264,11 +323,17 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
} }
} }
if let Some(master_key) = services().users.get_master_key(sender_user, user_id, &allowed_signatures)? { if let Some(master_key) =
services()
.users
.get_master_key(sender_user, user_id, &allowed_signatures)?
{
master_keys.insert(user_id.to_owned(), master_key); master_keys.insert(user_id.to_owned(), master_key);
} }
if let Some(self_signing_key) = if let Some(self_signing_key) =
services().users.get_self_signing_key(sender_user, user_id, &allowed_signatures)? services()
.users
.get_self_signing_key(sender_user, user_id, &allowed_signatures)?
{ {
self_signing_keys.insert(user_id.to_owned(), self_signing_key); self_signing_keys.insert(user_id.to_owned(), self_signing_key);
} }
@@ -281,19 +346,29 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
let mut failures = BTreeMap::new(); let mut failures = BTreeMap::new();
let back_off = |id| async { let back_off = |id| match services()
match services().globals.bad_query_ratelimiter.write().await.entry(id) { .globals
.bad_query_ratelimiter
.write()
.unwrap()
.entry(id)
{
hash_map::Entry::Vacant(e) => { hash_map::Entry::Vacant(e) => {
e.insert((Instant::now(), 1)); e.insert((Instant::now(), 1));
},
hash_map::Entry::Occupied(mut e) => *e.get_mut() = (Instant::now(), e.get().1 + 1),
} }
hash_map::Entry::Occupied(mut e) => *e.get_mut() = (Instant::now(), e.get().1 + 1),
}; };
let mut futures: FuturesUnordered<_> = get_over_federation let mut futures: FuturesUnordered<_> = get_over_federation
.into_iter() .into_iter()
.map(|(server, vec)| async move { .map(|(server, vec)| async move {
if let Some((time, tries)) = services().globals.bad_query_ratelimiter.read().await.get(server) { if let Some((time, tries)) = services()
.globals
.bad_query_ratelimiter
.read()
.unwrap()
.get(server)
{
// Exponential backoff // Exponential backoff
let mut min_elapsed_duration = Duration::from_secs(5 * 60) * (*tries) * (*tries); let mut min_elapsed_duration = Duration::from_secs(5 * 60) * (*tries) * (*tries);
if min_elapsed_duration > Duration::from_secs(60 * 60 * 24) { if min_elapsed_duration > Duration::from_secs(60 * 60 * 24) {
@@ -302,7 +377,10 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
if time.elapsed() < min_elapsed_duration { if time.elapsed() < min_elapsed_duration {
debug!("Backing off query from {:?}", server); debug!("Backing off query from {:?}", server);
return (server, Err(Error::BadServerResponse("bad query, still backing off"))); return (
server,
Err(Error::BadServerResponse("bad query, still backing off")),
);
} }
} }
@@ -334,31 +412,35 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
match response { match response {
Ok(Ok(response)) => { Ok(Ok(response)) => {
for (user, masterkey) in response.master_keys { for (user, masterkey) in response.master_keys {
let (master_key_id, mut master_key) = services().users.parse_master_key(&user, &masterkey)?; let (master_key_id, mut master_key) =
services().users.parse_master_key(&user, &masterkey)?;
if let Some(our_master_key) = if let Some(our_master_key) = services().users.get_key(
services().users.get_key(&master_key_id, sender_user, &user, &allowed_signatures)? &master_key_id,
{ sender_user,
let (_, our_master_key) = services().users.parse_master_key(&user, &our_master_key)?; &user,
&allowed_signatures,
)? {
let (_, our_master_key) =
services().users.parse_master_key(&user, &our_master_key)?;
master_key.signatures.extend(our_master_key.signatures); master_key.signatures.extend(our_master_key.signatures);
} }
let json = serde_json::to_value(master_key).expect("to_value always works"); let json = serde_json::to_value(master_key).expect("to_value always works");
let raw = serde_json::from_value(json).expect("Raw::from_value always works"); let raw = serde_json::from_value(json).expect("Raw::from_value always works");
services().users.add_cross_signing_keys( services().users.add_cross_signing_keys(
&user, &raw, &None, &None, &user, &raw, &None, &None,
false, /* Dont notify. A notification would trigger another key request resulting in an false, // Dont notify. A notification would trigger another key request resulting in an endless loop
* endless loop */
)?; )?;
master_keys.insert(user, raw); master_keys.insert(user, raw);
} }
self_signing_keys.extend(response.self_signing_keys); self_signing_keys.extend(response.self_signing_keys);
device_keys.extend(response.device_keys); device_keys.extend(response.device_keys);
}, }
_ => { _ => {
back_off(server.to_owned()).await; back_off(server.to_owned());
failures.insert(server.to_string(), json!({})); failures.insert(server.to_string(), json!({}));
}, }
} }
} }
@@ -372,7 +454,8 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
} }
fn add_unsigned_device_display_name( fn add_unsigned_device_display_name(
keys: &mut Raw<ruma::encryption::DeviceKeys>, metadata: ruma::api::client::device::Device, keys: &mut Raw<ruma::encryption::DeviceKeys>,
metadata: ruma::api::client::device::Device,
include_display_names: bool, include_display_names: bool,
) -> serde_json::Result<()> { ) -> serde_json::Result<()> {
if let Some(display_name) = metadata.display_name { if let Some(display_name) = metadata.display_name {
@@ -405,12 +488,19 @@ pub(crate) async fn claim_keys_helper(
for (user_id, map) in one_time_keys_input { for (user_id, map) in one_time_keys_input {
if user_id.server_name() != services().globals.server_name() { if user_id.server_name() != services().globals.server_name() {
get_over_federation.entry(user_id.server_name()).or_insert_with(Vec::new).push((user_id, map)); get_over_federation
.entry(user_id.server_name())
.or_insert_with(Vec::new)
.push((user_id, map));
} }
let mut container = BTreeMap::new(); let mut container = BTreeMap::new();
for (device_id, key_algorithm) in map { for (device_id, key_algorithm) in map {
if let Some(one_time_keys) = services().users.take_one_time_key(user_id, device_id, key_algorithm)? { if let Some(one_time_keys) =
services()
.users
.take_one_time_key(user_id, device_id, key_algorithm)?
{
let mut c = BTreeMap::new(); let mut c = BTreeMap::new();
c.insert(one_time_keys.0, one_time_keys.1); c.insert(one_time_keys.0, one_time_keys.1);
container.insert(device_id.clone(), c); container.insert(device_id.clone(), c);
@@ -447,10 +537,10 @@ pub(crate) async fn claim_keys_helper(
match response { match response {
Ok(keys) => { Ok(keys) => {
one_time_keys.extend(keys.one_time_keys); one_time_keys.extend(keys.one_time_keys);
}, }
Err(_e) => { Err(_e) => {
failures.insert(server.to_string(), json!({})); failures.insert(server.to_string(), json!({}));
}, }
} }
} }
+145 -369
View File
@@ -1,22 +1,22 @@
use std::{io::Cursor, net::IpAddr, sync::Arc, time::Duration}; use std::{io::Cursor, net::IpAddr, sync::Arc, time::Duration};
use crate::{
service::media::{FileMeta, UrlPreviewData},
services, utils, Error, Result, Ruma,
};
use image::io::Reader as ImgReader; use image::io::Reader as ImgReader;
use reqwest::Url; use reqwest::Url;
use ruma::api::client::{ use ruma::api::client::{
error::ErrorKind, error::ErrorKind,
media::{ media::{
create_content, get_content, get_content_as_filename, get_content_thumbnail, get_media_config, create_content, get_content, get_content_as_filename, get_content_thumbnail,
get_media_preview, get_media_config, get_media_preview,
}, },
}; };
use tracing::{debug, error, info, warn}; use tracing::{debug, error, info, warn};
use webpage::HTML; use webpage::HTML;
use crate::{
service::media::{FileMeta, UrlPreviewData},
services, utils, Error, Result, Ruma, RumaResponse,
};
/// generated MXC ID (`media-id`) length /// generated MXC ID (`media-id`) length
const MXC_LENGTH: usize = 32; const MXC_LENGTH: usize = 32;
@@ -31,22 +31,6 @@ pub async fn get_media_config_route(
}) })
} }
/// # `GET /_matrix/media/v1/config`
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// Returns max upload size.
pub async fn get_media_config_v1_route(
_body: Ruma<get_media_config::v3::Request>,
) -> Result<RumaResponse<get_media_config::v3::Response>> {
Ok(get_media_config::v3::Response {
upload_size: services().globals.max_request_size().into(),
}
.into())
}
/// # `GET /_matrix/media/v3/preview_url` /// # `GET /_matrix/media/v3/preview_url`
/// ///
/// Returns URL preview. /// Returns URL preview.
@@ -55,80 +39,33 @@ pub async fn get_media_preview_route(
) -> Result<get_media_preview::v3::Response> { ) -> Result<get_media_preview::v3::Response> {
let url = &body.url; let url = &body.url;
if !url_preview_allowed(url) { if !url_preview_allowed(url) {
return Err(Error::BadRequest(ErrorKind::Forbidden, "URL is not allowed to be previewed")); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"URL is not allowed to be previewed",
));
} }
match get_url_preview(url).await { if let Ok(preview) = get_url_preview(url).await {
Ok(preview) => {
let res = serde_json::value::to_raw_value(&preview).map_err(|e| { let res = serde_json::value::to_raw_value(&preview).map_err(|e| {
error!("Failed to convert UrlPreviewData into a serde json value: {}", e); error!(
"Failed to convert UrlPreviewData into a serde json value: {}",
e
);
Error::BadRequest( Error::BadRequest(
ErrorKind::LimitExceeded { ErrorKind::Unknown,
retry_after_ms: Some(Duration::from_secs(5)), "Unknown error occurred parsing URL preview",
},
"Failed to generate a URL preview, try again later.",
) )
})?; })?;
Ok(get_media_preview::v3::Response::from_raw_value(res)) return Ok(get_media_preview::v3::Response::from_raw_value(res));
}, }
Err(e) => {
warn!("Failed to generate a URL preview: {e}");
// there doesn't seem to be an agreed-upon error code in the spec.
// the only response codes in the preview_url spec page are 200 and 429.
Err(Error::BadRequest( Err(Error::BadRequest(
ErrorKind::LimitExceeded { ErrorKind::LimitExceeded {
retry_after_ms: Some(Duration::from_secs(5)), retry_after_ms: Some(Duration::from_secs(5)),
}, },
"Failed to generate a URL preview, try again later.", "Retry later",
)) ))
},
}
}
/// # `GET /_matrix/media/v1/preview_url`
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// Returns URL preview.
pub async fn get_media_preview_v1_route(
body: Ruma<get_media_preview::v3::Request>,
) -> Result<RumaResponse<get_media_preview::v3::Response>> {
let url = &body.url;
if !url_preview_allowed(url) {
return Err(Error::BadRequest(ErrorKind::Forbidden, "URL is not allowed to be previewed"));
}
match get_url_preview(url).await {
Ok(preview) => {
let res = serde_json::value::to_raw_value(&preview).map_err(|e| {
error!("Failed to convert UrlPreviewData into a serde json value: {}", e);
Error::BadRequest(
ErrorKind::LimitExceeded {
retry_after_ms: Some(Duration::from_secs(5)),
},
"Failed to generate a URL preview, try again later.",
)
})?;
Ok(get_media_preview::v3::Response::from_raw_value(res).into())
},
Err(e) => {
warn!("Failed to generate a URL preview: {e}");
// there doesn't seem to be an agreed-upon error code in the spec.
// the only response codes in the preview_url spec page are 200 and 429.
Err(Error::BadRequest(
ErrorKind::LimitExceeded {
retry_after_ms: Some(Duration::from_secs(5)),
},
"Failed to generate a URL preview, try again later.",
))
},
}
} }
/// # `POST /_matrix/media/v3/upload` /// # `POST /_matrix/media/v3/upload`
@@ -137,9 +74,9 @@ pub async fn get_media_preview_v1_route(
/// ///
/// - Some metadata will be saved in the database /// - Some metadata will be saved in the database
/// - Media will be saved in the media/ directory /// - Media will be saved in the media/ directory
pub async fn create_content_route(body: Ruma<create_content::v3::Request>) -> Result<create_content::v3::Response> { pub async fn create_content_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); body: Ruma<create_content::v3::Request>,
) -> Result<create_content::v3::Response> {
let mxc = format!( let mxc = format!(
"mxc://{}/{}", "mxc://{}/{}",
services().globals.server_name(), services().globals.server_name(),
@@ -149,9 +86,11 @@ pub async fn create_content_route(body: Ruma<create_content::v3::Request>) -> Re
services() services()
.media .media
.create( .create(
Some(sender_user.clone()),
mxc.clone(), mxc.clone(),
body.filename.as_ref().map(|filename| "inline; filename=".to_owned() + filename).as_deref(), body.filename
.as_ref()
.map(|filename| "inline; filename=".to_owned() + filename)
.as_deref(),
body.content_type.as_deref(), body.content_type.as_deref(),
&body.file, &body.file,
) )
@@ -165,58 +104,22 @@ pub async fn create_content_route(body: Ruma<create_content::v3::Request>) -> Re
}) })
} }
/// # `POST /_matrix/media/v1/upload`
///
/// Permanently save media in the server.
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// - Some metadata will be saved in the database
/// - Media will be saved in the media/ directory
pub async fn create_content_v1_route(
body: Ruma<create_content::v3::Request>,
) -> Result<RumaResponse<create_content::v3::Response>> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mxc = format!(
"mxc://{}/{}",
services().globals.server_name(),
utils::random_string(MXC_LENGTH)
);
services()
.media
.create(
Some(sender_user.clone()),
mxc.clone(),
body.filename.as_ref().map(|filename| "inline; filename=".to_owned() + filename).as_deref(),
body.content_type.as_deref(),
&body.file,
)
.await?;
let content_uri = mxc.into();
Ok(create_content::v3::Response {
content_uri,
blurhash: None,
}
.into())
}
/// helper method to fetch remote media from other servers over federation /// helper method to fetch remote media from other servers over federation
pub async fn get_remote_content( pub async fn get_remote_content(
mxc: &str, server_name: &ruma::ServerName, media_id: String, allow_redirect: bool, timeout_ms: Duration, mxc: &str,
server_name: &ruma::ServerName,
media_id: String,
allow_redirect: bool,
timeout_ms: Duration,
) -> Result<get_content::v3::Response, Error> { ) -> Result<get_content::v3::Response, Error> {
// we'll lie to the client and say the blocked server's media was not found and // we'll lie to the client and say the blocked server's media was not found and log.
// log. the client has no way of telling anyways so this is a security bonus. // the client has no way of telling anyways so this is a security bonus.
if services().globals.prevent_media_downloads_from().contains(&server_name.to_owned()) { if services()
info!( .globals
"Received request for remote media `{}` but server is in our media server blocklist. Returning 404.", .prevent_media_downloads_from()
mxc .contains(&server_name.to_owned())
); {
info!("Received request for remote media `{}` but server is in our media server blocklist. Returning 404.", mxc);
return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found.")); return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."));
} }
@@ -237,7 +140,6 @@ pub async fn get_remote_content(
services() services()
.media .media
.create( .create(
None,
mxc.to_owned(), mxc.to_owned(),
content_response.content_disposition.as_deref(), content_response.content_disposition.as_deref(),
content_response.content_type.as_deref(), content_response.content_type.as_deref(),
@@ -254,9 +156,10 @@ pub async fn get_remote_content(
/// ///
/// - Only allows federation if `allow_remote` is true /// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true /// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20 /// - Uses client-provided `timeout_ms` if available, else defaults to 20 seconds
/// seconds pub async fn get_content_route(
pub async fn get_content_route(body: Ruma<get_content::v3::Request>) -> Result<get_content::v3::Response> { body: Ruma<get_content::v3::Request>,
) -> Result<get_content::v3::Response> {
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
if let Some(FileMeta { if let Some(FileMeta {
@@ -286,68 +189,20 @@ pub async fn get_content_route(body: Ruma<get_content::v3::Request>) -> Result<g
} }
} }
/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}`
///
/// Load media from our server or over federation.
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
/// seconds
pub async fn get_content_v1_route(
body: Ruma<get_content::v3::Request>,
) -> Result<RumaResponse<get_content::v3::Response>> {
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
if let Some(FileMeta {
content_disposition,
content_type,
file,
}) = services().media.get(mxc.clone()).await?
{
Ok(get_content::v3::Response {
file,
content_type,
content_disposition,
cross_origin_resource_policy: Some("cross-origin".to_owned()),
}
.into())
} else if &*body.server_name != services().globals.server_name() && body.allow_remote {
let remote_content_response = get_remote_content(
&mxc,
&body.server_name,
body.media_id.clone(),
body.allow_redirect,
body.timeout_ms,
)
.await?;
Ok(remote_content_response.into())
} else {
Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
}
}
/// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}/{fileName}` /// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}/{fileName}`
/// ///
/// Load media from our server or over federation, permitting desired filename. /// Load media from our server or over federation, permitting desired filename.
/// ///
/// - Only allows federation if `allow_remote` is true /// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true /// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20 /// - Uses client-provided `timeout_ms` if available, else defaults to 20 seconds
/// seconds
pub async fn get_content_as_filename_route( pub async fn get_content_as_filename_route(
body: Ruma<get_content_as_filename::v3::Request>, body: Ruma<get_content_as_filename::v3::Request>,
) -> Result<get_content_as_filename::v3::Response> { ) -> Result<get_content_as_filename::v3::Response> {
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
if let Some(FileMeta { if let Some(FileMeta {
content_type, content_type, file, ..
file,
..
}) = services().media.get(mxc.clone()).await? }) = services().media.get(mxc.clone()).await?
{ {
Ok(get_content_as_filename::v3::Response { Ok(get_content_as_filename::v3::Response {
@@ -377,81 +232,30 @@ pub async fn get_content_as_filename_route(
} }
} }
/// # `GET /_matrix/media/v1/download/{serverName}/{mediaId}/{fileName}`
///
/// Load media from our server or over federation, permitting desired filename.
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
/// seconds
pub async fn get_content_as_filename_v1_route(
body: Ruma<get_content_as_filename::v3::Request>,
) -> Result<RumaResponse<get_content_as_filename::v3::Response>> {
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
if let Some(FileMeta {
content_type,
file,
..
}) = services().media.get(mxc.clone()).await?
{
Ok(get_content_as_filename::v3::Response {
file,
content_type,
content_disposition: Some(format!("inline; filename={}", body.filename)),
cross_origin_resource_policy: Some("cross-origin".to_owned()),
}
.into())
} else if &*body.server_name != services().globals.server_name() && body.allow_remote {
let remote_content_response = get_remote_content(
&mxc,
&body.server_name,
body.media_id.clone(),
body.allow_redirect,
body.timeout_ms,
)
.await?;
Ok(get_content_as_filename::v3::Response {
content_disposition: Some(format!("inline: filename={}", body.filename)),
content_type: remote_content_response.content_type,
file: remote_content_response.file,
cross_origin_resource_policy: Some("cross-origin".to_owned()),
}
.into())
} else {
Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
}
}
/// # `GET /_matrix/media/v3/thumbnail/{serverName}/{mediaId}` /// # `GET /_matrix/media/v3/thumbnail/{serverName}/{mediaId}`
/// ///
/// Load media thumbnail from our server or over federation. /// Load media thumbnail from our server or over federation.
/// ///
/// - Only allows federation if `allow_remote` is true /// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true /// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20 /// - Uses client-provided `timeout_ms` if available, else defaults to 20 seconds
/// seconds
pub async fn get_content_thumbnail_route( pub async fn get_content_thumbnail_route(
body: Ruma<get_content_thumbnail::v3::Request>, body: Ruma<get_content_thumbnail::v3::Request>,
) -> Result<get_content_thumbnail::v3::Response> { ) -> Result<get_content_thumbnail::v3::Response> {
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
if let Some(FileMeta { if let Some(FileMeta {
content_type, content_type, file, ..
file,
..
}) = services() }) = services()
.media .media
.get_thumbnail( .get_thumbnail(
mxc.clone(), mxc.clone(),
body.width.try_into().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?, body.width
body.height.try_into().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Height is invalid."))?, .try_into()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?,
body.height
.try_into()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Height is invalid."))?,
) )
.await? .await?
{ {
@@ -461,13 +265,14 @@ pub async fn get_content_thumbnail_route(
cross_origin_resource_policy: Some("cross-origin".to_owned()), cross_origin_resource_policy: Some("cross-origin".to_owned()),
}) })
} else if &*body.server_name != services().globals.server_name() && body.allow_remote { } else if &*body.server_name != services().globals.server_name() && body.allow_remote {
// we'll lie to the client and say the blocked server's media was not found and // we'll lie to the client and say the blocked server's media was not found and log.
// log. the client has no way of telling anyways so this is a security bonus. // the client has no way of telling anyways so this is a security bonus.
if services().globals.prevent_media_downloads_from().contains(&body.server_name.clone()) { if services()
info!( .globals
"Received request for remote media `{}` but server is in our media server blocklist. Returning 404.", .prevent_media_downloads_from()
mxc .contains(&body.server_name.to_owned())
); {
info!("Received request for remote media `{}` but server is in our media server blocklist. Returning 404.", mxc);
return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found.")); return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."));
} }
@@ -491,7 +296,6 @@ pub async fn get_content_thumbnail_route(
services() services()
.media .media
.upload_thumbnail( .upload_thumbnail(
None,
mxc, mxc,
None, None,
get_thumbnail_response.content_type.as_deref(), get_thumbnail_response.content_type.as_deref(),
@@ -507,89 +311,6 @@ pub async fn get_content_thumbnail_route(
} }
} }
/// # `GET /_matrix/media/v1/thumbnail/{serverName}/{mediaId}`
///
/// Load media thumbnail from our server or over federation.
///
/// This is a legacy endpoint ("/v1/") that some very old homeservers and/or
/// clients may call. conduwuit adds these for compatibility purposes.
/// See <https://spec.matrix.org/legacy/legacy/#id27>
///
/// - Only allows federation if `allow_remote` is true
/// - Only redirects if `allow_redirect` is true
/// - Uses client-provided `timeout_ms` if available, else defaults to 20
/// seconds
pub async fn get_content_thumbnail_v1_route(
body: Ruma<get_content_thumbnail::v3::Request>,
) -> Result<RumaResponse<get_content_thumbnail::v3::Response>> {
let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
if let Some(FileMeta {
content_type,
file,
..
}) = services()
.media
.get_thumbnail(
mxc.clone(),
body.width.try_into().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?,
body.height.try_into().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Height is invalid."))?,
)
.await?
{
Ok(get_content_thumbnail::v3::Response {
file,
content_type,
cross_origin_resource_policy: Some("cross-origin".to_owned()),
}
.into())
} else if &*body.server_name != services().globals.server_name() && body.allow_remote {
// we'll lie to the client and say the blocked server's media was not found and
// log. the client has no way of telling anyways so this is a security bonus.
if services().globals.prevent_media_downloads_from().contains(&body.server_name.clone()) {
info!(
"Received request for remote media `{}` but server is in our media server blocklist. Returning 404.",
mxc
);
return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."));
}
let get_thumbnail_response = services()
.sending
.send_federation_request(
&body.server_name,
get_content_thumbnail::v3::Request {
allow_remote: body.allow_remote,
height: body.height,
width: body.width,
method: body.method.clone(),
server_name: body.server_name.clone(),
media_id: body.media_id.clone(),
timeout_ms: body.timeout_ms,
allow_redirect: body.allow_redirect,
},
)
.await?;
services()
.media
.upload_thumbnail(
None,
mxc,
None,
get_thumbnail_response.content_type.as_deref(),
body.width.try_into().expect("all UInts are valid u32s"),
body.height.try_into().expect("all UInts are valid u32s"),
&get_thumbnail_response.file,
)
.await?;
Ok(get_thumbnail_response.into())
} else {
Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
}
}
async fn download_image(client: &reqwest::Client, url: &str) -> Result<UrlPreviewData> { async fn download_image(client: &reqwest::Client, url: &str) -> Result<UrlPreviewData> {
let image = client.get(url).send().await?.bytes().await?; let image = client.get(url).send().await?.bytes().await?;
let mxc = format!( let mxc = format!(
@@ -598,7 +319,10 @@ async fn download_image(client: &reqwest::Client, url: &str) -> Result<UrlPrevie
utils::random_string(MXC_LENGTH) utils::random_string(MXC_LENGTH)
); );
services().media.create(None, mxc.clone(), None, None, &image).await?; services()
.media
.create(mxc.clone(), None, None, &image)
.await?;
let (width, height) = match ImgReader::new(Cursor::new(&image)).with_guessed_format() { let (width, height) = match ImgReader::new(Cursor::new(&image)).with_guessed_format() {
Err(_) => (None, None), Err(_) => (None, None),
@@ -624,19 +348,19 @@ async fn download_html(client: &reqwest::Client, url: &str) -> Result<UrlPreview
while let Some(chunk) = response.chunk().await? { while let Some(chunk) = response.chunk().await? {
bytes.extend_from_slice(&chunk); bytes.extend_from_slice(&chunk);
if bytes.len() > services().globals.url_preview_max_spider_size() { if bytes.len() > services().globals.url_preview_max_spider_size() {
debug!( debug!("Response body from URL {} exceeds url_preview_max_spider_size ({}), not processing the rest of the response body and assuming our necessary data is in this range.", url, services().globals.url_preview_max_spider_size());
"Response body from URL {} exceeds url_preview_max_spider_size ({}), not processing the rest of the \
response body and assuming our necessary data is in this range.",
url,
services().globals.url_preview_max_spider_size()
);
break; break;
} }
} }
let body = String::from_utf8_lossy(&bytes); let body = String::from_utf8_lossy(&bytes);
let html = match HTML::from_string(body.to_string(), Some(url.to_owned())) { let html = match HTML::from_string(body.to_string(), Some(url.to_owned())) {
Ok(html) => html, Ok(html) => html,
Err(_) => return Err(Error::BadRequest(ErrorKind::Unknown, "Failed to parse HTML")), Err(_) => {
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Failed to parse HTML",
))
}
}; };
let mut data = match html.opengraph.images.first() { let mut data = match html.opengraph.images.first() {
@@ -675,7 +399,7 @@ fn url_request_allowed(addr: &IpAddr) -> bool {
|| (ip4.octets()[0] == 198 && (ip4.octets()[1] & 0xfe) == 18) // is_benchmarking() || (ip4.octets()[0] == 198 && (ip4.octets()[1] & 0xfe) == 18) // is_benchmarking()
|| (ip4.octets()[0] & 240 == 240 && !ip4.is_broadcast()) // is_reserved() || (ip4.octets()[0] & 240 == 240 && !ip4.is_broadcast()) // is_reserved()
|| ip4.is_broadcast()) || ip4.is_broadcast())
}, }
IpAddr::V6(ip6) => { IpAddr::V6(ip6) => {
!(ip6.is_unspecified() !(ip6.is_unspecified()
|| ip6.is_loopback() || ip6.is_loopback()
@@ -702,7 +426,7 @@ fn url_request_allowed(addr: &IpAddr) -> bool {
|| ((ip6.segments()[0] == 0x2001) && (ip6.segments()[1] == 0xdb8)) // is_documentation() || ((ip6.segments()[0] == 0x2001) && (ip6.segments()[1] == 0xdb8)) // is_documentation()
|| ((ip6.segments()[0] & 0xfe00) == 0xfc00) // is_unique_local() || ((ip6.segments()[0] & 0xfe00) == 0xfc00) // is_unique_local()
|| ((ip6.segments()[0] & 0xffc0) == 0xfe80)) // is_unicast_link_local || ((ip6.segments()[0] & 0xffc0) == 0xfe80)) // is_unicast_link_local
}, }
} }
} }
@@ -710,21 +434,38 @@ async fn request_url_preview(url: &str) -> Result<UrlPreviewData> {
let client = services().globals.url_preview_client(); let client = services().globals.url_preview_client();
let response = client.head(url).send().await?; let response = client.head(url).send().await?;
if !response.remote_addr().map_or(false, |a| url_request_allowed(&a.ip())) { if !response
.remote_addr()
.map_or(false, |a| url_request_allowed(&a.ip()))
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"Requesting from this address is forbidden", "Requesting from this address is forbidden",
)); ));
} }
let content_type = match response.headers().get(reqwest::header::CONTENT_TYPE).and_then(|x| x.to_str().ok()) { let content_type = match response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|x| x.to_str().ok())
{
Some(ct) => ct, Some(ct) => ct,
None => return Err(Error::BadRequest(ErrorKind::Unknown, "Unknown Content-Type")), None => {
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Unknown Content-Type",
))
}
}; };
let data = match content_type { let data = match content_type {
html if html.starts_with("text/html") => download_html(&client, url).await?, html if html.starts_with("text/html") => download_html(&client, url).await?,
img if img.starts_with("image/") => download_image(&client, url).await?, img if img.starts_with("image/") => download_image(&client, url).await?,
_ => return Err(Error::BadRequest(ErrorKind::Unknown, "Unsupported Content-Type")), _ => {
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Unsupported Content-Type",
))
}
}; };
services().media.set_url_preview(url, &data).await?; services().media.set_url_preview(url, &data).await?;
@@ -738,7 +479,15 @@ async fn get_url_preview(url: &str) -> Result<UrlPreviewData> {
} }
// ensure that only one request is made per URL // ensure that only one request is made per URL
let mutex_request = Arc::clone(services().media.url_preview_mutex.write().await.entry(url.to_owned()).or_default()); let mutex_request = Arc::clone(
services()
.media
.url_preview_mutex
.write()
.unwrap()
.entry(url.to_owned())
.or_default(),
);
let _request_lock = mutex_request.lock().await; let _request_lock = mutex_request.lock().await;
match services().media.get_url_preview(url).await { match services().media.get_url_preview(url).await {
@@ -753,19 +502,25 @@ fn url_preview_allowed(url_str: &str) -> bool {
Err(e) => { Err(e) => {
warn!("Failed to parse URL from a str: {}", e); warn!("Failed to parse URL from a str: {}", e);
return false; return false;
}, }
}; };
if ["http", "https"].iter().all(|&scheme| scheme != url.scheme().to_lowercase()) { if ["http", "https"]
.iter()
.all(|&scheme| scheme != url.scheme().to_lowercase())
{
debug!("Ignoring non-HTTP/HTTPS URL to preview: {}", url); debug!("Ignoring non-HTTP/HTTPS URL to preview: {}", url);
return false; return false;
} }
let host = match url.host_str() { let host = match url.host_str() {
None => { None => {
debug!("Ignoring URL preview for a URL that does not have a host (?): {}", url); debug!(
"Ignoring URL preview for a URL that does not have a host (?): {}",
url
);
return false; return false;
}, }
Some(h) => h.to_owned(), Some(h) => h.to_owned(),
}; };
@@ -777,23 +532,41 @@ fn url_preview_allowed(url_str: &str) -> bool {
|| allowlist_domain_explicit.contains(&"*".to_owned()) || allowlist_domain_explicit.contains(&"*".to_owned())
|| allowlist_url_contains.contains(&"*".to_owned()) || allowlist_url_contains.contains(&"*".to_owned())
{ {
debug!("Config key contains * which is allowing all URL previews. Allowing URL {}", url); debug!(
"Config key contains * which is allowing all URL previews. Allowing URL {}",
url
);
return true; return true;
} }
if !host.is_empty() { if !host.is_empty() {
if allowlist_domain_explicit.contains(&host) { if allowlist_domain_explicit.contains(&host) {
debug!("Host {} is allowed by url_preview_domain_explicit_allowlist (check 1/3)", &host); debug!(
"Host {} is allowed by url_preview_domain_explicit_allowlist (check 1/3)",
&host
);
return true; return true;
} }
if allowlist_domain_contains.iter().any(|domain_s| domain_s.contains(&host.clone())) { if allowlist_domain_contains
debug!("Host {} is allowed by url_preview_domain_contains_allowlist (check 2/3)", &host); .iter()
.any(|domain_s| domain_s.contains(&host.clone()))
{
debug!(
"Host {} is allowed by url_preview_domain_contains_allowlist (check 2/3)",
&host
);
return true; return true;
} }
if allowlist_url_contains.iter().any(|url_s| url.to_string().contains(&url_s.to_string())) { if allowlist_url_contains
debug!("URL {} is allowed by url_preview_url_contains_allowlist (check 3/3)", &host); .iter()
.any(|url_s| url.to_string().contains(&url_s.to_string()))
{
debug!(
"URL {} is allowed by url_preview_url_contains_allowlist (check 3/3)",
&host
);
return true; return true;
} }
@@ -811,14 +584,17 @@ fn url_preview_allowed(url_str: &str) -> bool {
return true; return true;
} }
if allowlist_domain_contains.iter().any(|domain_s| domain_s.contains(&root_domain.to_owned())) { if allowlist_domain_contains
.iter()
.any(|domain_s| domain_s.contains(&root_domain.to_owned()))
{
debug!( debug!(
"Root domain {} is allowed by url_preview_domain_contains_allowlist (check 2/3)", "Root domain {} is allowed by url_preview_domain_contains_allowlist (check 2/3)",
&root_domain &root_domain
); );
return true; return true;
} }
}, }
} }
} }
} }
File diff suppressed because it is too large Load Diff
+72 -40
View File
@@ -1,8 +1,7 @@
use std::{ use crate::{
collections::{BTreeMap, HashSet}, service::{pdu::PduBuilder, rooms::timeline::PduCount},
sync::Arc, services, utils, Error, Result, Ruma,
}; };
use ruma::{ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
@@ -11,40 +10,47 @@ use ruma::{
events::{StateEventType, TimelineEventType}, events::{StateEventType, TimelineEventType},
}; };
use serde_json::from_str; use serde_json::from_str;
use std::{
use crate::{ collections::{BTreeMap, HashSet},
service::{pdu::PduBuilder, rooms::timeline::PduCount}, sync::Arc,
services, utils, Error, Result, Ruma,
}; };
/// # `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}` /// # `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}`
/// ///
/// Send a message event into the room. /// Send a message event into the room.
/// ///
/// - Is a NOOP if the txn id was already used before and returns the same event /// - Is a NOOP if the txn id was already used before and returns the same event id again
/// id again
/// - The only requirement for the content is that it has to be valid json /// - The only requirement for the content is that it has to be valid json
/// - Tries to send the event into the room, auth rules will determine if it is /// - Tries to send the event into the room, auth rules will determine if it is allowed
/// allowed
pub async fn send_message_event_route( pub async fn send_message_event_route(
body: Ruma<send_message_event::v3::Request>, body: Ruma<send_message_event::v3::Request>,
) -> Result<send_message_event::v3::Response> { ) -> Result<send_message_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_deref(); let sender_device = body.sender_device.as_deref();
let mutex_state = let mutex_state = Arc::clone(
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(body.room_id.clone()).or_default()); services()
.globals
.roomid_mutex_state
.write()
.unwrap()
.entry(body.room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
// Forbid m.room.encrypted if encryption is disabled // Forbid m.room.encrypted if encryption is disabled
if TimelineEventType::RoomEncrypted == body.event_type.to_string().into() && !services().globals.allow_encryption() if TimelineEventType::RoomEncrypted == body.event_type.to_string().into()
&& !services().globals.allow_encryption()
{ {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Encryption has been disabled")); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Encryption has been disabled",
));
} }
// certain event types require certain fields to be valid in request bodies. // certain event types require certain fields to be valid in request bodies.
// this helps prevent attempting to handle events that we can't deserialise // this helps prevent attempting to handle events that we can't deserialise later so don't waste resources on it.
// later so don't waste resources on it.
// //
// see https://spec.matrix.org/v1.9/client-server-api/#events-2 for what's required per event type. // see https://spec.matrix.org/v1.9/client-server-api/#events-2 for what's required per event type.
match body.event_type.to_string().into() { match body.event_type.to_string().into() {
@@ -65,7 +71,7 @@ pub async fn send_message_event_route(
"'msgtype' field in JSON request is invalid", "'msgtype' field in JSON request is invalid",
)); ));
} }
}, }
TimelineEventType::RoomName => { TimelineEventType::RoomName => {
let name_field = body.body.body.get_field::<String>("name"); let name_field = body.body.body.get_field::<String>("name");
@@ -75,7 +81,7 @@ pub async fn send_message_event_route(
"'name' field in JSON request is invalid", "'name' field in JSON request is invalid",
)); ));
} }
}, }
TimelineEventType::RoomTopic => { TimelineEventType::RoomTopic => {
let topic_field = body.body.body.get_field::<String>("topic"); let topic_field = body.body.body.get_field::<String>("topic");
@@ -85,12 +91,16 @@ pub async fn send_message_event_route(
"'topic' field in JSON request is invalid", "'topic' field in JSON request is invalid",
)); ));
} }
}, }
_ => {}, // event may be custom/experimental or can be empty don't do anything with it _ => {} // event may be custom/experimental or can be empty don't do anything with it
}; };
// Check if this is a new transaction id // Check if this is a new transaction id
if let Some(response) = services().transaction_ids.existing_txnid(sender_user, sender_device, &body.txn_id)? { if let Some(response) =
services()
.transaction_ids
.existing_txnid(sender_user, sender_device, &body.txn_id)?
{
// The client might have sent a txnid of the /sendToDevice endpoint // The client might have sent a txnid of the /sendToDevice endpoint
// This txnid has no response associated with it // This txnid has no response associated with it
if response.is_empty() { if response.is_empty() {
@@ -104,9 +114,7 @@ pub async fn send_message_event_route(
.map_err(|_| Error::bad_database("Invalid txnid bytes in database."))? .map_err(|_| Error::bad_database("Invalid txnid bytes in database."))?
.try_into() .try_into()
.map_err(|_| Error::bad_database("Invalid event id in txnid data."))?; .map_err(|_| Error::bad_database("Invalid event id in txnid data."))?;
return Ok(send_message_event::v3::Response { return Ok(send_message_event::v3::Response { event_id });
event_id,
});
} }
let mut unsigned = BTreeMap::new(); let mut unsigned = BTreeMap::new();
@@ -130,19 +138,25 @@ pub async fn send_message_event_route(
) )
.await?; .await?;
services().transaction_ids.add_txnid(sender_user, sender_device, &body.txn_id, event_id.as_bytes())?; services().transaction_ids.add_txnid(
sender_user,
sender_device,
&body.txn_id,
event_id.as_bytes(),
)?;
drop(state_lock); drop(state_lock);
Ok(send_message_event::v3::Response::new((*event_id).to_owned())) Ok(send_message_event::v3::Response::new(
(*event_id).to_owned(),
))
} }
/// # `GET /_matrix/client/r0/rooms/{roomId}/messages` /// # `GET /_matrix/client/r0/rooms/{roomId}/messages`
/// ///
/// Allows paginating through room history. /// Allows paginating through room history.
/// ///
/// - Only works if the user is joined (TODO: always allow, but only show events /// - Only works if the user is joined (TODO: always allow, but only show events where the user was
/// where the user was
/// joined, depending on history_visibility) /// joined, depending on history_visibility)
pub async fn get_message_events_route( pub async fn get_message_events_route(
body: Ruma<get_message_events::v3::Request>, body: Ruma<get_message_events::v3::Request>,
@@ -158,9 +172,17 @@ pub async fn get_message_events_route(
}, },
}; };
let to = body.to.as_ref().and_then(|t| PduCount::try_from_string(t).ok()); let to = body
.to
.as_ref()
.and_then(|t| PduCount::try_from_string(t).ok());
services().rooms.lazy_loading.lazy_load_confirm_delivery(sender_user, sender_device, &body.room_id, from).await?; services().rooms.lazy_loading.lazy_load_confirm_delivery(
sender_user,
sender_device,
&body.room_id,
from,
)?;
let limit = u64::from(body.limit).min(100) as usize; let limit = u64::from(body.limit).min(100) as usize;
@@ -177,7 +199,7 @@ pub async fn get_message_events_route(
.timeline .timeline
.pdus_after(sender_user, &body.room_id, from)? .pdus_after(sender_user, &body.room_id, from)?
.take(limit) .take(limit)
.filter_map(std::result::Result::ok) // Filter out buggy events .filter_map(|r| r.ok()) // Filter out buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
@@ -206,20 +228,27 @@ pub async fn get_message_events_route(
next_token = events_after.last().map(|(count, _)| count).copied(); next_token = events_after.last().map(|(count, _)| count).copied();
let events_after: Vec<_> = events_after.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect(); let events_after: Vec<_> = events_after
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
resp.start = from.stringify(); resp.start = from.stringify();
resp.end = next_token.map(|count| count.stringify()); resp.end = next_token.map(|count| count.stringify());
resp.chunk = events_after; resp.chunk = events_after;
}, }
ruma::api::Direction::Backward => { ruma::api::Direction::Backward => {
services().rooms.timeline.backfill_if_required(&body.room_id, from).await?; services()
.rooms
.timeline
.backfill_if_required(&body.room_id, from)
.await?;
let events_before: Vec<_> = services() let events_before: Vec<_> = services()
.rooms .rooms
.timeline .timeline
.pdus_until(sender_user, &body.room_id, from)? .pdus_until(sender_user, &body.room_id, from)?
.take(limit) .take(limit)
.filter_map(std::result::Result::ok) // Filter out buggy events .filter_map(|r| r.ok()) // Filter out buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
@@ -248,12 +277,15 @@ pub async fn get_message_events_route(
next_token = events_before.last().map(|(count, _)| count).copied(); next_token = events_before.last().map(|(count, _)| count).copied();
let events_before: Vec<_> = events_before.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect(); let events_before: Vec<_> = events_before
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
resp.start = from.stringify(); resp.start = from.stringify();
resp.end = next_token.map(|count| count.stringify()); resp.end = next_token.map(|count| count.stringify());
resp.chunk = events_before; resp.chunk = events_before;
}, }
} }
resp.state = Vec::new(); resp.state = Vec::new();
@@ -276,7 +308,7 @@ pub async fn get_message_events_route(
&body.room_id, &body.room_id,
lazy_loaded, lazy_loaded,
next_token, next_token,
).await; );
} }
*/ */
+31 -11
View File
@@ -1,18 +1,21 @@
use std::time::Duration; use crate::{services, Error, Result, Ruma};
use ruma::api::client::{ use ruma::api::client::{
error::ErrorKind, error::ErrorKind,
presence::{get_presence, set_presence}, presence::{get_presence, set_presence},
}; };
use std::time::Duration;
use crate::{services, Error, Result, Ruma};
/// # `PUT /_matrix/client/r0/presence/{userId}/status` /// # `PUT /_matrix/client/r0/presence/{userId}/status`
/// ///
/// Sets the presence state of the sender user. /// Sets the presence state of the sender user.
pub async fn set_presence_route(body: Ruma<set_presence::v3::Request>) -> Result<set_presence::v3::Response> { pub async fn set_presence_route(
body: Ruma<set_presence::v3::Request>,
) -> Result<set_presence::v3::Response> {
if !services().globals.allow_local_presence() { if !services().globals.allow_local_presence() {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Presence is disabled on this server")); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Presence is disabled on this server",
));
} }
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@@ -37,19 +40,33 @@ pub async fn set_presence_route(body: Ruma<set_presence::v3::Request>) -> Result
/// Gets the presence state of the given user. /// Gets the presence state of the given user.
/// ///
/// - Only works if you share a room with the user /// - Only works if you share a room with the user
pub async fn get_presence_route(body: Ruma<get_presence::v3::Request>) -> Result<get_presence::v3::Response> { pub async fn get_presence_route(
body: Ruma<get_presence::v3::Request>,
) -> Result<get_presence::v3::Response> {
if !services().globals.allow_local_presence() { if !services().globals.allow_local_presence() {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Presence is disabled on this server")); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Presence is disabled on this server",
));
} }
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mut presence_event = None; let mut presence_event = None;
for room_id in services().rooms.user.get_shared_rooms(vec![sender_user.clone(), body.user_id.clone()])? { for room_id in services()
.rooms
.user
.get_shared_rooms(vec![sender_user.clone(), body.user_id.clone()])?
{
let room_id = room_id?; let room_id = room_id?;
if let Some(presence) = services().rooms.edus.presence.get_presence(&room_id, sender_user)? { if let Some(presence) = services()
.rooms
.edus
.presence
.get_presence(&room_id, sender_user)?
{
presence_event = Some(presence); presence_event = Some(presence);
break; break;
} }
@@ -60,7 +77,10 @@ pub async fn get_presence_route(body: Ruma<get_presence::v3::Request>) -> Result
// TODO: Should ruma just use the presenceeventcontent type here? // TODO: Should ruma just use the presenceeventcontent type here?
status_msg: presence.content.status_msg, status_msg: presence.content.status_msg,
currently_active: presence.content.currently_active, currently_active: presence.content.currently_active,
last_active_ago: presence.content.last_active_ago.map(|millis| Duration::from_millis(millis.into())), last_active_ago: presence
.content
.last_active_ago
.map(|millis| Duration::from_millis(millis.into())),
presence: presence.content.presence, presence: presence.content.presence,
}) })
} else { } else {
+166 -81
View File
@@ -1,19 +1,19 @@
use std::sync::Arc; use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::{ api::{
client::{ client::{
error::ErrorKind, error::ErrorKind,
profile::{get_avatar_url, get_display_name, get_profile, set_avatar_url, set_display_name}, profile::{
get_avatar_url, get_display_name, get_profile, set_avatar_url, set_display_name,
}, },
federation, },
federation::{self, query::get_profile_information::v1::ProfileField},
}, },
events::{room::member::RoomMemberEventContent, StateEventType, TimelineEventType}, events::{room::member::RoomMemberEventContent, StateEventType, TimelineEventType},
presence::PresenceState, presence::PresenceState,
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use std::sync::Arc;
use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma};
/// # `PUT /_matrix/client/r0/profile/{userId}/displayname` /// # `PUT /_matrix/client/r0/profile/{userId}/displayname`
/// ///
@@ -25,14 +25,17 @@ pub async fn set_displayname_route(
) -> Result<set_display_name::v3::Response> { ) -> Result<set_display_name::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().users.set_displayname(sender_user, body.displayname.clone()).await?; services()
.users
.set_displayname(sender_user, body.displayname.clone())
.await?;
// Send a new membership event and presence update into all joined rooms // Send a new membership event and presence update into all joined rooms
let all_rooms_joined: Vec<_> = services() let all_rooms_joined: Vec<_> = services()
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
@@ -43,9 +46,16 @@ pub async fn set_displayname_route(
services() services()
.rooms .rooms
.state_accessor .state_accessor
.room_state_get(&room_id, &StateEventType::RoomMember, sender_user.as_str())? .room_state_get(
&room_id,
&StateEventType::RoomMember,
sender_user.as_str(),
)?
.ok_or_else(|| { .ok_or_else(|| {
Error::bad_database("Tried to send displayname update for user not in the room.") Error::bad_database(
"Tried to send displayname update for user not in the \
room.",
)
})? })?
.content .content
.get(), .get(),
@@ -60,20 +70,35 @@ pub async fn set_displayname_route(
room_id, room_id,
)) ))
}) })
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.collect(); .collect();
for (pdu_builder, room_id) in all_rooms_joined { for (pdu_builder, room_id) in all_rooms_joined {
let mutex_state = let mutex_state = Arc::clone(
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default()); services()
.globals
.roomid_mutex_state
.write()
.unwrap()
.entry(room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
let _ = services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await; let _ = services()
.rooms
.timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await;
} }
if services().globals.allow_local_presence() { if services().globals.allow_local_presence() {
// Presence update // Presence update
services().rooms.edus.presence.ping_presence(sender_user, PresenceState::Online)?; services()
.rooms
.edus
.presence
.ping_presence(sender_user, PresenceState::Online)?;
} }
Ok(set_display_name::v3::Response {}) Ok(set_display_name::v3::Response {})
@@ -88,38 +113,44 @@ pub async fn set_displayname_route(
pub async fn get_displayname_route( pub async fn get_displayname_route(
body: Ruma<get_display_name::v3::Request>, body: Ruma<get_display_name::v3::Request>,
) -> Result<get_display_name::v3::Response> { ) -> Result<get_display_name::v3::Response> {
if body.user_id.server_name() != services().globals.server_name() { if (services().users.exists(&body.user_id)?)
// Create and update our local copy of the user && (body.user_id.server_name() != services().globals.server_name())
if let Ok(response) = services() {
let response = services()
.sending .sending
.send_federation_request( .send_federation_request(
body.user_id.server_name(), body.user_id.server_name(),
federation::query::get_profile_information::v1::Request { federation::query::get_profile_information::v1::Request {
user_id: body.user_id.clone(), user_id: body.user_id.clone(),
field: None, // we want the full user's profile to update locally too field: Some(ProfileField::DisplayName),
}, },
) )
.await .await?;
{
if !services().users.exists(&body.user_id)? {
services().users.create(&body.user_id, None)?;
}
services().users.set_displayname(&body.user_id, response.displayname.clone()).await?; /*
services().users.set_avatar_url(&body.user_id, response.avatar_url.clone()).await?; TODO: ignore errors properly?
services().users.set_blurhash(&body.user_id, response.blurhash.clone()).await?; // Create and update our local copy of the user
// these are `let _` because it's fine if we can't find these for the user.
// also these requests are sent on room join so dead servers will make room joins annoying again
let _ = services().users.create(&body.user_id, None);
let _ = services()
.users
.set_displayname(&body.user_id, response.displayname.clone())
.await;
let _ = services()
.users
.set_avatar_url(&body.user_id, response.avatar_url)
.await;
let _ = services()
.users
.set_blurhash(&body.user_id, response.blurhash)
.await;
*/
return Ok(get_display_name::v3::Response { return Ok(get_display_name::v3::Response {
displayname: response.displayname, displayname: response.displayname,
}); });
} }
}
if !services().users.exists(&body.user_id)? {
// Return 404 if this user doesn't exist and we couldn't fetch it over
// federation
return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found."));
}
Ok(get_display_name::v3::Response { Ok(get_display_name::v3::Response {
displayname: services().users.displayname(&body.user_id)?, displayname: services().users.displayname(&body.user_id)?,
@@ -131,19 +162,27 @@ pub async fn get_displayname_route(
/// Updates the avatar_url and blurhash. /// Updates the avatar_url and blurhash.
/// ///
/// - Also makes sure other users receive the update using presence EDUs /// - Also makes sure other users receive the update using presence EDUs
pub async fn set_avatar_url_route(body: Ruma<set_avatar_url::v3::Request>) -> Result<set_avatar_url::v3::Response> { pub async fn set_avatar_url_route(
body: Ruma<set_avatar_url::v3::Request>,
) -> Result<set_avatar_url::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().users.set_avatar_url(sender_user, body.avatar_url.clone()).await?; services()
.users
.set_avatar_url(sender_user, body.avatar_url.clone())
.await?;
services().users.set_blurhash(sender_user, body.blurhash.clone()).await?; services()
.users
.set_blurhash(sender_user, body.blurhash.clone())
.await?;
// Send a new membership event and presence update into all joined rooms // Send a new membership event and presence update into all joined rooms
let all_joined_rooms: Vec<_> = services() let all_joined_rooms: Vec<_> = services()
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
@@ -154,9 +193,16 @@ pub async fn set_avatar_url_route(body: Ruma<set_avatar_url::v3::Request>) -> Re
services() services()
.rooms .rooms
.state_accessor .state_accessor
.room_state_get(&room_id, &StateEventType::RoomMember, sender_user.as_str())? .room_state_get(
&room_id,
&StateEventType::RoomMember,
sender_user.as_str(),
)?
.ok_or_else(|| { .ok_or_else(|| {
Error::bad_database("Tried to send displayname update for user not in the room.") Error::bad_database(
"Tried to send displayname update for user not in the \
room.",
)
})? })?
.content .content
.get(), .get(),
@@ -171,20 +217,35 @@ pub async fn set_avatar_url_route(body: Ruma<set_avatar_url::v3::Request>) -> Re
room_id, room_id,
)) ))
}) })
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.collect(); .collect();
for (pdu_builder, room_id) in all_joined_rooms { for (pdu_builder, room_id) in all_joined_rooms {
let mutex_state = let mutex_state = Arc::clone(
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default()); services()
.globals
.roomid_mutex_state
.write()
.unwrap()
.entry(room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
let _ = services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await; let _ = services()
.rooms
.timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await;
} }
if services().globals.allow_local_presence() { if services().globals.allow_local_presence() {
// Presence update // Presence update
services().rooms.edus.presence.ping_presence(sender_user, PresenceState::Online)?; services()
.rooms
.edus
.presence
.ping_presence(sender_user, PresenceState::Online)?;
} }
Ok(set_avatar_url::v3::Response {}) Ok(set_avatar_url::v3::Response {})
@@ -196,40 +257,48 @@ pub async fn set_avatar_url_route(body: Ruma<set_avatar_url::v3::Request>) -> Re
/// ///
/// - If user is on another server and we do not have a local copy already /// - If user is on another server and we do not have a local copy already
/// fetch avatar_url and blurhash over federation /// fetch avatar_url and blurhash over federation
pub async fn get_avatar_url_route(body: Ruma<get_avatar_url::v3::Request>) -> Result<get_avatar_url::v3::Response> { pub async fn get_avatar_url_route(
if body.user_id.server_name() != services().globals.server_name() { body: Ruma<get_avatar_url::v3::Request>,
// Create and update our local copy of the user ) -> Result<get_avatar_url::v3::Response> {
if let Ok(response) = services() if (services().users.exists(&body.user_id)?)
&& (body.user_id.server_name() != services().globals.server_name())
{
let response = services()
.sending .sending
.send_federation_request( .send_federation_request(
body.user_id.server_name(), body.user_id.server_name(),
federation::query::get_profile_information::v1::Request { federation::query::get_profile_information::v1::Request {
user_id: body.user_id.clone(), user_id: body.user_id.clone(),
field: None, // we want the full user's profile to update locally as well field: Some(ProfileField::AvatarUrl),
}, },
) )
.await .await?;
{
if !services().users.exists(&body.user_id)? {
services().users.create(&body.user_id, None)?;
}
services().users.set_displayname(&body.user_id, response.displayname.clone()).await?; /*
services().users.set_avatar_url(&body.user_id, response.avatar_url.clone()).await?; TODO: ignore errors properly?
services().users.set_blurhash(&body.user_id, response.blurhash.clone()).await?; // Create and update our local copy of the user
// these are `let _` because it's fine if we can't find these for the user.
// also these requests are sent on room join so dead servers will make room joins annoying again
let _ = services().users.create(&body.user_id, None);
let _ = services()
.users
.set_displayname(&body.user_id, response.displayname)
.await;
let _ = services()
.users
.set_avatar_url(&body.user_id, response.avatar_url.clone())
.await;
let _ = services()
.users
.set_blurhash(&body.user_id, response.blurhash.clone())
.await;
*/
return Ok(get_avatar_url::v3::Response { return Ok(get_avatar_url::v3::Response {
avatar_url: response.avatar_url, avatar_url: response.avatar_url,
blurhash: response.blurhash, blurhash: response.blurhash,
}); });
} }
}
if !services().users.exists(&body.user_id)? {
// Return 404 if this user doesn't exist and we couldn't fetch it over
// federation
return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found."));
}
Ok(get_avatar_url::v3::Response { Ok(get_avatar_url::v3::Response {
avatar_url: services().users.avatar_url(&body.user_id)?, avatar_url: services().users.avatar_url(&body.user_id)?,
@@ -243,10 +312,13 @@ pub async fn get_avatar_url_route(body: Ruma<get_avatar_url::v3::Request>) -> Re
/// ///
/// - If user is on another server and we do not have a local copy already, /// - If user is on another server and we do not have a local copy already,
/// fetch profile over federation. /// fetch profile over federation.
pub async fn get_profile_route(body: Ruma<get_profile::v3::Request>) -> Result<get_profile::v3::Response> { pub async fn get_profile_route(
if body.user_id.server_name() != services().globals.server_name() { body: Ruma<get_profile::v3::Request>,
// Create and update our local copy of the user ) -> Result<get_profile::v3::Response> {
if let Ok(response) = services() if (services().users.exists(&body.user_id)?)
&& (body.user_id.server_name() != services().globals.server_name())
{
let response = services()
.sending .sending
.send_federation_request( .send_federation_request(
body.user_id.server_name(), body.user_id.server_name(),
@@ -255,15 +327,27 @@ pub async fn get_profile_route(body: Ruma<get_profile::v3::Request>) -> Result<g
field: None, field: None,
}, },
) )
.await .await?;
{
if !services().users.exists(&body.user_id)? {
services().users.create(&body.user_id, None)?;
}
services().users.set_displayname(&body.user_id, response.displayname.clone()).await?; /*
services().users.set_avatar_url(&body.user_id, response.avatar_url.clone()).await?; TODO: ignore errors properly?
services().users.set_blurhash(&body.user_id, response.blurhash.clone()).await?; // Create and update our local copy of the user
// these are `let _` because it's fine if we can't find these for the user.
// also these requests are sent on room join so dead servers will make room joins annoying again
let _ = services().users.create(&body.user_id, None);
let _ = services()
.users
.set_displayname(&body.user_id, response.displayname.clone())
.await;
let _ = services()
.users
.set_avatar_url(&body.user_id, response.avatar_url.clone())
.await;
let _ = services()
.users
.set_blurhash(&body.user_id, response.blurhash.clone())
.await;
*/
return Ok(get_profile::v3::Response { return Ok(get_profile::v3::Response {
displayname: response.displayname, displayname: response.displayname,
@@ -271,12 +355,13 @@ pub async fn get_profile_route(body: Ruma<get_profile::v3::Request>) -> Result<g
blurhash: response.blurhash, blurhash: response.blurhash,
}); });
} }
}
if !services().users.exists(&body.user_id)? { if !services().users.exists(&body.user_id)? {
// Return 404 if this user doesn't exist and we couldn't fetch it over // Return 404 if this user doesn't exist and we couldn't fetch it over federation
// federation return Err(Error::BadRequest(
return Err(Error::BadRequest(ErrorKind::NotFound, "Profile was not found.")); ErrorKind::NotFound,
"Profile was not found.",
));
} }
Ok(get_profile::v3::Response { Ok(get_profile::v3::Response {
+159 -58
View File
@@ -1,17 +1,17 @@
use crate::{services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
push::{ push::{
delete_pushrule, get_pushers, get_pushrule, get_pushrule_actions, get_pushrule_enabled, get_pushrules_all, delete_pushrule, get_pushers, get_pushrule, get_pushrule_actions, get_pushrule_enabled,
set_pusher, set_pushrule, set_pushrule_actions, set_pushrule_enabled, RuleScope, get_pushrules_all, set_pusher, set_pushrule, set_pushrule_actions,
set_pushrule_enabled, RuleScope,
}, },
}, },
events::{push_rules::PushRulesEvent, GlobalAccountDataEventType}, events::{push_rules::PushRulesEvent, GlobalAccountDataEventType},
push::{InsertPushRuleError, RemovePushRuleError}, push::{InsertPushRuleError, RemovePushRuleError},
}; };
use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/r0/pushrules` /// # `GET /_matrix/client/r0/pushrules`
/// ///
/// Retrieves the push rules event for this user. /// Retrieves the push rules event for this user.
@@ -22,8 +22,15 @@ pub async fn get_pushrules_all_route(
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
@@ -37,33 +44,48 @@ pub async fn get_pushrules_all_route(
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}` /// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
/// ///
/// Retrieves a single specified push rule for this user. /// Retrieves a single specified push rule for this user.
pub async fn get_pushrule_route(body: Ruma<get_pushrule::v3::Request>) -> Result<get_pushrule::v3::Response> { pub async fn get_pushrule_route(
body: Ruma<get_pushrule::v3::Request>,
) -> Result<get_pushrule::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content; .content;
let rule = account_data.global.get(body.kind.clone(), &body.rule_id).map(Into::into); let rule = account_data
.global
.get(body.kind.clone(), &body.rule_id)
.map(Into::into);
if let Some(rule) = rule { if let Some(rule) = rule {
Ok(get_pushrule::v3::Response { Ok(get_pushrule::v3::Response { rule })
rule,
})
} else { } else {
Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")) Err(Error::BadRequest(
ErrorKind::NotFound,
"Push rule not found.",
))
} }
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}` /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
/// ///
/// Creates a single specified push rule for this user. /// Creates a single specified push rule for this user.
pub async fn set_pushrule_route(body: Ruma<set_pushrule::v3::Request>) -> Result<set_pushrule::v3::Response> { pub async fn set_pushrule_route(
body: Ruma<set_pushrule::v3::Request>,
) -> Result<set_pushrule::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let body = body.body; let body = body.body;
@@ -76,30 +98,41 @@ pub async fn set_pushrule_route(body: Ruma<set_pushrule::v3::Request>) -> Result
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if let Err(error) = if let Err(error) = account_data.content.global.insert(
account_data.content.global.insert(body.rule.clone(), body.after.as_deref(), body.before.as_deref()) body.rule.clone(),
{ body.after.as_deref(),
body.before.as_deref(),
) {
let err = match error { let err = match error {
InsertPushRuleError::ServerDefaultRuleId => Error::BadRequest( InsertPushRuleError::ServerDefaultRuleId => Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Rule IDs starting with a dot are reserved for server-default rules.", "Rule IDs starting with a dot are reserved for server-default rules.",
), ),
InsertPushRuleError::InvalidRuleId => { InsertPushRuleError::InvalidRuleId => Error::BadRequest(
Error::BadRequest(ErrorKind::InvalidParam, "Rule ID containing invalid characters.") ErrorKind::InvalidParam,
}, "Rule ID containing invalid characters.",
),
InsertPushRuleError::RelativeToServerDefaultRule => Error::BadRequest( InsertPushRuleError::RelativeToServerDefaultRule => Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Can't place a push rule relatively to a server-default rule.", "Can't place a push rule relatively to a server-default rule.",
), ),
InsertPushRuleError::UnknownRuleId => { InsertPushRuleError::UnknownRuleId => Error::BadRequest(
Error::BadRequest(ErrorKind::NotFound, "The before or after rule could not be found.") ErrorKind::NotFound,
}, "The before or after rule could not be found.",
),
InsertPushRuleError::BeforeHigherThanAfter => Error::BadRequest( InsertPushRuleError::BeforeHigherThanAfter => Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"The before rule has a higher priority than the after rule.", "The before rule has a higher priority than the after rule.",
@@ -137,8 +170,15 @@ pub async fn get_pushrule_actions_route(
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
@@ -148,11 +188,12 @@ pub async fn get_pushrule_actions_route(
let actions = global let actions = global
.get(body.kind.clone(), &body.rule_id) .get(body.kind.clone(), &body.rule_id)
.map(|rule| rule.actions().to_owned()) .map(|rule| rule.actions().to_owned())
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Push rule not found."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Push rule not found.",
))?;
Ok(get_pushrule_actions::v3::Response { Ok(get_pushrule_actions::v3::Response { actions })
actions,
})
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions` /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions`
@@ -172,14 +213,29 @@ pub async fn set_pushrule_actions_route(
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if account_data.content.global.set_actions(body.kind.clone(), &body.rule_id, body.actions.clone()).is_err() { if account_data
return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")); .content
.global
.set_actions(body.kind.clone(), &body.rule_id, body.actions.clone())
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::NotFound,
"Push rule not found.",
));
} }
services().account_data.update( services().account_data.update(
@@ -209,8 +265,15 @@ pub async fn get_pushrule_enabled_route(
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
@@ -218,12 +281,13 @@ pub async fn get_pushrule_enabled_route(
let global = account_data.content.global; let global = account_data.content.global;
let enabled = global let enabled = global
.get(body.kind.clone(), &body.rule_id) .get(body.kind.clone(), &body.rule_id)
.map(ruma::push::AnyPushRuleRef::enabled) .map(|r| r.enabled())
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Push rule not found."))?; .ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Push rule not found.",
))?;
Ok(get_pushrule_enabled::v3::Response { Ok(get_pushrule_enabled::v3::Response { enabled })
enabled,
})
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled` /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled`
@@ -243,14 +307,29 @@ pub async fn set_pushrule_enabled_route(
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if account_data.content.global.set_enabled(body.kind.clone(), &body.rule_id, body.enabled).is_err() { if account_data
return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")); .content
.global
.set_enabled(body.kind.clone(), &body.rule_id, body.enabled)
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::NotFound,
"Push rule not found.",
));
} }
services().account_data.update( services().account_data.update(
@@ -266,7 +345,9 @@ pub async fn set_pushrule_enabled_route(
/// # `DELETE /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}` /// # `DELETE /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
/// ///
/// Deletes a single specified push rule for this user. /// Deletes a single specified push rule for this user.
pub async fn delete_pushrule_route(body: Ruma<delete_pushrule::v3::Request>) -> Result<delete_pushrule::v3::Response> { pub async fn delete_pushrule_route(
body: Ruma<delete_pushrule::v3::Request>,
) -> Result<delete_pushrule::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if body.scope != RuleScope::Global { if body.scope != RuleScope::Global {
@@ -278,18 +359,32 @@ pub async fn delete_pushrule_route(body: Ruma<delete_pushrule::v3::Request>) ->
let event = services() let event = services()
.account_data .account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())? .get(
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?; None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"PushRules event not found.",
))?;
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get()) let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?; .map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if let Err(error) = account_data.content.global.remove(body.kind.clone(), &body.rule_id) { if let Err(error) = account_data
.content
.global
.remove(body.kind.clone(), &body.rule_id)
{
let err = match error { let err = match error {
RemovePushRuleError::ServerDefault => { RemovePushRuleError::ServerDefault => Error::BadRequest(
Error::BadRequest(ErrorKind::InvalidParam, "Cannot delete a server-default pushrule.") ErrorKind::InvalidParam,
}, "Cannot delete a server-default pushrule.",
RemovePushRuleError::NotFound => Error::BadRequest(ErrorKind::NotFound, "Push rule not found."), ),
RemovePushRuleError::NotFound => {
Error::BadRequest(ErrorKind::NotFound, "Push rule not found.")
}
_ => Error::BadRequest(ErrorKind::InvalidParam, "Invalid data."), _ => Error::BadRequest(ErrorKind::InvalidParam, "Invalid data."),
}; };
@@ -309,7 +404,9 @@ pub async fn delete_pushrule_route(body: Ruma<delete_pushrule::v3::Request>) ->
/// # `GET /_matrix/client/r0/pushers` /// # `GET /_matrix/client/r0/pushers`
/// ///
/// Gets all currently active pushers for the sender user. /// Gets all currently active pushers for the sender user.
pub async fn get_pushers_route(body: Ruma<get_pushers::v3::Request>) -> Result<get_pushers::v3::Response> { pub async fn get_pushers_route(
body: Ruma<get_pushers::v3::Request>,
) -> Result<get_pushers::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
Ok(get_pushers::v3::Response { Ok(get_pushers::v3::Response {
@@ -322,10 +419,14 @@ pub async fn get_pushers_route(body: Ruma<get_pushers::v3::Request>) -> Result<g
/// Adds a pusher for the sender user. /// Adds a pusher for the sender user.
/// ///
/// - TODO: Handle `append` /// - TODO: Handle `append`
pub async fn set_pushers_route(body: Ruma<set_pusher::v3::Request>) -> Result<set_pusher::v3::Response> { pub async fn set_pushers_route(
body: Ruma<set_pusher::v3::Request>,
) -> Result<set_pusher::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().pusher.set_pusher(sender_user, body.action.clone())?; services()
.pusher
.set_pusher(sender_user, body.action.clone())?;
Ok(set_pusher::v3::Response::default()) Ok(set_pusher::v3::Response::default())
} }
+41 -24
View File
@@ -1,5 +1,4 @@
use std::collections::BTreeMap; use crate::{service::rooms::timeline::PduCount, services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::{error::ErrorKind, read_marker::set_read_marker, receipt::create_receipt}, api::client::{error::ErrorKind, read_marker::set_read_marker, receipt::create_receipt},
events::{ events::{
@@ -8,17 +7,17 @@ use ruma::{
}, },
MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch,
}; };
use std::collections::BTreeMap;
use crate::{service::rooms::timeline::PduCount, services, Error, Result, Ruma};
/// # `POST /_matrix/client/r0/rooms/{roomId}/read_markers` /// # `POST /_matrix/client/r0/rooms/{roomId}/read_markers`
/// ///
/// Sets different types of read markers. /// Sets different types of read markers.
/// ///
/// - Updates fully-read account data event to `fully_read` /// - Updates fully-read account data event to `fully_read`
/// - If `read_receipt` is set: Update private marker and public read receipt /// - If `read_receipt` is set: Update private marker and public read receipt EDU
/// EDU pub async fn set_read_marker_route(
pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) -> Result<set_read_marker::v3::Response> { body: Ruma<set_read_marker::v3::Request>,
) -> Result<set_read_marker::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if let Some(fully_read) = &body.fully_read { if let Some(fully_read) = &body.fully_read {
@@ -36,7 +35,10 @@ pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) ->
} }
if body.private_read_receipt.is_some() || body.read_receipt.is_some() { if body.private_read_receipt.is_some() || body.read_receipt.is_some() {
services().rooms.user.reset_notification_counts(sender_user, &body.room_id)?; services()
.rooms
.user
.reset_notification_counts(sender_user, &body.room_id)?;
} }
if let Some(event) = &body.private_read_receipt { if let Some(event) = &body.private_read_receipt {
@@ -44,17 +46,24 @@ pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) ->
.rooms .rooms
.timeline .timeline
.get_pdu_count(event)? .get_pdu_count(event)?
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Event does not exist."))?; .ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Event does not exist.",
))?;
let count = match count { let count = match count {
PduCount::Backfilled(_) => { PduCount::Backfilled(_) => {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Read receipt is in backfilled timeline", "Read receipt is in backfilled timeline",
)) ))
}, }
PduCount::Normal(c) => c, PduCount::Normal(c) => c,
}; };
services().rooms.edus.read_receipt.private_read_set(&body.room_id, sender_user, count)?; services()
.rooms
.edus
.read_receipt
.private_read_set(&body.room_id, sender_user, count)?;
} }
if let Some(event) = &body.read_receipt { if let Some(event) = &body.read_receipt {
@@ -81,8 +90,6 @@ pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) ->
room_id: body.room_id.clone(), room_id: body.room_id.clone(),
}, },
)?; )?;
services().sending.flush_room(&body.room_id)?;
} }
Ok(set_read_marker::v3::Response {}) Ok(set_read_marker::v3::Response {})
@@ -91,14 +98,19 @@ pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) ->
/// # `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}` /// # `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}`
/// ///
/// Sets private read marker and public read receipt EDU. /// Sets private read marker and public read receipt EDU.
pub async fn create_receipt_route(body: Ruma<create_receipt::v3::Request>) -> Result<create_receipt::v3::Response> { pub async fn create_receipt_route(
body: Ruma<create_receipt::v3::Request>,
) -> Result<create_receipt::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if matches!( if matches!(
&body.receipt_type, &body.receipt_type,
create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate
) { ) {
services().rooms.user.reset_notification_counts(sender_user, &body.room_id)?; services()
.rooms
.user
.reset_notification_counts(sender_user, &body.room_id)?;
} }
match body.receipt_type { match body.receipt_type {
@@ -114,7 +126,7 @@ pub async fn create_receipt_route(body: Ruma<create_receipt::v3::Request>) -> Re
RoomAccountDataEventType::FullyRead, RoomAccountDataEventType::FullyRead,
&serde_json::to_value(fully_read_event).expect("to json value always works"), &serde_json::to_value(fully_read_event).expect("to json value always works"),
)?; )?;
}, }
create_receipt::v3::ReceiptType::Read => { create_receipt::v3::ReceiptType::Read => {
let mut user_receipts = BTreeMap::new(); let mut user_receipts = BTreeMap::new();
user_receipts.insert( user_receipts.insert(
@@ -128,7 +140,7 @@ pub async fn create_receipt_route(body: Ruma<create_receipt::v3::Request>) -> Re
receipts.insert(ReceiptType::Read, user_receipts); receipts.insert(ReceiptType::Read, user_receipts);
let mut receipt_content = BTreeMap::new(); let mut receipt_content = BTreeMap::new();
receipt_content.insert(body.event_id.clone(), receipts); receipt_content.insert(body.event_id.to_owned(), receipts);
services().rooms.edus.read_receipt.readreceipt_update( services().rooms.edus.read_receipt.readreceipt_update(
sender_user, sender_user,
@@ -138,26 +150,31 @@ pub async fn create_receipt_route(body: Ruma<create_receipt::v3::Request>) -> Re
room_id: body.room_id.clone(), room_id: body.room_id.clone(),
}, },
)?; )?;
}
services().sending.flush_room(&body.room_id)?;
},
create_receipt::v3::ReceiptType::ReadPrivate => { create_receipt::v3::ReceiptType::ReadPrivate => {
let count = services() let count = services()
.rooms .rooms
.timeline .timeline
.get_pdu_count(&body.event_id)? .get_pdu_count(&body.event_id)?
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Event does not exist."))?; .ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Event does not exist.",
))?;
let count = match count { let count = match count {
PduCount::Backfilled(_) => { PduCount::Backfilled(_) => {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Read receipt is in backfilled timeline", "Read receipt is in backfilled timeline",
)) ))
}, }
PduCount::Normal(c) => c, PduCount::Normal(c) => c,
}; };
services().rooms.edus.read_receipt.private_read_set(&body.room_id, sender_user, count)?; services().rooms.edus.read_receipt.private_read_set(
}, &body.room_id,
sender_user,
count,
)?;
}
_ => return Err(Error::bad_database("Unsupported receipt type")), _ => return Err(Error::bad_database("Unsupported receipt type")),
} }
+15 -8
View File
@@ -1,24 +1,33 @@
use std::sync::Arc; use std::sync::Arc;
use crate::{service::pdu::PduBuilder, services, Result, Ruma};
use ruma::{ use ruma::{
api::client::redact::redact_event, api::client::redact::redact_event,
events::{room::redaction::RoomRedactionEventContent, TimelineEventType}, events::{room::redaction::RoomRedactionEventContent, TimelineEventType},
}; };
use serde_json::value::to_raw_value;
use crate::{service::pdu::PduBuilder, services, Result, Ruma}; use serde_json::value::to_raw_value;
/// # `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}` /// # `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}`
/// ///
/// Tries to send a redaction event into the room. /// Tries to send a redaction event into the room.
/// ///
/// - TODO: Handle txn id /// - TODO: Handle txn id
pub async fn redact_event_route(body: Ruma<redact_event::v3::Request>) -> Result<redact_event::v3::Response> { pub async fn redact_event_route(
body: Ruma<redact_event::v3::Request>,
) -> Result<redact_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let body = body.body; let body = body.body;
let mutex_state = let mutex_state = Arc::clone(
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(body.room_id.clone()).or_default()); services()
.globals
.roomid_mutex_state
.write()
.unwrap()
.entry(body.room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
let event_id = services() let event_id = services()
@@ -45,7 +54,5 @@ pub async fn redact_event_route(body: Ruma<redact_event::v3::Request>) -> Result
drop(state_lock); drop(state_lock);
let event_id = (*event_id).to_owned(); let event_id = (*event_id).to_owned();
Ok(redact_event::v3::Response { Ok(redact_event::v3::Response { event_id })
event_id,
})
} }
+51 -18
View File
@@ -1,5 +1,6 @@
use ruma::api::client::relations::{ use ruma::api::client::relations::{
get_relating_events, get_relating_events_with_rel_type, get_relating_events_with_rel_type_and_event_type, get_relating_events, get_relating_events_with_rel_type,
get_relating_events_with_rel_type_and_event_type,
}; };
use crate::{service::rooms::timeline::PduCount, services, Result, Ruma}; use crate::{service::rooms::timeline::PduCount, services, Result, Ruma};
@@ -19,27 +20,39 @@ pub async fn get_relating_events_with_rel_type_and_event_type_route(
}, },
}; };
let to = body.to.as_ref().and_then(|t| PduCount::try_from_string(t).ok()); let to = body
.to
.as_ref()
.and_then(|t| PduCount::try_from_string(t).ok());
// Use limit or else 10, with maximum 100 // Use limit or else 10, with maximum 100
let limit = body.limit.and_then(|u| u32::try_from(u).ok()).map_or(10_usize, |u| u as usize).min(100); let limit = body
.limit
.and_then(|u| u32::try_from(u).ok())
.map_or(10_usize, |u| u as usize)
.min(100);
let res = services().rooms.pdu_metadata.paginate_relations_with_filter( let res = services()
.rooms
.pdu_metadata
.paginate_relations_with_filter(
sender_user, sender_user,
&body.room_id, &body.room_id,
&body.event_id, &body.event_id,
&Some(body.event_type.clone()), Some(body.event_type.clone()),
&Some(body.rel_type.clone()), Some(body.rel_type.clone()),
from, from,
to, to,
limit, limit,
)?; )?;
Ok(get_relating_events_with_rel_type_and_event_type::v1::Response { Ok(
get_relating_events_with_rel_type_and_event_type::v1::Response {
chunk: res.chunk, chunk: res.chunk,
next_batch: res.next_batch, next_batch: res.next_batch,
prev_batch: res.prev_batch, prev_batch: res.prev_batch,
}) },
)
} }
/// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}` /// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}`
@@ -57,17 +70,27 @@ pub async fn get_relating_events_with_rel_type_route(
}, },
}; };
let to = body.to.as_ref().and_then(|t| PduCount::try_from_string(t).ok()); let to = body
.to
.as_ref()
.and_then(|t| PduCount::try_from_string(t).ok());
// Use limit or else 10, with maximum 100 // Use limit or else 10, with maximum 100
let limit = body.limit.and_then(|u| u32::try_from(u).ok()).map_or(10_usize, |u| u as usize).min(100); let limit = body
.limit
.and_then(|u| u32::try_from(u).ok())
.map_or(10_usize, |u| u as usize)
.min(100);
let res = services().rooms.pdu_metadata.paginate_relations_with_filter( let res = services()
.rooms
.pdu_metadata
.paginate_relations_with_filter(
sender_user, sender_user,
&body.room_id, &body.room_id,
&body.event_id, &body.event_id,
&None, None,
&Some(body.rel_type.clone()), Some(body.rel_type.clone()),
from, from,
to, to,
limit, limit,
@@ -95,17 +118,27 @@ pub async fn get_relating_events_route(
}, },
}; };
let to = body.to.as_ref().and_then(|t| PduCount::try_from_string(t).ok()); let to = body
.to
.as_ref()
.and_then(|t| PduCount::try_from_string(t).ok());
// Use limit or else 10, with maximum 100 // Use limit or else 10, with maximum 100
let limit = body.limit.and_then(|u| u32::try_from(u).ok()).map_or(10_usize, |u| u as usize).min(100); let limit = body
.limit
.and_then(|u| u32::try_from(u).ok())
.map_or(10_usize, |u| u as usize)
.min(100);
services().rooms.pdu_metadata.paginate_relations_with_filter( services()
.rooms
.pdu_metadata
.paginate_relations_with_filter(
sender_user, sender_user,
&body.room_id, &body.room_id,
&body.event_id, &body.event_id,
&None, None,
&None, None,
from, from,
to, to,
limit, limit,
+25 -19
View File
@@ -1,5 +1,6 @@
use std::time::Duration; use std::time::Duration;
use crate::{services, utils::HtmlEscape, Error, Result, Ruma};
use rand::Rng; use rand::Rng;
use ruma::{ use ruma::{
api::client::{error::ErrorKind, room::report_content}, api::client::{error::ErrorKind, room::report_content},
@@ -9,12 +10,13 @@ use ruma::{
use tokio::time::sleep; use tokio::time::sleep;
use tracing::{debug, info}; use tracing::{debug, info};
use crate::{services, utils::HtmlEscape, Error, Result, Ruma};
/// # `POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}` /// # `POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}`
/// ///
/// Reports an inappropriate event to homeserver admins /// Reports an inappropriate event to homeserver admins
pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Result<report_content::v3::Response> { ///
pub async fn report_event_route(
body: Ruma<report_content::v3::Request>,
) -> Result<report_content::v3::Response> {
// user authentication // user authentication
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
@@ -28,7 +30,7 @@ pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Resu
ErrorKind::NotFound, ErrorKind::NotFound,
"Event ID is not known to us or Event ID is invalid", "Event ID is not known to us or Event ID is invalid",
)) ))
}, }
}; };
// check if the room ID from the URI matches the PDU's room ID // check if the room ID from the URI matches the PDU's room ID
@@ -44,7 +46,7 @@ pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Resu
.rooms .rooms
.state_cache .state_cache
.room_members(&pdu.room_id) .room_members(&pdu.room_id)
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.any(|user_id| user_id == *sender_user) .any(|user_id| user_id == *sender_user)
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@@ -69,17 +71,22 @@ pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Resu
)); ));
}; };
// send admin room message that we received the report with an @room ping for // send admin room message that we received the report with an @room ping for urgency
// urgency services()
services().admin.send_message(message::RoomMessageEventContent::text_html( .admin
.send_message(message::RoomMessageEventContent::text_html(
format!( format!(
"@room Report received from: {}\n\nEvent ID: {}\nRoom ID: {}\nSent By: {}\n\nReport Score: {}\nReport \ "@room Report received from: {}\n\n\
Reason: {}", Event ID: {}\n\
Room ID: {}\n\
Sent By: {}\n\n\
Report Score: {}\n\
Report Reason: {}",
sender_user.to_owned(), sender_user.to_owned(),
pdu.event_id, pdu.event_id,
pdu.room_id, pdu.room_id,
pdu.sender.clone(), pdu.sender.to_owned(),
body.score.unwrap_or_else(|| ruma::Int::from(0)), body.score.unwrap_or(ruma::Int::from(0)),
body.reason.as_deref().unwrap_or("") body.reason.as_deref().unwrap_or("")
), ),
format!( format!(
@@ -90,17 +97,16 @@ pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Resu
Report Info<ul><li>Report Score: {4}</li><li>Report Reason: {5}</li></ul></li>\ Report Info<ul><li>Report Score: {4}</li><li>Report Reason: {5}</li></ul></li>\
</ul></details>", </ul></details>",
sender_user.to_owned(), sender_user.to_owned(),
pdu.event_id.clone(), pdu.event_id.to_owned(),
pdu.room_id.clone(), pdu.room_id.to_owned(),
pdu.sender.clone(), pdu.sender.to_owned(),
body.score.unwrap_or_else(|| ruma::Int::from(0)), body.score.unwrap_or(ruma::Int::from(0)),
HtmlEscape(body.reason.as_deref().unwrap_or("")) HtmlEscape(body.reason.as_deref().unwrap_or(""))
), ),
)); ));
// even though this is kinda security by obscurity, let's still make a small // even though this is kinda security by obscurity, let's still make a small random delay sending a successful response
// random delay sending a successful response per spec suggestion regarding // per spec suggestion regarding enumerating for potential events existing in our server.
// enumerating for potential events existing in our server.
let time_to_wait = rand::thread_rng().gen_range(8..21); let time_to_wait = rand::thread_rng().gen_range(8..21);
debug!( debug!(
"Got successful /report request, waiting {} seconds before sending successful response.", "Got successful /report request, waiting {} seconds before sending successful response.",
+228 -95
View File
@@ -1,5 +1,6 @@
use std::{cmp::max, collections::BTreeMap, sync::Arc}; use crate::{
api::client_server::invite_helper, service::pdu::PduBuilder, services, Error, Result, Ruma,
};
use ruma::{ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
@@ -22,13 +23,13 @@ use ruma::{
}, },
int, int,
serde::JsonObject, serde::JsonObject,
CanonicalJsonObject, CanonicalJsonValue, OwnedRoomAliasId, OwnedRoomId, RoomAliasId, RoomId, RoomVersionId, CanonicalJsonObject, CanonicalJsonValue, OwnedRoomAliasId, OwnedRoomId, RoomAliasId, RoomId,
RoomVersionId,
}; };
use serde_json::{json, value::to_raw_value}; use serde_json::{json, value::to_raw_value};
use std::{cmp::max, collections::BTreeMap, sync::Arc};
use tracing::{debug, error, info, warn}; use tracing::{debug, error, info, warn};
use crate::{api::client_server::invite_helper, service::pdu::PduBuilder, services, Error, Result, Ruma};
/// # `POST /_matrix/client/v3/createRoom` /// # `POST /_matrix/client/v3/createRoom`
/// ///
/// Creates a new room. /// Creates a new room.
@@ -45,19 +46,27 @@ use crate::{api::client_server::invite_helper, service::pdu::PduBuilder, service
/// - Send events listed in initial state /// - Send events listed in initial state
/// - Send events implied by `name` and `topic` /// - Send events implied by `name` and `topic`
/// - Send invite events /// - Send invite events
pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<create_room::v3::Response> { pub async fn create_room_route(
body: Ruma<create_room::v3::Request>,
) -> Result<create_room::v3::Response> {
use create_room::v3::RoomPreset; use create_room::v3::RoomPreset;
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().globals.allow_room_creation() && !&body.from_appservice && !services().users.is_admin(sender_user)? { if !services().globals.allow_room_creation()
return Err(Error::BadRequest(ErrorKind::Forbidden, "Room creation has been disabled.")); && !&body.from_appservice
&& !services().users.is_admin(sender_user)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Room creation has been disabled.",
));
} }
let room_id: OwnedRoomId; let room_id: OwnedRoomId;
// checks if the user specified an explicit (custom) room_id to be created with // checks if the user specified an explicit (custom) room_id to be created with in request body.
// in request body. falls back to normal generated room ID if not specified. // falls back to normal generated room ID if not specified.
if let Some(CanonicalJsonValue::Object(json_body)) = &body.json_body { if let Some(CanonicalJsonValue::Object(json_body)) = &body.json_body {
match json_body.get("room_id") { match json_body.get("room_id") {
Some(custom_room_id) => { Some(custom_room_id) => {
@@ -67,8 +76,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
if custom_room_id_s.contains(':') { if custom_room_id_s.contains(':') {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Custom room ID contained `:` which is not allowed. Please note that this expects a \ "Custom room ID contained `:` which is not allowed. Please note that this expects a localpart, not the full room ID.",
localpart, not the full room ID.",
)); ));
} else if custom_room_id_s.contains(char::is_whitespace) { } else if custom_room_id_s.contains(char::is_whitespace) {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@@ -76,28 +84,45 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
"Custom room ID contained spaces which is not valid.", "Custom room ID contained spaces which is not valid.",
)); ));
} else if custom_room_id_s.len() > 255 { } else if custom_room_id_s.len() > 255 {
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Custom room ID is too long.")); return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Custom room ID is too long.",
));
} }
// apply forbidden room alias checks to custom room IDs too // apply forbidden room alias checks to custom room IDs too
if services().globals.forbidden_room_names().is_match(&custom_room_id_s) { if services()
return Err(Error::BadRequest(ErrorKind::Unknown, "Custom room ID is forbidden.")); .globals
.forbidden_room_names()
.is_match(&custom_room_id_s)
{
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Custom room ID is forbidden.",
));
} }
let full_room_id = "!".to_owned() let full_room_id = "!".to_owned()
+ &custom_room_id_s.replace('"', "") + &custom_room_id_s.replace('"', "")
+ ":" + services().globals.server_name().as_ref(); + ":"
+ services().globals.server_name().as_ref();
debug!("Full room ID: {}", full_room_id); debug!("Full room ID: {}", full_room_id);
room_id = RoomId::parse(full_room_id).map_err(|e| { room_id = RoomId::parse(full_room_id).map_err(|e| {
info!("User attempted to create room with custom room ID but failed parsing: {}", e); info!(
Error::BadRequest(ErrorKind::InvalidParam, "Custom room ID could not be parsed") "User attempted to create room with custom room ID but failed parsing: {}",
e
);
Error::BadRequest(
ErrorKind::InvalidParam,
"Custom room ID could not be parsed",
)
})?; })?;
}, }
None => room_id = RoomId::new(services().globals.server_name()), None => room_id = RoomId::new(services().globals.server_name()),
} }
} else { } else {
room_id = RoomId::new(services().globals.server_name()); room_id = RoomId::new(services().globals.server_name())
} }
// check if room ID doesn't already exist instead of erroring on auth check // check if room ID doesn't already exist instead of erroring on auth check
@@ -110,17 +135,27 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
services().rooms.short.get_or_create_shortroomid(&room_id)?; services().rooms.short.get_or_create_shortroomid(&room_id)?;
let mutex_state = let mutex_state = Arc::clone(
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default()); services()
.globals
.roomid_mutex_state
.write()
.unwrap()
.entry(room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
let alias: Option<OwnedRoomAliasId> = body.room_alias_name.as_ref().map_or(Ok(None), |localpart| { let alias: Option<OwnedRoomAliasId> =
body.room_alias_name
.as_ref()
.map_or(Ok(None), |localpart| {
// Basic checks on the room alias validity // Basic checks on the room alias validity
if localpart.contains(':') { if localpart.contains(':') {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Room alias contained `:` which is not allowed. Please note that this expects a localpart, not the \ "Room alias contained `:` which is not allowed. Please note that this expects a localpart, not the full room alias.",
full room alias.",
)); ));
} else if localpart.contains(char::is_whitespace) { } else if localpart.contains(char::is_whitespace) {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@@ -129,9 +164,9 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
)); ));
} else if localpart.len() > 255 { } else if localpart.len() > 255 {
// there is nothing spec-wise saying to check the limit of this, // there is nothing spec-wise saying to check the limit of this,
// however absurdly long room aliases are guaranteed to be unreadable or done // however absurdly long room aliases are guaranteed to be unreadable or done maliciously.
// maliciously. there is no reason a room alias should even exceed 100 // there is no reason a room alias should even exceed 100 characters as is.
// characters as is. generally in spec, 255 is matrix's fav number // generally in spec, 255 is matrix's fav number
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Room alias is excessively long, clients may not be able to handle this. Please shorten it.", "Room alias is excessively long, clients may not be able to handle this. Please shorten it.",
@@ -144,18 +179,37 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
} }
// check if room alias is forbidden // check if room alias is forbidden
if services().globals.forbidden_room_names().is_match(localpart) { if services()
return Err(Error::BadRequest(ErrorKind::Unknown, "Room alias name is forbidden.")); .globals
.forbidden_room_names()
.is_match(localpart)
{
return Err(Error::BadRequest(
ErrorKind::Unknown,
"Room alias name is forbidden.",
));
} }
let alias = let alias = RoomAliasId::parse(format!(
RoomAliasId::parse(format!("#{}:{}", localpart, services().globals.server_name())).map_err(|e| { "#{}:{}",
localpart,
services().globals.server_name()
))
.map_err(|e| {
warn!("Failed to parse room alias for room ID {}: {e}", room_id); warn!("Failed to parse room alias for room ID {}: {e}", room_id);
Error::BadRequest(ErrorKind::InvalidParam, "Invalid room alias specified.") Error::BadRequest(ErrorKind::InvalidParam, "Invalid room alias specified.")
})?; })?;
if services().rooms.alias.resolve_local_alias(&alias)?.is_some() { if services()
Err(Error::BadRequest(ErrorKind::RoomInUse, "Room alias already exists.")) .rooms
.alias
.resolve_local_alias(&alias)?
.is_some()
{
Err(Error::BadRequest(
ErrorKind::RoomInUse,
"Room alias already exists.",
))
} else { } else {
Ok(Some(alias)) Ok(Some(alias))
} }
@@ -163,7 +217,11 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
let room_version = match body.room_version.clone() { let room_version = match body.room_version.clone() {
Some(room_version) => { Some(room_version) => {
if services().globals.supported_room_versions().contains(&room_version) { if services()
.globals
.supported_room_versions()
.contains(&room_version)
{
room_version room_version
} else { } else {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@@ -171,13 +229,15 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
"This server does not support that room version.", "This server does not support that room version.",
)); ));
} }
}, }
None => services().globals.default_room_version(), None => services().globals.default_room_version(),
}; };
let content = match &body.creation_content { let content = match &body.creation_content {
Some(content) => { Some(content) => {
let mut content = content.deserialize_as::<CanonicalJsonObject>().map_err(|e| { let mut content = content
.deserialize_as::<CanonicalJsonObject>()
.map_err(|e| {
error!("Failed to deserialise content as canonical JSON: {}", e); error!("Failed to deserialise content as canonical JSON: {}", e);
Error::bad_database("Failed to deserialise content as canonical JSON.") Error::bad_database("Failed to deserialise content as canonical JSON.")
})?; })?;
@@ -199,25 +259,25 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
Error::BadRequest(ErrorKind::BadJson, "Invalid creation content") Error::BadRequest(ErrorKind::BadJson, "Invalid creation content")
})?, })?,
); );
}, }
RoomVersionId::V11 => {}, // V11 removed the "creator" key RoomVersionId::V11 => {} // V11 removed the "creator" key
_ => { _ => {
warn!("Unexpected or unsupported room version {}", room_version); warn!("Unexpected or unsupported room version {}", room_version);
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::BadJson, ErrorKind::BadJson,
"Unexpected or unsupported room version found", "Unexpected or unsupported room version found",
)); ));
}, }
} }
content.insert( content.insert(
"room_version".into(), "room_version".into(),
json!(room_version.as_str()) json!(room_version.as_str()).try_into().map_err(|_| {
.try_into() Error::BadRequest(ErrorKind::BadJson, "Invalid creation content")
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Invalid creation content"))?, })?,
); );
content content
}, }
None => { None => {
// TODO: Add correct value for v11 // TODO: Add correct value for v11
let content = match room_version { let content = match room_version {
@@ -238,7 +298,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
ErrorKind::BadJson, ErrorKind::BadJson,
"Unexpected or unsupported room version found", "Unexpected or unsupported room version found",
)); ));
}, }
}; };
let mut content = serde_json::from_str::<CanonicalJsonObject>( let mut content = serde_json::from_str::<CanonicalJsonObject>(
to_raw_value(&content) to_raw_value(&content)
@@ -248,20 +308,26 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
.unwrap(); .unwrap();
content.insert( content.insert(
"room_version".into(), "room_version".into(),
json!(room_version.as_str()) json!(room_version.as_str()).try_into().map_err(|_| {
.try_into() Error::BadRequest(ErrorKind::BadJson, "Invalid creation content")
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Invalid creation content"))?, })?,
); );
content content
}, }
}; };
// Validate creation content // Validate creation content
let de_result = let de_result = serde_json::from_str::<CanonicalJsonObject>(
serde_json::from_str::<CanonicalJsonObject>(to_raw_value(&content).expect("Invalid creation content").get()); to_raw_value(&content)
.expect("Invalid creation content")
.get(),
);
if de_result.is_err() { if de_result.is_err() {
return Err(Error::BadRequest(ErrorKind::BadJson, "Invalid creation content")); return Err(Error::BadRequest(
ErrorKind::BadJson,
"Invalid creation content",
));
} }
// 1. The room create event // 1. The room create event
@@ -314,6 +380,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
// Figure out preset. We need it for preset specific events // Figure out preset. We need it for preset specific events
let preset = body.preset.clone().unwrap_or(match &body.visibility { let preset = body.preset.clone().unwrap_or(match &body.visibility {
room::Visibility::Private => RoomPreset::PrivateChat,
room::Visibility::Public => RoomPreset::PublicChat, room::Visibility::Public => RoomPreset::PublicChat,
_ => RoomPreset::PrivateChat, // Room visibility should not be custom _ => RoomPreset::PrivateChat, // Room visibility should not be custom
}); });
@@ -335,7 +402,9 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
if let Some(power_level_content_override) = &body.power_level_content_override { if let Some(power_level_content_override) = &body.power_level_content_override {
let json: JsonObject = serde_json::from_str(power_level_content_override.json().get()) let json: JsonObject = serde_json::from_str(power_level_content_override.json().get())
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Invalid power_level_content_override."))?; .map_err(|_| {
Error::BadRequest(ErrorKind::BadJson, "Invalid power_level_content_override.")
})?;
for (key, value) in json { for (key, value) in json {
power_levels_content[key] = value; power_levels_content[key] = value;
@@ -348,7 +417,8 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
.build_and_append_pdu( .build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: TimelineEventType::RoomPowerLevels, event_type: TimelineEventType::RoomPowerLevels,
content: to_raw_value(&power_levels_content).expect("to_raw_value always works on serde_json::Value"), content: to_raw_value(&power_levels_content)
.expect("to_raw_value always works on serde_json::Value"),
unsigned: None, unsigned: None,
state_key: Some("".to_owned()), state_key: Some("".to_owned()),
redacts: None, redacts: None,
@@ -415,7 +485,9 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
.build_and_append_pdu( .build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: TimelineEventType::RoomHistoryVisibility, event_type: TimelineEventType::RoomHistoryVisibility,
content: to_raw_value(&RoomHistoryVisibilityEventContent::new(HistoryVisibility::Shared)) content: to_raw_value(&RoomHistoryVisibilityEventContent::new(
HistoryVisibility::Shared,
))
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some("".to_owned()), state_key: Some("".to_owned()),
@@ -460,11 +532,17 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
pdu_builder.state_key.get_or_insert_with(|| "".to_owned()); pdu_builder.state_key.get_or_insert_with(|| "".to_owned());
// Silently skip encryption events if they are not allowed // Silently skip encryption events if they are not allowed
if pdu_builder.event_type == TimelineEventType::RoomEncryption && !services().globals.allow_encryption() { if pdu_builder.event_type == TimelineEventType::RoomEncryption
&& !services().globals.allow_encryption()
{
continue; continue;
} }
services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await?; services()
.rooms
.timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await?;
} }
// 7. Events implied by name and topic // 7. Events implied by name and topic
@@ -534,17 +612,26 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
/// ///
/// Gets a single event. /// Gets a single event.
/// ///
/// - You have to currently be joined to the room (TODO: Respect history /// - You have to currently be joined to the room (TODO: Respect history visibility)
/// visibility) pub async fn get_room_event_route(
pub async fn get_room_event_route(body: Ruma<get_room_event::v3::Request>) -> Result<get_room_event::v3::Response> { body: Ruma<get_room_event::v3::Request>,
) -> Result<get_room_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services().rooms.timeline.get_pdu(&body.event_id)?.ok_or_else(|| { let event = services()
.rooms
.timeline
.get_pdu(&body.event_id)?
.ok_or_else(|| {
warn!("Event not found, event ID: {:?}", &body.event_id); warn!("Event not found, event ID: {:?}", &body.event_id);
Error::BadRequest(ErrorKind::NotFound, "Event not found.") Error::BadRequest(ErrorKind::NotFound, "Event not found.")
})?; })?;
if !services().rooms.state_accessor.user_can_see_event(sender_user, &event.room_id, &body.event_id)? { if !services().rooms.state_accessor.user_can_see_event(
sender_user,
&event.room_id,
&body.event_id,
)? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"You don't have permission to view this event.", "You don't have permission to view this event.",
@@ -563,12 +650,17 @@ pub async fn get_room_event_route(body: Ruma<get_room_event::v3::Request>) -> Re
/// ///
/// Lists all aliases of the room. /// Lists all aliases of the room.
/// ///
/// - Only users joined to the room are allowed to call this TODO: Allow any /// - Only users joined to the room are allowed to call this TODO: Allow any user to call it if history_visibility is world readable
/// user to call it if history_visibility is world readable pub async fn get_room_aliases_route(
pub async fn get_room_aliases_route(body: Ruma<aliases::v3::Request>) -> Result<aliases::v3::Response> { body: Ruma<aliases::v3::Request>,
) -> Result<aliases::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_cache.is_joined(sender_user, &body.room_id)? { if !services()
.rooms
.state_cache
.is_joined(sender_user, &body.room_id)?
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"You don't have permission to view this room.", "You don't have permission to view this room.",
@@ -580,7 +672,7 @@ pub async fn get_room_aliases_route(body: Ruma<aliases::v3::Request>) -> Result<
.rooms .rooms
.alias .alias
.local_aliases_for_room(&body.room_id) .local_aliases_for_room(&body.room_id)
.filter_map(std::result::Result::ok) .filter_map(|a| a.ok())
.collect(), .collect(),
}) })
} }
@@ -595,10 +687,16 @@ pub async fn get_room_aliases_route(body: Ruma<aliases::v3::Request>) -> Result<
/// - Transfers some state events /// - Transfers some state events
/// - Moves local aliases /// - Moves local aliases
/// - Modifies old room power levels to prevent users from speaking /// - Modifies old room power levels to prevent users from speaking
pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result<upgrade_room::v3::Response> { pub async fn upgrade_room_route(
body: Ruma<upgrade_room::v3::Request>,
) -> Result<upgrade_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().globals.supported_room_versions().contains(&body.new_version) { if !services()
.globals
.supported_room_versions()
.contains(&body.new_version)
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::UnsupportedRoomVersion, ErrorKind::UnsupportedRoomVersion,
"This server does not support that room version.", "This server does not support that room version.",
@@ -607,15 +705,24 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Create a replacement room // Create a replacement room
let replacement_room = RoomId::new(services().globals.server_name()); let replacement_room = RoomId::new(services().globals.server_name());
services().rooms.short.get_or_create_shortroomid(&replacement_room)?; services()
.rooms
.short
.get_or_create_shortroomid(&replacement_room)?;
let mutex_state = let mutex_state = Arc::clone(
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(body.room_id.clone()).or_default()); services()
.globals
.roomid_mutex_state
.write()
.unwrap()
.entry(body.room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
// Send a m.room.tombstone event to the old room to indicate that it is not // Send a m.room.tombstone event to the old room to indicate that it is not intended to be used any further
// intended to be used any further Fail if the sender does not have the required // Fail if the sender does not have the required permissions
// permissions
let tombstone_event_id = services() let tombstone_event_id = services()
.rooms .rooms
.timeline .timeline
@@ -639,8 +746,15 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Change lock to replacement room // Change lock to replacement room
drop(state_lock); drop(state_lock);
let mutex_state = let mutex_state = Arc::clone(
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(replacement_room.clone()).or_default()); services()
.globals
.roomid_mutex_state
.write()
.unwrap()
.entry(replacement_room.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
// Get the old room creation event // Get the old room creation event
@@ -661,8 +775,7 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
(*tombstone_event_id).to_owned(), (*tombstone_event_id).to_owned(),
)); ));
// Send a m.room.create event containing a predecessor field and the applicable // Send a m.room.create event containing a predecessor field and the applicable room_version
// room_version
match body.new_version { match body.new_version {
RoomVersionId::V1 RoomVersionId::V1
| RoomVersionId::V2 | RoomVersionId::V2
@@ -681,18 +794,21 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
Error::BadRequest(ErrorKind::BadJson, "Error forming creation event") Error::BadRequest(ErrorKind::BadJson, "Error forming creation event")
})?, })?,
); );
}, }
RoomVersionId::V11 => { RoomVersionId::V11 => {
// "creator" key no longer exists in V11 rooms // "creator" key no longer exists in V11 rooms
create_event_content.remove("creator"); create_event_content.remove("creator");
}, }
_ => { _ => {
warn!("Unexpected or unsupported room version {}", body.new_version); warn!(
"Unexpected or unsupported room version {}",
body.new_version
);
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::BadJson, ErrorKind::BadJson,
"Unexpected or unsupported room version found", "Unexpected or unsupported room version found",
)); ));
}, }
} }
create_event_content.insert( create_event_content.insert(
@@ -710,11 +826,16 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Validate creation event content // Validate creation event content
let de_result = serde_json::from_str::<CanonicalJsonObject>( let de_result = serde_json::from_str::<CanonicalJsonObject>(
to_raw_value(&create_event_content).expect("Error forming creation event").get(), to_raw_value(&create_event_content)
.expect("Error forming creation event")
.get(),
); );
if de_result.is_err() { if de_result.is_err() {
return Err(Error::BadRequest(ErrorKind::BadJson, "Error forming creation event")); return Err(Error::BadRequest(
ErrorKind::BadJson,
"Error forming creation event",
));
} }
services() services()
@@ -723,7 +844,8 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
.build_and_append_pdu( .build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: TimelineEventType::RoomCreate, event_type: TimelineEventType::RoomCreate,
content: to_raw_value(&create_event_content).expect("event is valid, we just created it"), content: to_raw_value(&create_event_content)
.expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some("".to_owned()), state_key: Some("".to_owned()),
redacts: None, redacts: None,
@@ -777,7 +899,12 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Replicate transferable state events to the new room // Replicate transferable state events to the new room
for event_type in transferable_state_events { for event_type in transferable_state_events {
let event_content = match services().rooms.state_accessor.room_state_get(&body.room_id, &event_type, "")? { let event_content =
match services()
.rooms
.state_accessor
.room_state_get(&body.room_id, &event_type, "")?
{
Some(v) => v.content.clone(), Some(v) => v.content.clone(),
None => continue, // Skipping missing events. None => continue, // Skipping missing events.
}; };
@@ -801,8 +928,16 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
} }
// Moves any local aliases to the new room // Moves any local aliases to the new room
for alias in services().rooms.alias.local_aliases_for_room(&body.room_id).filter_map(std::result::Result::ok) { for alias in services()
services().rooms.alias.set_alias(&alias, &replacement_room)?; .rooms
.alias
.local_aliases_for_room(&body.room_id)
.filter_map(|r| r.ok())
{
services()
.rooms
.alias
.set_alias(&alias, &replacement_room)?;
} }
// Get the old room power levels // Get the old room power levels
@@ -822,15 +957,15 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
power_levels_event_content.events_default = new_level; power_levels_event_content.events_default = new_level;
power_levels_event_content.invite = new_level; power_levels_event_content.invite = new_level;
// Modify the power levels in the old room to prevent sending of events and // Modify the power levels in the old room to prevent sending of events and inviting new users
// inviting new users
let _ = services() let _ = services()
.rooms .rooms
.timeline .timeline
.build_and_append_pdu( .build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: TimelineEventType::RoomPowerLevels, event_type: TimelineEventType::RoomPowerLevels,
content: to_raw_value(&power_levels_event_content).expect("event is valid, we just created it"), content: to_raw_value(&power_levels_event_content)
.expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: Some("".to_owned()), state_key: Some("".to_owned()),
redacts: None, redacts: None,
@@ -844,7 +979,5 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
drop(state_lock); drop(state_lock);
// Return the replacement room id // Return the replacement room id
Ok(upgrade_room::v3::Response { Ok(upgrade_room::v3::Response { replacement_room })
replacement_room,
})
} }
+29 -11
View File
@@ -1,5 +1,4 @@
use std::collections::BTreeMap; use crate::{services, Error, Result, Ruma};
use ruma::api::client::{ use ruma::api::client::{
error::ErrorKind, error::ErrorKind,
search::search_events::{ search::search_events::{
@@ -8,22 +7,28 @@ use ruma::api::client::{
}, },
}; };
use crate::{services, Error, Result, Ruma}; use std::collections::BTreeMap;
/// # `POST /_matrix/client/r0/search` /// # `POST /_matrix/client/r0/search`
/// ///
/// Searches rooms for messages. /// Searches rooms for messages.
/// ///
/// - Only works if the user is currently joined to the room (TODO: Respect /// - Only works if the user is currently joined to the room (TODO: Respect history visibility)
/// history visibility) pub async fn search_events_route(
pub async fn search_events_route(body: Ruma<search_events::v3::Request>) -> Result<search_events::v3::Response> { body: Ruma<search_events::v3::Request>,
) -> Result<search_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let search_criteria = body.search_categories.room_events.as_ref().unwrap(); let search_criteria = body.search_categories.room_events.as_ref().unwrap();
let filter = &search_criteria.filter; let filter = &search_criteria.filter;
let room_ids = filter.rooms.clone().unwrap_or_else(|| { let room_ids = filter.rooms.clone().unwrap_or_else(|| {
services().rooms.state_cache.rooms_joined(sender_user).filter_map(std::result::Result::ok).collect() services()
.rooms
.state_cache
.rooms_joined(sender_user)
.filter_map(|r| r.ok())
.collect()
}); });
// Use limit or else 10, with maximum 100 // Use limit or else 10, with maximum 100
@@ -32,21 +37,34 @@ pub async fn search_events_route(body: Ruma<search_events::v3::Request>) -> Resu
let mut searches = Vec::new(); let mut searches = Vec::new();
for room_id in room_ids { for room_id in room_ids {
if !services().rooms.state_cache.is_joined(sender_user, &room_id)? { if !services()
.rooms
.state_cache
.is_joined(sender_user, &room_id)?
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"You don't have permission to view this room.", "You don't have permission to view this room.",
)); ));
} }
if let Some(search) = services().rooms.search.search_pdus(&room_id, &search_criteria.search_term)? { if let Some(search) = services()
.rooms
.search
.search_pdus(&room_id, &search_criteria.search_term)?
{
searches.push(search.0.peekable()); searches.push(search.0.peekable());
} }
} }
let skip = match body.next_batch.as_ref().map(|s| s.parse()) { let skip = match body.next_batch.as_ref().map(|s| s.parse()) {
Some(Ok(s)) => s, Some(Ok(s)) => s,
Some(Err(_)) => return Err(Error::BadRequest(ErrorKind::InvalidParam, "Invalid next_batch token.")), Some(Err(_)) => {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid next_batch token.",
))
}
None => 0, // Default to the start None => 0, // Default to the start
}; };
@@ -92,7 +110,7 @@ pub async fn search_events_route(body: Ruma<search_events::v3::Request>) -> Resu
result: Some(result), result: Some(result),
}) })
}) })
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.skip(skip) .skip(skip)
.take(limit) .take(limit)
.collect(); .collect();
+89 -68
View File
@@ -1,12 +1,11 @@
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{services, utils, Error, Result, Ruma};
use argon2::{PasswordHash, PasswordVerifier}; use argon2::{PasswordHash, PasswordVerifier};
use ruma::{ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
session::{ session::{
get_login_types::{ get_login_types,
self,
v3::{ApplicationServiceLoginType, PasswordLoginType},
},
login::{ login::{
self, self,
v3::{DiscoveryInfo, HomeserverInfo}, v3::{DiscoveryInfo, HomeserverInfo},
@@ -20,9 +19,6 @@ use ruma::{
use serde::Deserialize; use serde::Deserialize;
use tracing::{debug, error, info, warn}; use tracing::{debug, error, info, warn};
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
use crate::{services, utils, Error, Result, Ruma};
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct Claims { struct Claims {
sub: String, sub: String,
@@ -31,28 +27,27 @@ struct Claims {
/// # `GET /_matrix/client/v3/login` /// # `GET /_matrix/client/v3/login`
/// ///
/// Get the supported login types of this server. One of these should be used as /// Get the supported login types of this server. One of these should be used as the `type` field
/// the `type` field when logging in. /// when logging in.
pub async fn get_login_types_route(_body: Ruma<get_login_types::v3::Request>) -> Result<get_login_types::v3::Response> { pub async fn get_login_types_route(
_body: Ruma<get_login_types::v3::Request>,
) -> Result<get_login_types::v3::Response> {
Ok(get_login_types::v3::Response::new(vec![ Ok(get_login_types::v3::Response::new(vec![
get_login_types::v3::LoginType::Password(PasswordLoginType::default()), get_login_types::v3::LoginType::Password(Default::default()),
get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()), get_login_types::v3::LoginType::ApplicationService(Default::default()),
])) ]))
} }
/// # `POST /_matrix/client/v3/login` /// # `POST /_matrix/client/v3/login`
/// ///
/// Authenticates the user and returns an access token it can use in subsequent /// Authenticates the user and returns an access token it can use in subsequent requests.
/// requests.
/// ///
/// - The user needs to authenticate using their password (or if enabled using a /// - The user needs to authenticate using their password (or if enabled using a json web token)
/// json web token)
/// - If `device_id` is known: invalidates old access token of that device /// - If `device_id` is known: invalidates old access token of that device
/// - If `device_id` is unknown: creates a new device /// - If `device_id` is unknown: creates a new device
/// - Returns access token that is associated with the user and device /// - Returns access token that is associated with the user and device
/// ///
/// Note: You can use [`GET /// Note: You can use [`GET /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see
/// /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see
/// supported login types. /// supported login types.
pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Response> { pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Response> {
// Validate login method // Validate login method
@@ -70,19 +65,16 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
debug!("Using username from identifier field"); debug!("Using username from identifier field");
user_id.to_lowercase() user_id.to_lowercase()
} else if let Some(user_id) = user { } else if let Some(user_id) = user {
warn!( warn!("User \"{}\" is attempting to login with the deprecated \"user\" field at \"/_matrix/client/v3/login\". conduwuit implements this deprecated behaviour, but this is destined to be removed in a future Matrix release.", user_id);
"User \"{}\" is attempting to login with the deprecated \"user\" field at \
\"/_matrix/client/v3/login\". conduwuit implements this deprecated behaviour, but this is \
destined to be removed in a future Matrix release.",
user_id
);
user_id.to_lowercase() user_id.to_lowercase()
} else { } else {
warn!("Bad login type: {:?}", &body.login_info); warn!("Bad login type: {:?}", &body.login_info);
return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type.")); return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type."));
}; };
let user_id = UserId::parse_with_server_name(username, services().globals.server_name()).map_err(|e| { let user_id =
UserId::parse_with_server_name(username, services().globals.server_name())
.map_err(|e| {
warn!("Failed to parse username from user logging in: {}", e); warn!("Failed to parse username from user logging in: {}", e);
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.") Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?; })?;
@@ -90,10 +82,16 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
let hash = services() let hash = services()
.users .users
.password_hash(&user_id)? .password_hash(&user_id)?
.ok_or(Error::BadRequest(ErrorKind::Forbidden, "Wrong username or password."))?; .ok_or(Error::BadRequest(
ErrorKind::Forbidden,
"Wrong username or password.",
))?;
if hash.is_empty() { if hash.is_empty() {
return Err(Error::BadRequest(ErrorKind::UserDeactivated, "The user has been deactivated")); return Err(Error::BadRequest(
ErrorKind::UserDeactivated,
"The user has been deactivated",
));
} }
let Ok(parsed_hash) = PasswordHash::new(&hash) else { let Ok(parsed_hash) = PasswordHash::new(&hash) else {
@@ -101,21 +99,29 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
return Err(Error::BadServerResponse("could not hash")); return Err(Error::BadServerResponse("could not hash"));
}; };
let hash_matches = services().globals.argon.verify_password(password.as_bytes(), &parsed_hash).is_ok(); let hash_matches = services()
.globals
.argon
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok();
if !hash_matches { if !hash_matches {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Wrong username or password.")); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Wrong username or password.",
));
} }
user_id user_id
}, }
login::v3::LoginInfo::Token(login::v3::Token { login::v3::LoginInfo::Token(login::v3::Token { token }) => {
token,
}) => {
debug!("Got token login type"); debug!("Got token login type");
if let Some(jwt_decoding_key) = services().globals.jwt_decoding_key() { if let Some(jwt_decoding_key) = services().globals.jwt_decoding_key() {
let token = let token = jsonwebtoken::decode::<Claims>(
jsonwebtoken::decode::<Claims>(token, jwt_decoding_key, &jsonwebtoken::Validation::default()) token,
jwt_decoding_key,
&jsonwebtoken::Validation::default(),
)
.map_err(|e| { .map_err(|e| {
warn!("Failed to parse JWT token from user logging in: {}", e); warn!("Failed to parse JWT token from user logging in: {}", e);
Error::BadRequest(ErrorKind::InvalidUsername, "Token is invalid.") Error::BadRequest(ErrorKind::InvalidUsername, "Token is invalid.")
@@ -123,17 +129,19 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
let username = token.claims.sub.to_lowercase(); let username = token.claims.sub.to_lowercase();
UserId::parse_with_server_name(username, services().globals.server_name()).map_err(|e| { UserId::parse_with_server_name(username, services().globals.server_name()).map_err(
|e| {
warn!("Failed to parse username from user logging in: {}", e); warn!("Failed to parse username from user logging in: {}", e);
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.") Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})? },
)?
} else { } else {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Unknown, ErrorKind::Unknown,
"Token login is not supported (server has no jwt decoding key).", "Token login is not supported (server has no jwt decoding key).",
)); ));
} }
}, }
#[allow(deprecated)] #[allow(deprecated)]
login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService { login::v3::LoginInfo::ApplicationService(login::v3::ApplicationService {
identifier, identifier,
@@ -141,65 +149,79 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
}) => { }) => {
debug!("Got appservice login type"); debug!("Got appservice login type");
if !body.from_appservice { if !body.from_appservice {
info!( info!("User tried logging in as an appservice, but request body is not from a known/registered appservice");
"User tried logging in as an appservice, but request body is not from a known/registered \ return Err(Error::BadRequest(
appservice" ErrorKind::Forbidden,
); "Forbidden login type.",
return Err(Error::BadRequest(ErrorKind::Forbidden, "Forbidden login type.")); ));
}; };
let username = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier { let username = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
user_id.to_lowercase() user_id.to_lowercase()
} else if let Some(user_id) = user { } else if let Some(user_id) = user {
warn!( warn!("Appservice \"{}\" is attempting to login with the deprecated \"user\" field at \"/_matrix/client/v3/login\". conduwuit implements this deprecated behaviour, but this is destined to be removed in a future Matrix release.", user_id);
"Appservice \"{}\" is attempting to login with the deprecated \"user\" field at \
\"/_matrix/client/v3/login\". conduwuit implements this deprecated behaviour, but this is \
destined to be removed in a future Matrix release.",
user_id
);
user_id.to_lowercase() user_id.to_lowercase()
} else { } else {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type.")); return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type."));
}; };
UserId::parse_with_server_name(username, services().globals.server_name()).map_err(|e| { UserId::parse_with_server_name(username, services().globals.server_name()).map_err(
|e| {
warn!("Failed to parse username from appservice logging in: {}", e); warn!("Failed to parse username from appservice logging in: {}", e);
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.") Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?
}, },
)?
}
_ => { _ => {
warn!("Unsupported or unknown login type: {:?}", &body.login_info); warn!("Unsupported or unknown login type: {:?}", &body.login_info);
debug!("JSON body: {:?}", &body.json_body); debug!("JSON body: {:?}", &body.json_body);
return Err(Error::BadRequest(ErrorKind::Unknown, "Unsupported or unknown login type.")); return Err(Error::BadRequest(
}, ErrorKind::Unknown,
"Unsupported or unknown login type.",
));
}
}; };
// Generate new device id if the user didn't specify one // Generate new device id if the user didn't specify one
let device_id = body.device_id.clone().unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into()); let device_id = body
.device_id
.clone()
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
// Generate a new token for the device // Generate a new token for the device
let token = utils::random_string(TOKEN_LENGTH); let token = utils::random_string(TOKEN_LENGTH);
// Determine if device_id was provided and exists in the db for this user // Determine if device_id was provided and exists in the db for this user
let device_exists = body.device_id.as_ref().map_or(false, |device_id| { let device_exists = body.device_id.as_ref().map_or(false, |device_id| {
services().users.all_device_ids(&user_id).any(|x| x.as_ref().map_or(false, |v| v == device_id)) services()
.users
.all_device_ids(&user_id)
.any(|x| x.as_ref().map_or(false, |v| v == device_id))
}); });
if device_exists { if device_exists {
services().users.set_token(&user_id, &device_id, &token)?; services().users.set_token(&user_id, &device_id, &token)?;
} else { } else {
services().users.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?; services().users.create_device(
&user_id,
&device_id,
&token,
body.initial_device_display_name.clone(),
)?;
} }
// send client well-known if specified so the client knows to reconfigure itself // send client well-known if specified so the client knows to reconfigure itself
let client_discovery_info = DiscoveryInfo::new(HomeserverInfo::new( let client_discovery_info = DiscoveryInfo::new(HomeserverInfo::new(
services().globals.well_known_client().to_owned().unwrap_or_else(|| "".to_owned()), services()
.globals
.well_known_client()
.to_owned()
.unwrap_or("".to_owned()),
)); ));
info!("{} logged in", user_id); info!("{} logged in", user_id);
// home_server is deprecated but apparently must still be sent despite it being // home_server is deprecated but apparently must still be sent despite it being deprecated over 6 years ago.
// deprecated over 6 years ago. initially i thought this macro was unnecessary, // initially i thought this macro was unnecessary, but ruma uses this same macro for the same reason so...
// but ruma uses this same macro for the same reason so...
#[allow(deprecated)] #[allow(deprecated)]
Ok(login::v3::Response { Ok(login::v3::Response {
user_id, user_id,
@@ -223,8 +245,7 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
/// Log out the current device. /// Log out the current device.
/// ///
/// - Invalidates access token /// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, /// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets to-device events /// - Forgets to-device events
/// - Triggers device list updates /// - Triggers device list updates
pub async fn logout_route(body: Ruma<logout::v3::Request>) -> Result<logout::v3::Response> { pub async fn logout_route(body: Ruma<logout::v3::Request>) -> Result<logout::v3::Response> {
@@ -244,15 +265,15 @@ pub async fn logout_route(body: Ruma<logout::v3::Request>) -> Result<logout::v3:
/// Log out all devices of this user. /// Log out all devices of this user.
/// ///
/// - Invalidates all access tokens /// - Invalidates all access tokens
/// - Deletes all device metadata (device id, device display name, last seen ip, /// - Deletes all device metadata (device id, device display name, last seen ip, last seen ts)
/// last seen ts)
/// - Forgets all to-device events /// - Forgets all to-device events
/// - Triggers device list updates /// - Triggers device list updates
/// ///
/// Note: This is equivalent to calling [`GET /// Note: This is equivalent to calling [`GET /_matrix/client/r0/logout`](fn.logout_route.html)
/// /_matrix/client/r0/logout`](fn.logout_route.html) from each device of this /// from each device of this user.
/// user. pub async fn logout_all_route(
pub async fn logout_all_route(body: Ruma<logout_all::v3::Request>) -> Result<logout_all::v3::Response> { body: Ruma<logout_all::v3::Request>,
) -> Result<logout_all::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
for device_id in services().users.all_device_ids(sender_user).flatten() { for device_id in services().users.all_device_ids(sender_user).flatten() {
+17 -28
View File
@@ -1,44 +1,33 @@
use std::str::FromStr; use crate::{services, Result, Ruma};
use ruma::api::client::space::get_hierarchy;
use ruma::{
api::client::{error::ErrorKind, space::get_hierarchy},
UInt,
};
use crate::{service::rooms::spaces::PagnationToken, services, Error, Result, Ruma};
/// # `GET /_matrix/client/v1/rooms/{room_id}/hierarchy`` /// # `GET /_matrix/client/v1/rooms/{room_id}/hierarchy``
/// ///
/// Paginates over the space tree in a depth-first manner to locate child rooms /// Paginates over the space tree in a depth-first manner to locate child rooms of a given space.
/// of a given space. pub async fn get_hierarchy_route(
pub async fn get_hierarchy_route(body: Ruma<get_hierarchy::v1::Request>) -> Result<get_hierarchy::v1::Response> { body: Ruma<get_hierarchy::v1::Request>,
) -> Result<get_hierarchy::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let limit = body.limit.unwrap_or_else(|| UInt::from(10_u32)).min(UInt::from(100_u32)); let skip = body
.from
.as_ref()
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(0);
let max_depth = body.max_depth.unwrap_or_else(|| UInt::from(3_u32)).min(UInt::from(10_u32)); let limit = body.limit.map_or(10, u64::from).min(100) as usize;
let key = body.from.as_ref().and_then(|s| PagnationToken::from_str(s).ok()); let max_depth = body.max_depth.map_or(3, u64::from).min(10) as usize + 1; // +1 to skip the space room itself
// Should prevent unexpeded behaviour in (bad) clients
if let Some(ref token) = key {
if token.suggested_only != body.suggested_only || token.max_depth != max_depth {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"suggested_only and max_depth cannot change on paginated requests",
));
}
}
services() services()
.rooms .rooms
.spaces .spaces
.get_client_hierarchy( .get_hierarchy(
sender_user, sender_user,
&body.room_id, &body.room_id,
u64::from(limit) as usize, limit,
key.map_or(0, |token| u64::from(token.skip) as usize), skip,
u64::from(max_depth) as usize, max_depth,
body.suggested_only, body.suggested_only,
) )
.await .await
+87 -49
View File
@@ -1,25 +1,25 @@
use std::sync::Arc; use std::sync::Arc;
use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma, RumaResponse};
use ruma::{ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
state::{get_state_events, get_state_events_for_key, send_state_event}, state::{get_state_events, get_state_events_for_key, send_state_event},
}, },
events::{room::canonical_alias::RoomCanonicalAliasEventContent, AnyStateEventContent, StateEventType}, events::{
room::canonical_alias::RoomCanonicalAliasEventContent, AnyStateEventContent, StateEventType,
},
serde::Raw, serde::Raw,
EventId, RoomId, UserId, EventId, RoomId, UserId,
}; };
use tracing::{error, log::warn}; use tracing::{error, log::warn};
use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma, RumaResponse};
/// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}` /// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}`
/// ///
/// Sends a state event into the room. /// Sends a state event into the room.
/// ///
/// - The only requirement for the content is that it has to be valid json /// - The only requirement for the content is that it has to be valid json
/// - Tries to send the event into the room, auth rules will determine if it is /// - Tries to send the event into the room, auth rules will determine if it is allowed
/// allowed
/// - If event is new canonical_alias: Rejects if alias is incorrect /// - If event is new canonical_alias: Rejects if alias is incorrect
pub async fn send_state_event_for_key_route( pub async fn send_state_event_for_key_route(
body: Ruma<send_state_event::v3::Request>, body: Ruma<send_state_event::v3::Request>,
@@ -31,14 +31,12 @@ pub async fn send_state_event_for_key_route(
&body.room_id, &body.room_id,
&body.event_type, &body.event_type,
&body.body.body, // Yes, I hate it too &body.body.body, // Yes, I hate it too
body.state_key.clone(), body.state_key.to_owned(),
) )
.await?; .await?;
let event_id = (*event_id).to_owned(); let event_id = (*event_id).to_owned();
Ok(send_state_event::v3::Response { Ok(send_state_event::v3::Response { event_id })
event_id,
})
} }
/// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}` /// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}`
@@ -46,8 +44,7 @@ pub async fn send_state_event_for_key_route(
/// Sends a state event into the room. /// Sends a state event into the room.
/// ///
/// - The only requirement for the content is that it has to be valid json /// - The only requirement for the content is that it has to be valid json
/// - Tries to send the event into the room, auth rules will determine if it is /// - Tries to send the event into the room, auth rules will determine if it is allowed
/// allowed
/// - If event is new canonical_alias: Rejects if alias is incorrect /// - If event is new canonical_alias: Rejects if alias is incorrect
pub async fn send_state_event_for_empty_key_route( pub async fn send_state_event_for_empty_key_route(
body: Ruma<send_state_event::v3::Request>, body: Ruma<send_state_event::v3::Request>,
@@ -56,7 +53,10 @@ pub async fn send_state_event_for_empty_key_route(
// Forbid m.room.encryption if encryption is disabled // Forbid m.room.encryption if encryption is disabled
if body.event_type == StateEventType::RoomEncryption && !services().globals.allow_encryption() { if body.event_type == StateEventType::RoomEncryption && !services().globals.allow_encryption() {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Encryption has been disabled")); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Encryption has been disabled",
));
} }
let event_id = send_state_event_for_key_helper( let event_id = send_state_event_for_key_helper(
@@ -64,29 +64,29 @@ pub async fn send_state_event_for_empty_key_route(
&body.room_id, &body.room_id,
&body.event_type.to_string().into(), &body.event_type.to_string().into(),
&body.body.body, &body.body.body,
body.state_key.clone(), body.state_key.to_owned(),
) )
.await?; .await?;
let event_id = (*event_id).to_owned(); let event_id = (*event_id).to_owned();
Ok(send_state_event::v3::Response { Ok(send_state_event::v3::Response { event_id }.into())
event_id,
}
.into())
} }
/// # `GET /_matrix/client/v3/rooms/{roomid}/state` /// # `GET /_matrix/client/r0/rooms/{roomid}/state`
/// ///
/// Get all state events for a room. /// Get all state events for a room.
/// ///
/// - If not joined: Only works if current room history visibility is world /// - If not joined: Only works if current room history visibility is world readable
/// readable
pub async fn get_state_events_route( pub async fn get_state_events_route(
body: Ruma<get_state_events::v3::Request>, body: Ruma<get_state_events::v3::Request>,
) -> Result<get_state_events::v3::Response> { ) -> Result<get_state_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_accessor.user_can_see_state_events(sender_user, &body.room_id)? { if !services()
.rooms
.state_accessor
.user_can_see_state_events(sender_user, &body.room_id)?
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"You don't have permission to view the room state.", "You don't have permission to view the room state.",
@@ -108,31 +108,42 @@ pub async fn get_state_events_route(
/// # `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}/{stateKey}` /// # `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}/{stateKey}`
/// ///
/// Get single state event of a room with the specified state key. /// Get single state event of a room with the specified state key.
/// The optional query parameter `?format=event|content` allows returning the /// The optional query parameter `?format=event|content` allows returning the full room state event
/// full room state event or just the state event's content (default behaviour) /// or just the state event's content (default behaviour)
/// ///
/// - If not joined: Only works if current room history visibility is world /// - If not joined: Only works if current room history visibility is world readable
/// readable
pub async fn get_state_events_for_key_route( pub async fn get_state_events_for_key_route(
body: Ruma<get_state_events_for_key::v3::Request>, body: Ruma<get_state_events_for_key::v3::Request>,
) -> Result<get_state_events_for_key::v3::Response> { ) -> Result<get_state_events_for_key::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_accessor.user_can_see_state_events(sender_user, &body.room_id)? { if !services()
.rooms
.state_accessor
.user_can_see_state_events(sender_user, &body.room_id)?
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"You don't have permission to view the room state.", "You don't have permission to view the room state.",
)); ));
} }
let event = let event = services()
services().rooms.state_accessor.room_state_get(&body.room_id, &body.event_type, &body.state_key)?.ok_or_else( .rooms
|| { .state_accessor
warn!("State event {:?} not found in room {:?}", &body.event_type, &body.room_id); .room_state_get(&body.room_id, &body.event_type, &body.state_key)?
.ok_or_else(|| {
warn!(
"State event {:?} not found in room {:?}",
&body.event_type, &body.room_id
);
Error::BadRequest(ErrorKind::NotFound, "State event not found.") Error::BadRequest(ErrorKind::NotFound, "State event not found.")
}, })?;
)?; if body
if body.format.as_ref().is_some_and(|f| f.to_lowercase().eq("event")) { .format
.as_ref()
.is_some_and(|f| f.to_lowercase().eq("event"))
{
Ok(get_state_events_for_key::v3::Response { Ok(get_state_events_for_key::v3::Response {
content: None, content: None,
event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| { event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| {
@@ -154,30 +165,43 @@ pub async fn get_state_events_for_key_route(
/// # `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}` /// # `GET /_matrix/client/v3/rooms/{roomid}/state/{eventType}`
/// ///
/// Get single state event of a room. /// Get single state event of a room.
/// The optional query parameter `?format=event|content` allows returning the /// The optional query parameter `?format=event|content` allows returning the full room state event
/// full room state event or just the state event's content (default behaviour) /// or just the state event's content (default behaviour)
/// ///
/// - If not joined: Only works if current room history visibility is world /// - If not joined: Only works if current room history visibility is world readable
/// readable
pub async fn get_state_events_for_empty_key_route( pub async fn get_state_events_for_empty_key_route(
body: Ruma<get_state_events_for_key::v3::Request>, body: Ruma<get_state_events_for_key::v3::Request>,
) -> Result<RumaResponse<get_state_events_for_key::v3::Response>> { ) -> Result<RumaResponse<get_state_events_for_key::v3::Response>> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_accessor.user_can_see_state_events(sender_user, &body.room_id)? { if !services()
.rooms
.state_accessor
.user_can_see_state_events(sender_user, &body.room_id)?
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"You don't have permission to view the room state.", "You don't have permission to view the room state.",
)); ));
} }
let event = let event = services()
services().rooms.state_accessor.room_state_get(&body.room_id, &body.event_type, "")?.ok_or_else(|| { .rooms
warn!("State event {:?} not found in room {:?}", &body.event_type, &body.room_id); .state_accessor
.room_state_get(&body.room_id, &body.event_type, "")?
.ok_or_else(|| {
warn!(
"State event {:?} not found in room {:?}",
&body.event_type, &body.room_id
);
Error::BadRequest(ErrorKind::NotFound, "State event not found.") Error::BadRequest(ErrorKind::NotFound, "State event not found.")
})?; })?;
if body.format.as_ref().is_some_and(|f| f.to_lowercase().eq("event")) { if body
.format
.as_ref()
.is_some_and(|f| f.to_lowercase().eq("event"))
{
Ok(get_state_events_for_key::v3::Response { Ok(get_state_events_for_key::v3::Response {
content: None, content: None,
event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| { event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| {
@@ -199,13 +223,19 @@ pub async fn get_state_events_for_empty_key_route(
} }
async fn send_state_event_for_key_helper( async fn send_state_event_for_key_helper(
sender: &UserId, room_id: &RoomId, event_type: &StateEventType, json: &Raw<AnyStateEventContent>, state_key: String, sender: &UserId,
room_id: &RoomId,
event_type: &StateEventType,
json: &Raw<AnyStateEventContent>,
state_key: String,
) -> Result<Arc<EventId>> { ) -> Result<Arc<EventId>> {
let sender_user = sender; let sender_user = sender;
// TODO: Review this check, error if event is unparsable, use event type, allow // TODO: Review this check, error if event is unparsable, use event type, allow alias if it
// alias if it previously existed // previously existed
if let Ok(canonical_alias) = serde_json::from_str::<RoomCanonicalAliasEventContent>(json.json().get()) { if let Ok(canonical_alias) =
serde_json::from_str::<RoomCanonicalAliasEventContent>(json.json().get())
{
let mut aliases = canonical_alias.alt_aliases.clone(); let mut aliases = canonical_alias.alt_aliases.clone();
if let Some(alias) = canonical_alias.alias { if let Some(alias) = canonical_alias.alias {
@@ -223,14 +253,22 @@ async fn send_state_event_for_key_helper(
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"You are only allowed to send canonical_alias events when it's aliases already exists", "You are only allowed to send canonical_alias \
events when it's aliases already exists",
)); ));
} }
} }
} }
let mutex_state = let mutex_state = Arc::clone(
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.to_owned()).or_default()); services()
.globals
.roomid_mutex_state
.write()
.unwrap()
.entry(room_id.to_owned())
.or_default(),
);
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
let event_id = services() let event_id = services()
File diff suppressed because it is too large Load Diff
+39 -13
View File
@@ -1,5 +1,4 @@
use std::collections::BTreeMap; use crate::{services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::client::tag::{create_tag, delete_tag, get_tags}, api::client::tag::{create_tag, delete_tag, get_tags},
events::{ events::{
@@ -7,21 +6,29 @@ use ruma::{
RoomAccountDataEventType, RoomAccountDataEventType,
}, },
}; };
use std::collections::BTreeMap;
use crate::{services, Error, Result, Ruma};
/// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}` /// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}`
/// ///
/// Adds a tag to the room. /// Adds a tag to the room.
/// ///
/// - Inserts the tag into the tag event of the room account data. /// - Inserts the tag into the tag event of the room account data.
pub async fn update_tag_route(body: Ruma<create_tag::v3::Request>) -> Result<create_tag::v3::Response> { pub async fn update_tag_route(
body: Ruma<create_tag::v3::Request>,
) -> Result<create_tag::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services().account_data.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?; let event = services().account_data.get(
Some(&body.room_id),
sender_user,
RoomAccountDataEventType::Tag,
)?;
let mut tags_event = event let mut tags_event = event
.map(|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db."))) .map(|e| {
serde_json::from_str(e.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))
})
.unwrap_or_else(|| { .unwrap_or_else(|| {
Ok(TagEvent { Ok(TagEvent {
content: TagEventContent { content: TagEventContent {
@@ -30,7 +37,10 @@ pub async fn update_tag_route(body: Ruma<create_tag::v3::Request>) -> Result<cre
}) })
})?; })?;
tags_event.content.tags.insert(body.tag.clone().into(), body.tag_info.clone()); tags_event
.content
.tags
.insert(body.tag.clone().into(), body.tag_info.clone());
services().account_data.update( services().account_data.update(
Some(&body.room_id), Some(&body.room_id),
@@ -47,13 +57,22 @@ pub async fn update_tag_route(body: Ruma<create_tag::v3::Request>) -> Result<cre
/// Deletes a tag from the room. /// Deletes a tag from the room.
/// ///
/// - Removes the tag from the tag event of the room account data. /// - Removes the tag from the tag event of the room account data.
pub async fn delete_tag_route(body: Ruma<delete_tag::v3::Request>) -> Result<delete_tag::v3::Response> { pub async fn delete_tag_route(
body: Ruma<delete_tag::v3::Request>,
) -> Result<delete_tag::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services().account_data.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?; let event = services().account_data.get(
Some(&body.room_id),
sender_user,
RoomAccountDataEventType::Tag,
)?;
let mut tags_event = event let mut tags_event = event
.map(|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db."))) .map(|e| {
serde_json::from_str(e.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))
})
.unwrap_or_else(|| { .unwrap_or_else(|| {
Ok(TagEvent { Ok(TagEvent {
content: TagEventContent { content: TagEventContent {
@@ -82,10 +101,17 @@ pub async fn delete_tag_route(body: Ruma<delete_tag::v3::Request>) -> Result<del
pub async fn get_tags_route(body: Ruma<get_tags::v3::Request>) -> Result<get_tags::v3::Response> { pub async fn get_tags_route(body: Ruma<get_tags::v3::Request>) -> Result<get_tags::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services().account_data.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?; let event = services().account_data.get(
Some(&body.room_id),
sender_user,
RoomAccountDataEventType::Tag,
)?;
let tags_event = event let tags_event = event
.map(|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db."))) .map(|e| {
serde_json::from_str(e.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))
})
.unwrap_or_else(|| { .unwrap_or_else(|| {
Ok(TagEvent { Ok(TagEvent {
content: TagEventContent { content: TagEventContent {
+5 -4
View File
@@ -1,13 +1,14 @@
use std::collections::BTreeMap; use crate::{Result, Ruma};
use ruma::api::client::thirdparty::get_protocols; use ruma::api::client::thirdparty::get_protocols;
use crate::{Result, Ruma}; use std::collections::BTreeMap;
/// # `GET /_matrix/client/r0/thirdparty/protocols` /// # `GET /_matrix/client/r0/thirdparty/protocols`
/// ///
/// TODO: Fetches all metadata about protocols supported by the homeserver. /// TODO: Fetches all metadata about protocols supported by the homeserver.
pub async fn get_protocols_route(_body: Ruma<get_protocols::v3::Request>) -> Result<get_protocols::v3::Response> { pub async fn get_protocols_route(
_body: Ruma<get_protocols::v3::Request>,
) -> Result<get_protocols::v3::Response> {
// TODO // TODO
Ok(get_protocols::v3::Response { Ok(get_protocols::v3::Response {
protocols: BTreeMap::new(), protocols: BTreeMap::new(),
+15 -5
View File
@@ -3,14 +3,21 @@ use ruma::api::client::{error::ErrorKind, threads::get_threads};
use crate::{services, Error, Result, Ruma}; use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/r0/rooms/{roomId}/threads` /// # `GET /_matrix/client/r0/rooms/{roomId}/threads`
pub async fn get_threads_route(body: Ruma<get_threads::v1::Request>) -> Result<get_threads::v1::Response> { pub async fn get_threads_route(
body: Ruma<get_threads::v1::Request>,
) -> Result<get_threads::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
// Use limit or else 10, with maximum 100 // Use limit or else 10, with maximum 100
let limit = body.limit.and_then(|l| l.try_into().ok()).unwrap_or(10).min(100); let limit = body
.limit
.and_then(|l| l.try_into().ok())
.unwrap_or(10)
.min(100);
let from = if let Some(from) = &body.from { let from = if let Some(from) = &body.from {
from.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, ""))? from.parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, ""))?
} else { } else {
u64::MAX u64::MAX
}; };
@@ -20,7 +27,7 @@ pub async fn get_threads_route(body: Ruma<get_threads::v1::Request>) -> Result<g
.threads .threads
.threads_until(sender_user, &body.room_id, from, &body.include)? .threads_until(sender_user, &body.room_id, from, &body.include)?
.take(limit) .take(limit)
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
@@ -33,7 +40,10 @@ pub async fn get_threads_route(body: Ruma<get_threads::v1::Request>) -> Result<g
let next_batch = threads.last().map(|(count, _)| count.to_string()); let next_batch = threads.last().map(|(count, _)| count.to_string());
Ok(get_threads::v1::Response { Ok(get_threads::v1::Response {
chunk: threads.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect(), chunk: threads
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect(),
next_batch, next_batch,
}) })
} }
+22 -15
View File
@@ -1,5 +1,6 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use crate::{services, Error, Result, Ruma};
use ruma::{ use ruma::{
api::{ api::{
client::{error::ErrorKind, to_device::send_event_to_device}, client::{error::ErrorKind, to_device::send_event_to_device},
@@ -8,8 +9,6 @@ use ruma::{
to_device::DeviceIdOrAllDevices, to_device::DeviceIdOrAllDevices,
}; };
use crate::{services, Error, Result, Ruma};
/// # `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}` /// # `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}`
/// ///
/// Send a to-device event to a set of client devices. /// Send a to-device event to a set of client devices.
@@ -20,7 +19,11 @@ pub async fn send_event_to_device_route(
let sender_device = body.sender_device.as_deref(); let sender_device = body.sender_device.as_deref();
// Check if this is a new transaction id // Check if this is a new transaction id
if services().transaction_ids.existing_txnid(sender_user, sender_device, &body.txn_id)?.is_some() { if services()
.transaction_ids
.existing_txnid(sender_user, sender_device, &body.txn_id)?
.is_some()
{
return Ok(send_event_to_device::v3::Response {}); return Ok(send_event_to_device::v3::Response {});
} }
@@ -35,12 +38,14 @@ pub async fn send_event_to_device_route(
services().sending.send_reliable_edu( services().sending.send_reliable_edu(
target_user_id.server_name(), target_user_id.server_name(),
serde_json::to_vec(&federation::transactions::edu::Edu::DirectToDevice(DirectDeviceContent { serde_json::to_vec(&federation::transactions::edu::Edu::DirectToDevice(
DirectDeviceContent {
sender: sender_user.clone(), sender: sender_user.clone(),
ev_type: body.event_type.clone(), ev_type: body.event_type.clone(),
message_id: count.to_string().into(), message_id: count.to_string().into(),
messages, messages,
})) },
))
.expect("DirectToDevice EDU can be serialized"), .expect("DirectToDevice EDU can be serialized"),
count, count,
)?; )?;
@@ -55,11 +60,11 @@ pub async fn send_event_to_device_route(
target_user_id, target_user_id,
target_device_id, target_device_id,
&body.event_type.to_string(), &body.event_type.to_string(),
event event.deserialize_as().map_err(|_| {
.deserialize_as() Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid"))?, })?,
)?; )?
}, }
DeviceIdOrAllDevices::AllDevices => { DeviceIdOrAllDevices::AllDevices => {
for target_device_id in services().users.all_device_ids(target_user_id) { for target_device_id in services().users.all_device_ids(target_user_id) {
@@ -68,18 +73,20 @@ pub async fn send_event_to_device_route(
target_user_id, target_user_id,
&target_device_id?, &target_device_id?,
&body.event_type.to_string(), &body.event_type.to_string(),
event event.deserialize_as().map_err(|_| {
.deserialize_as() Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid"))?, })?,
)?; )?;
} }
}, }
} }
} }
} }
// Save transaction id with empty data // Save transaction id with empty data
services().transaction_ids.add_txnid(sender_user, sender_device, &body.txn_id, &[])?; services()
.transaction_ids
.add_txnid(sender_user, sender_device, &body.txn_id, &[])?;
Ok(send_event_to_device::v3::Response {}) Ok(send_event_to_device::v3::Response {})
} }
+17 -12
View File
@@ -1,6 +1,5 @@
use ruma::api::client::{error::ErrorKind, typing::create_typing_event};
use crate::{services, utils, Error, Result, Ruma}; use crate::{services, utils, Error, Result, Ruma};
use ruma::api::client::{error::ErrorKind, typing::create_typing_event};
/// # `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}` /// # `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}`
/// ///
@@ -12,23 +11,29 @@ pub async fn create_typing_event_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_cache.is_joined(sender_user, &body.room_id)? { if !services()
return Err(Error::BadRequest(ErrorKind::Forbidden, "You are not in this room.")); .rooms
.state_cache
.is_joined(sender_user, &body.room_id)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"You are not in this room.",
));
} }
if let Typing::Yes(duration) = body.state { if let Typing::Yes(duration) = body.state {
services().rooms.edus.typing.typing_add(
sender_user,
&body.room_id,
duration.as_millis() as u64 + utils::millis_since_unix_epoch(),
)?;
} else {
services() services()
.rooms .rooms
.edus .edus
.typing .typing
.typing_add( .typing_remove(sender_user, &body.room_id)?;
sender_user,
&body.room_id,
duration.as_millis() as u64 + utils::millis_since_unix_epoch(),
)
.await?;
} else {
services().rooms.edus.typing.typing_remove(sender_user, &body.room_id).await?;
} }
Ok(create_typing_event::v3::Response {}) Ok(create_typing_event::v3::Response {})
+7 -9
View File
@@ -1,4 +1,4 @@
use std::collections::BTreeMap; use std::{collections::BTreeMap, iter::FromIterator};
use axum::{response::IntoResponse, Json}; use axum::{response::IntoResponse, Json};
use ruma::api::client::{discovery::get_supported_versions, error::ErrorKind}; use ruma::api::client::{discovery::get_supported_versions, error::ErrorKind};
@@ -7,16 +7,14 @@ use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/versions` /// # `GET /_matrix/client/versions`
/// ///
/// Get the versions of the specification and unstable features supported by /// Get the versions of the specification and unstable features supported by this server.
/// this server.
/// ///
/// - Versions take the form MAJOR.MINOR.PATCH /// - Versions take the form MAJOR.MINOR.PATCH
/// - Only the latest PATCH release will be reported for each MAJOR.MINOR value /// - Only the latest PATCH release will be reported for each MAJOR.MINOR value
/// - Unstable features are namespaced and may include version information in /// - Unstable features are namespaced and may include version information in their name
/// their name
/// ///
/// Note: Unstable features are used while developing new features. Clients /// Note: Unstable features are used while developing new features. Clients should avoid using
/// should avoid using unstable features in their stable releases /// unstable features in their stable releases
pub async fn get_supported_versions_route( pub async fn get_supported_versions_route(
_body: Ruma<get_supported_versions::Request>, _body: Ruma<get_supported_versions::Request>,
) -> Result<get_supported_versions::Response> { ) -> Result<get_supported_versions::Response> {
@@ -62,8 +60,8 @@ pub async fn well_known_client_route() -> Result<impl IntoResponse> {
/// # `GET /client/server.json` /// # `GET /client/server.json`
/// ///
/// Endpoint provided by sliding sync proxy used by some clients such as Element /// Endpoint provided by sliding sync proxy used by some clients such as Element Web
/// Web as a non-standard health check. /// as a non-standard health check.
pub async fn syncv3_client_server_json() -> Result<impl IntoResponse> { pub async fn syncv3_client_server_json() -> Result<impl IntoResponse> {
let server_url = match services().globals.well_known_client() { let server_url = match services().globals.well_known_client() {
Some(url) => url.clone(), Some(url) => url.clone(),
+42 -33
View File
@@ -1,3 +1,4 @@
use crate::{services, Result, Ruma};
use ruma::{ use ruma::{
api::client::user_directory::search_users, api::client::user_directory::search_users,
events::{ events::{
@@ -6,16 +7,15 @@ use ruma::{
}, },
}; };
use crate::{services, Result, Ruma};
/// # `POST /_matrix/client/r0/user_directory/search` /// # `POST /_matrix/client/r0/user_directory/search`
/// ///
/// Searches all known users for a match. /// Searches all known users for a match.
/// ///
/// - Hides any local users that aren't in any public rooms (i.e. those that /// - Hides any local users that aren't in any public rooms (i.e. those that have the join rule set to public)
/// have the join rule set to public)
/// and don't share a room with the sender /// and don't share a room with the sender
pub async fn search_users_route(body: Ruma<search_users::v3::Request>) -> Result<search_users::v3::Response> { pub async fn search_users_route(
body: Ruma<search_users::v3::Request>,
) -> Result<search_users::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let limit = u64::from(body.limit) as usize; let limit = u64::from(body.limit) as usize;
@@ -29,57 +29,66 @@ pub async fn search_users_route(body: Ruma<search_users::v3::Request>) -> Result
avatar_url: services().users.avatar_url(&user_id).ok()?, avatar_url: services().users.avatar_url(&user_id).ok()?,
}; };
let user_id_matches = user.user_id.to_string().to_lowercase().contains(&body.search_term.to_lowercase()); let user_id_matches = user
.user_id
.to_string()
.to_lowercase()
.contains(&body.search_term.to_lowercase());
let user_displayname_matches = user let user_displayname_matches = user
.display_name .display_name
.as_ref() .as_ref()
.filter(|name| name.to_lowercase().contains(&body.search_term.to_lowercase())) .filter(|name| {
name.to_lowercase()
.contains(&body.search_term.to_lowercase())
})
.is_some(); .is_some();
if !user_id_matches && !user_displayname_matches { if !user_id_matches && !user_displayname_matches {
return None; return None;
} }
// It's a matching user, but is the sender allowed to see them? let user_is_in_public_rooms = services()
let mut user_visible = false; .rooms
.state_cache
let user_is_in_public_rooms = .rooms_joined(&user_id)
services().rooms.state_cache.rooms_joined(&user_id).filter_map(std::result::Result::ok).any(|room| { .filter_map(|r| r.ok())
services().rooms.state_accessor.room_state_get(&room, &StateEventType::RoomJoinRules, "").map_or( .any(|room| {
false, services()
|event| { .rooms
.state_accessor
.room_state_get(&room, &StateEventType::RoomJoinRules, "")
.map_or(false, |event| {
event.map_or(false, |event| { event.map_or(false, |event| {
serde_json::from_str(event.content.get()) serde_json::from_str(event.content.get())
.map_or(false, |r: RoomJoinRulesEventContent| r.join_rule == JoinRule::Public) .map_or(false, |r: RoomJoinRulesEventContent| {
r.join_rule == JoinRule::Public
})
})
}) })
},
)
}); });
if user_is_in_public_rooms { if user_is_in_public_rooms {
user_visible = true; return Some(user);
} else { }
let user_is_in_shared_rooms =
services().rooms.user.get_shared_rooms(vec![sender_user.clone(), user_id]).ok()?.next().is_some(); let user_is_in_shared_rooms = services()
.rooms
.user
.get_shared_rooms(vec![sender_user.clone(), user_id])
.ok()?
.next()
.is_some();
if user_is_in_shared_rooms { if user_is_in_shared_rooms {
user_visible = true; return Some(user);
}
} }
if !user_visible { None
return None;
}
Some(user)
}); });
let results = users.by_ref().take(limit).collect(); let results = users.by_ref().take(limit).collect();
let limited = users.next().is_some(); let limited = users.next().is_some();
Ok(search_users::v3::Response { Ok(search_users::v3::Response { results, limited })
results,
limited,
})
} }
+4 -5
View File
@@ -1,11 +1,9 @@
use std::time::{Duration, SystemTime}; use crate::{services, Result, Ruma};
use base64::{engine::general_purpose, Engine as _}; use base64::{engine::general_purpose, Engine as _};
use hmac::{Hmac, Mac}; use hmac::{Hmac, Mac};
use ruma::{api::client::voip::get_turn_server_info, SecondsSinceUnixEpoch}; use ruma::{api::client::voip::get_turn_server_info, SecondsSinceUnixEpoch};
use sha1::Sha1; use sha1::Sha1;
use std::time::{Duration, SystemTime};
use crate::{services, Result, Ruma};
type HmacSha1 = Hmac<Sha1>; type HmacSha1 = Hmac<Sha1>;
@@ -27,7 +25,8 @@ pub async fn turn_server_route(
let username: String = format!("{}:{}", expiry.get(), sender_user); let username: String = format!("{}:{}", expiry.get(), sender_user);
let mut mac = HmacSha1::new_from_slice(turn_secret.as_bytes()).expect("HMAC can take key of any size"); let mut mac = HmacSha1::new_from_slice(turn_secret.as_bytes())
.expect("HMAC can take key of any size");
mac.update(username.as_bytes()); mac.update(username.as_bytes());
let password: String = general_purpose::STANDARD.encode(mac.finalize().into_bytes()); let password: String = general_purpose::STANDARD.encode(mac.finalize().into_bytes());
+130 -92
View File
@@ -1,4 +1,4 @@
use std::{collections::BTreeMap, str}; use std::{collections::BTreeMap, iter::FromIterator, str};
use axum::{ use axum::{
async_trait, async_trait,
@@ -39,21 +39,22 @@ where
{ {
type Rejection = Error; type Rejection = Error;
#[allow(unused_qualifications)] // async traits
async fn from_request(req: Request<B>, _state: &S) -> Result<Self, Self::Rejection> { async fn from_request(req: Request<B>, _state: &S) -> Result<Self, Self::Rejection> {
let (mut parts, mut body) = match req.with_limited_body() { let (mut parts, mut body) = match req.with_limited_body() {
Ok(limited_req) => { Ok(limited_req) => {
let (parts, body) = limited_req.into_parts(); let (parts, body) = limited_req.into_parts();
let body = let body = to_bytes(body)
to_bytes(body).await.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?; .await
.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?;
(parts, body) (parts, body)
}, }
Err(original_req) => { Err(original_req) => {
let (parts, body) = original_req.into_parts(); let (parts, body) = original_req.into_parts();
let body = let body = to_bytes(body)
to_bytes(body).await.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?; .await
.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?;
(parts, body) (parts, body)
}, }
}; };
let metadata = T::METADATA; let metadata = T::METADATA;
@@ -65,8 +66,11 @@ where
Ok(params) => params, Ok(params) => params,
Err(e) => { Err(e) => {
error!(%query, "Failed to deserialize query parameters: {}", e); error!(%query, "Failed to deserialize query parameters: {}", e);
return Err(Error::BadRequest(ErrorKind::Unknown, "Failed to read query parameters")); return Err(Error::BadRequest(
}, ErrorKind::Unknown,
"Failed to read query parameters",
));
}
}; };
let token = match &auth_header { let token = match &auth_header {
@@ -77,15 +81,14 @@ where
let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&body).ok(); let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&body).ok();
let appservices = services().appservice.all().unwrap(); let appservices = services().appservice.all().unwrap();
let appservice_registration = let appservice_registration = appservices
appservices.iter().find(|(_id, registration)| Some(registration.as_token.as_str()) == token); .iter()
.find(|(_id, registration)| Some(registration.as_token.as_str()) == token);
let (sender_user, sender_device, sender_servername, from_appservice) = if let Some((_id, registration)) = let (sender_user, sender_device, sender_servername, from_appservice) =
appservice_registration if let Some((_id, registration)) = appservice_registration {
{
match metadata.authentication { match metadata.authentication {
// TODO: verify if just or'ing `AuthScheme::AppserviceToken` is correct here AuthScheme::AccessToken => {
AuthScheme::AccessToken | AuthScheme::AccessTokenOptional | AuthScheme::AppserviceToken => {
let user_id = query_params.user_id.map_or_else( let user_id = query_params.user_id.map_or_else(
|| { || {
UserId::parse_with_server_name( UserId::parse_with_server_name(
@@ -97,13 +100,16 @@ where
|s| UserId::parse(s).unwrap(), |s| UserId::parse(s).unwrap(),
); );
if !services().users.exists(&user_id)? { if !services().users.exists(&user_id).unwrap() {
return Err(Error::BadRequest(ErrorKind::Forbidden, "User does not exist.")); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"User does not exist.",
));
} }
// TODO: Check if appservice is allowed to be that user // TODO: Check if appservice is allowed to be that user
(Some(user_id), None, None, true) (Some(user_id), None, None, true)
}, }
AuthScheme::ServerSignatures => (None, None, None, true), AuthScheme::ServerSignatures => (None, None, None, true),
AuthScheme::None => (None, None, None, true), AuthScheme::None => (None, None, None, true),
} }
@@ -112,89 +118,92 @@ where
AuthScheme::AccessToken => { AuthScheme::AccessToken => {
let token = match token { let token = match token {
Some(token) => token, Some(token) => token,
_ => return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token.")), _ => {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing access token.",
))
}
}; };
match services().users.find_from_token(token)? { match services().users.find_from_token(token).unwrap() {
None => { None => {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::UnknownToken { ErrorKind::UnknownToken { soft_logout: false },
soft_logout: false,
},
"Unknown access token.", "Unknown access token.",
)) ))
},
Some((user_id, device_id)) => {
(Some(user_id), Some(OwnedDeviceId::from(device_id)), None, false)
},
} }
}, Some((user_id, device_id)) => (
AuthScheme::AccessTokenOptional => { Some(user_id),
let token = token.unwrap_or(""); Some(OwnedDeviceId::from(device_id)),
None,
if token.is_empty() { false,
(None, None, None, false) ),
} else {
match services().users.find_from_token(token)? {
None => {
return Err(Error::BadRequest(
ErrorKind::UnknownToken {
soft_logout: false,
},
"Unknown access token.",
))
},
Some((user_id, device_id)) => {
(Some(user_id), Some(OwnedDeviceId::from(device_id)), None, false)
},
} }
} }
},
// treat non-appservice registrations as None authentication
AuthScheme::AppserviceToken => (None, None, None, false),
AuthScheme::ServerSignatures => { AuthScheme::ServerSignatures => {
if !services().globals.allow_federation() { let TypedHeader(Authorization(x_matrix)) = parts
return Err(Error::bad_config("Federation is disabled.")); .extract::<TypedHeader<Authorization<XMatrix>>>()
} .await
.map_err(|e| {
let TypedHeader(Authorization(x_matrix)) =
parts.extract::<TypedHeader<Authorization<XMatrix>>>().await.map_err(|e| {
warn!("Missing or invalid Authorization header: {}", e); warn!("Missing or invalid Authorization header: {}", e);
let msg = match e.reason() { let msg = match e.reason() {
TypedHeaderRejectionReason::Missing => "Missing Authorization header.", TypedHeaderRejectionReason::Missing => {
TypedHeaderRejectionReason::Error(_) => "Invalid X-Matrix signatures.", "Missing Authorization header."
}
TypedHeaderRejectionReason::Error(_) => {
"Invalid X-Matrix signatures."
}
_ => "Unknown header-related error", _ => "Unknown header-related error",
}; };
Error::BadRequest(ErrorKind::Forbidden, msg) Error::BadRequest(ErrorKind::Forbidden, msg)
})?; })?;
let origin_signatures = let origin_signatures = BTreeMap::from_iter([(
BTreeMap::from_iter([(x_matrix.key.clone(), CanonicalJsonValue::String(x_matrix.sig))]); x_matrix.key.clone(),
CanonicalJsonValue::String(x_matrix.sig),
)]);
let signatures = BTreeMap::from_iter([( let signatures = BTreeMap::from_iter([(
x_matrix.origin.as_str().to_owned(), x_matrix.origin.as_str().to_owned(),
CanonicalJsonValue::Object(origin_signatures), CanonicalJsonValue::Object(origin_signatures),
)]); )]);
let server_destination = services().globals.server_name().as_str().to_owned(); let server_destination =
services().globals.server_name().as_str().to_owned();
if let Some(destination) = x_matrix.destination.as_ref() { if let Some(destination) = x_matrix.destination.as_ref() {
if destination != &server_destination { if destination != &server_destination {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Invalid authorization.")); return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Invalid authorization.",
));
} }
} }
let mut request_map = BTreeMap::from_iter([ let mut request_map = BTreeMap::from_iter([
("method".to_owned(), CanonicalJsonValue::String(parts.method.to_string())), (
("uri".to_owned(), CanonicalJsonValue::String(parts.uri.to_string())), "method".to_owned(),
CanonicalJsonValue::String(parts.method.to_string()),
),
(
"uri".to_owned(),
CanonicalJsonValue::String(parts.uri.to_string()),
),
( (
"origin".to_owned(), "origin".to_owned(),
CanonicalJsonValue::String(x_matrix.origin.as_str().to_owned()), CanonicalJsonValue::String(x_matrix.origin.as_str().to_owned()),
), ),
("destination".to_owned(), CanonicalJsonValue::String(server_destination)), (
("signatures".to_owned(), CanonicalJsonValue::Object(signatures)), "destination".to_owned(),
CanonicalJsonValue::String(server_destination),
),
(
"signatures".to_owned(),
CanonicalJsonValue::Object(signatures),
),
]); ]);
if let Some(json_body) = &json_body { if let Some(json_body) = &json_body {
@@ -204,18 +213,25 @@ where
let keys_result = services() let keys_result = services()
.rooms .rooms
.event_handler .event_handler
.fetch_signing_keys_for_server(&x_matrix.origin, vec![x_matrix.key.clone()]) .fetch_signing_keys_for_server(
&x_matrix.origin,
vec![x_matrix.key.to_owned()],
)
.await; .await;
let keys = match keys_result { let keys = match keys_result {
Ok(b) => b, Ok(b) => b,
Err(e) => { Err(e) => {
warn!("Failed to fetch signing keys: {}", e); warn!("Failed to fetch signing keys: {}", e);
return Err(Error::BadRequest(ErrorKind::Forbidden, "Failed to fetch signing keys.")); return Err(Error::BadRequest(
}, ErrorKind::Forbidden,
"Failed to fetch signing keys.",
));
}
}; };
let pub_key_map = BTreeMap::from_iter([(x_matrix.origin.as_str().to_owned(), keys)]); let pub_key_map =
BTreeMap::from_iter([(x_matrix.origin.as_str().to_owned(), keys)]);
match ruma::signatures::verify_json(&pub_key_map, &request_map) { match ruma::signatures::verify_json(&pub_key_map, &request_map) {
Ok(()) => (None, None, Some(x_matrix.origin), false), Ok(()) => (None, None, Some(x_matrix.origin), false),
@@ -227,8 +243,9 @@ where
if parts.uri.to_string().contains('@') { if parts.uri.to_string().contains('@') {
warn!( warn!(
"Request uri contained '@' character. Make sure your reverse proxy gives Conduit \ "Request uri contained '@' character. Make sure your \
the raw uri (apache: use nocanon)" reverse proxy gives Conduit the raw uri (apache: use \
nocanon)"
); );
} }
@@ -236,46 +253,57 @@ where
ErrorKind::Forbidden, ErrorKind::Forbidden,
"Failed to verify X-Matrix signatures.", "Failed to verify X-Matrix signatures.",
)); ));
},
} }
}, }
}
AuthScheme::None => match parts.uri.path() { AuthScheme::None => match parts.uri.path() {
// allow_public_room_directory_without_auth // allow_public_room_directory_without_auth
"/_matrix/client/v3/publicRooms" | "/_matrix/client/r0/publicRooms" => { "/_matrix/client/v3/publicRooms" | "/_matrix/client/r0/publicRooms" => {
if !services().globals.config.allow_public_room_directory_without_auth { if !services()
.globals
.config
.allow_public_room_directory_without_auth
{
let token = match token { let token = match token {
Some(token) => token, Some(token) => token,
_ => return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token.")), _ => {
return Err(Error::BadRequest(
ErrorKind::MissingToken,
"Missing access token.",
))
}
}; };
match services().users.find_from_token(token)? { match services().users.find_from_token(token).unwrap() {
None => { None => {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::UnknownToken { ErrorKind::UnknownToken { soft_logout: false },
soft_logout: false,
},
"Unknown access token.", "Unknown access token.",
)) ))
}, }
Some((user_id, device_id)) => { Some((user_id, device_id)) => (
(Some(user_id), Some(OwnedDeviceId::from(device_id)), None, false) Some(user_id),
}, Some(OwnedDeviceId::from(device_id)),
None,
false,
),
} }
} else { } else {
(None, None, None, false) (None, None, None, false)
} }
}, }
_ => (None, None, None, false), _ => (None, None, None, false),
}, },
} }
}; };
let mut http_request = Request::builder().uri(parts.uri).method(parts.method); let mut http_request = http::Request::builder().uri(parts.uri).method(parts.method);
*http_request.headers_mut().unwrap() = parts.headers; *http_request.headers_mut().unwrap() = parts.headers;
if let Some(CanonicalJsonValue::Object(json_body)) = &mut json_body { if let Some(CanonicalJsonValue::Object(json_body)) = &mut json_body {
let user_id = sender_user.clone().unwrap_or_else(|| { let user_id = sender_user.clone().unwrap_or_else(|| {
UserId::parse_with_server_name("", services().globals.server_name()).expect("we know this is valid") UserId::parse_with_server_name("", services().globals.server_name())
.expect("we know this is valid")
}); });
let uiaa_request = json_body let uiaa_request = json_body
@@ -339,7 +367,9 @@ impl Credentials for XMatrix {
"HeaderValue to decode should start with \"X-Matrix ..\", received = {value:?}", "HeaderValue to decode should start with \"X-Matrix ..\", received = {value:?}",
); );
let parameters = str::from_utf8(&value.as_bytes()["X-Matrix ".len()..]).ok()?.trim_start(); let parameters = str::from_utf8(&value.as_bytes()["X-Matrix ".len()..])
.ok()?
.trim_start();
let mut origin = None; let mut origin = None;
let mut destination = None; let mut destination = None;
@@ -351,7 +381,10 @@ impl Credentials for XMatrix {
// It's not at all clear why some fields are quoted and others not in the spec, // It's not at all clear why some fields are quoted and others not in the spec,
// let's simply accept either form for every field. // let's simply accept either form for every field.
let value = value.strip_prefix('"').and_then(|rest| rest.strip_suffix('"')).unwrap_or(value); let value = value
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.unwrap_or(value);
// FIXME: Catch multiple fields of the same name // FIXME: Catch multiple fields of the same name
match name { match name {
@@ -359,7 +392,10 @@ impl Credentials for XMatrix {
"key" => key = Some(value.to_owned()), "key" => key = Some(value.to_owned()),
"sig" => sig = Some(value.to_owned()), "sig" => sig = Some(value.to_owned()),
"destination" => destination = Some(value.to_owned()), "destination" => destination = Some(value.to_owned()),
_ => debug!("Unexpected field `{}` in X-Matrix Authorization header", name), _ => debug!(
"Unexpected field `{}` in X-Matrix Authorization header",
name
),
} }
} }
@@ -371,7 +407,9 @@ impl Credentials for XMatrix {
}) })
} }
fn encode(&self) -> http::HeaderValue { todo!() } fn encode(&self) -> http::HeaderValue {
todo!()
}
} }
impl<T: OutgoingResponse> IntoResponse for RumaResponse<T> { impl<T: OutgoingResponse> IntoResponse for RumaResponse<T> {
+14 -7
View File
@@ -1,8 +1,9 @@
use std::ops::Deref;
use ruma::{api::client::uiaa::UiaaResponse, CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId};
use crate::Error; use crate::Error;
use ruma::{
api::client::uiaa::UiaaResponse, CanonicalJsonValue, OwnedDeviceId, OwnedServerName,
OwnedUserId,
};
use std::ops::Deref;
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
mod axum; mod axum;
@@ -21,16 +22,22 @@ pub struct Ruma<T> {
impl<T> Deref for Ruma<T> { impl<T> Deref for Ruma<T> {
type Target = T; type Target = T;
fn deref(&self) -> &Self::Target { &self.body } fn deref(&self) -> &Self::Target {
&self.body
}
} }
#[derive(Clone)] #[derive(Clone)]
pub struct RumaResponse<T>(pub T); pub struct RumaResponse<T>(pub T);
impl<T> From<T> for RumaResponse<T> { impl<T> From<T> for RumaResponse<T> {
fn from(t: T) -> Self { Self(t) } fn from(t: T) -> Self {
Self(t)
}
} }
impl From<Error> for RumaResponse<UiaaResponse> { impl From<Error> for RumaResponse<UiaaResponse> {
fn from(t: Error) -> Self { t.to_response() } fn from(t: Error) -> Self {
t.to_response()
}
} }
+718 -356
View File
File diff suppressed because it is too large Load Diff
-54
View File
@@ -1,54 +0,0 @@
//! Integration with `clap`
use std::path::PathBuf;
use clap::{Parser, Subcommand};
/// Commandline arguments
#[derive(Parser, Debug)]
#[clap(version, about, long_about = None)]
pub struct Args {
#[arg(short, long)]
/// Optional argument to the path of a conduwuit config TOML file
pub config: Option<PathBuf>,
#[clap(subcommand)]
/// Optional subcommand to export the homeserver signing key and exit
pub signing_key: Option<SigningKey>,
}
#[derive(Debug, Subcommand)]
pub enum SigningKey {
/// Filesystem path to export the homeserver signing key to.
/// The output will be: `ed25519 <version> <keypair base64 encoded>` which
/// is Synapse's format
ExportPath {
path: PathBuf,
},
/// Filesystem path for conduwuit to attempt to read and import the
/// homeserver signing key. The expected format is Synapse's format:
/// `ed25519 <version> <keypair base64 encoded>`
ImportPath {
path: PathBuf,
#[arg(long)]
/// Optional argument to import the key but don't overwrite our signing
/// key, and instead add it to `old_verify_keys`. This field tells other
/// servers that this is our old public key that can still be used to
/// sign old events.
///
/// See https://spec.matrix.org/v1.9/server-server-api/#get_matrixkeyv2server for more details.
add_to_old_public_keys: bool,
#[arg(long)]
/// Timestamp (`expired_ts`) in seconds since UNIX epoch that the old
/// homeserver signing key stopped being used.
///
/// See https://spec.matrix.org/v1.9/server-server-api/#get_matrixkeyv2server for more details.
timestamp: u64,
},
}
/// Parse commandline arguments into structured data
pub fn parse() -> Args { Args::parse() }
+133 -159
View File
@@ -1,29 +1,21 @@
use std::{ use std::{
collections::BTreeMap, collections::BTreeMap,
fmt, fmt,
fmt::Write as _,
net::{IpAddr, Ipv4Addr}, net::{IpAddr, Ipv4Addr},
path::PathBuf, path::PathBuf,
}; };
use either::Either;
use figment::Figment; use figment::Figment;
use itertools::Itertools; use itertools::Itertools;
use regex::RegexSet; use regex::RegexSet;
use ruma::{OwnedServerName, RoomVersionId}; use ruma::{OwnedServerName, RoomVersionId};
use serde::{de::IgnoredAny, Deserialize}; use serde::{de::IgnoredAny, Deserialize};
use tracing::{debug, error, warn}; use tracing::{debug, error, warn};
use self::proxy::ProxyConfig;
mod proxy; mod proxy;
#[derive(Deserialize, Clone, Debug)] use self::proxy::ProxyConfig;
#[serde(transparent)]
pub struct ListeningPort {
#[serde(with = "either::serde_untagged")]
pub ports: Either<u16, Vec<u16>>,
}
/// all the config options for conduwuit /// all the config options for conduwuit
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
@@ -31,9 +23,9 @@ pub struct Config {
/// [`IpAddr`] conduwuit will listen on (can be IPv4 or IPv6) /// [`IpAddr`] conduwuit will listen on (can be IPv4 or IPv6)
#[serde(default = "default_address")] #[serde(default = "default_address")]
pub address: IpAddr, pub address: IpAddr,
/// default TCP port(s) conduwuit will listen on /// default TCP port conduwuit will listen on
#[serde(default = "default_port")] #[serde(default = "default_port")]
pub port: ListeningPort, pub port: u16,
pub tls: Option<TlsConfig>, pub tls: Option<TlsConfig>,
pub unix_socket_path: Option<PathBuf>, pub unix_socket_path: Option<PathBuf>,
#[serde(default = "default_unix_socket_perms")] #[serde(default = "default_unix_socket_perms")]
@@ -44,9 +36,9 @@ pub struct Config {
pub database_path: String, pub database_path: String,
#[serde(default = "default_db_cache_capacity_mb")] #[serde(default = "default_db_cache_capacity_mb")]
pub db_cache_capacity_mb: f64, pub db_cache_capacity_mb: f64,
#[serde(default = "default_new_user_displayname_suffix")] #[serde(default = "true_fn")]
pub new_user_displayname_suffix: String, pub enable_lightning_bolt: bool,
#[serde(default)] #[serde(default = "true_fn")]
pub allow_check_for_updates: bool, pub allow_check_for_updates: bool,
#[serde(default = "default_conduit_cache_capacity_modifier")] #[serde(default = "default_conduit_cache_capacity_modifier")]
pub conduit_cache_capacity_modifier: f64, pub conduit_cache_capacity_modifier: f64,
@@ -92,8 +84,6 @@ pub struct Config {
pub jwt_secret: Option<String>, pub jwt_secret: Option<String>,
#[serde(default = "default_trusted_servers")] #[serde(default = "default_trusted_servers")]
pub trusted_servers: Vec<OwnedServerName>, pub trusted_servers: Vec<OwnedServerName>,
#[serde(default = "true_fn")]
pub query_trusted_key_servers_first: bool,
#[serde(default = "default_log")] #[serde(default = "default_log")]
pub log: String, pub log: String,
#[serde(default)] #[serde(default)]
@@ -115,18 +105,6 @@ pub struct Config {
pub rocksdb_log_time_to_roll: usize, pub rocksdb_log_time_to_roll: usize,
#[serde(default)] #[serde(default)]
pub rocksdb_optimize_for_spinning_disks: bool, pub rocksdb_optimize_for_spinning_disks: bool,
#[serde(default = "default_rocksdb_parallelism_threads")]
pub rocksdb_parallelism_threads: usize,
#[serde(default = "default_rocksdb_max_log_files")]
pub rocksdb_max_log_files: usize,
#[serde(default = "default_rocksdb_compression_algo")]
pub rocksdb_compression_algo: String,
#[serde(default = "default_rocksdb_compression_level")]
pub rocksdb_compression_level: i32,
#[serde(default = "default_rocksdb_bottommost_compression_level")]
pub rocksdb_bottommost_compression_level: i32,
#[serde(default)]
pub rocksdb_bottommost_compression: bool,
pub emergency_password: Option<String>, pub emergency_password: Option<String>,
@@ -144,9 +122,6 @@ pub struct Config {
#[serde(default = "default_presence_offline_timeout_s")] #[serde(default = "default_presence_offline_timeout_s")]
pub presence_offline_timeout_s: u64, pub presence_offline_timeout_s: u64,
#[serde(default = "true_fn")]
pub allow_incoming_read_receipts: bool,
#[serde(default)] #[serde(default)]
pub zstd_compression: bool, pub zstd_compression: bool,
@@ -178,9 +153,6 @@ pub struct Config {
#[serde(with = "serde_regex")] #[serde(with = "serde_regex")]
pub forbidden_usernames: RegexSet, pub forbidden_usernames: RegexSet,
#[serde(default)]
pub block_non_admin_invites: bool,
#[serde(flatten)] #[serde(flatten)]
pub catchall: BTreeMap<String, IgnoredAny>, pub catchall: BTreeMap<String, IgnoredAny>,
} }
@@ -189,53 +161,48 @@ pub struct Config {
pub struct TlsConfig { pub struct TlsConfig {
pub certs: String, pub certs: String,
pub key: String, pub key: String,
#[serde(default)]
/// Whether to listen and allow for HTTP and HTTPS connections (insecure!)
/// Only works / does something if the `axum_dual_protocol` feature flag was
/// built
pub dual_protocol: bool,
} }
const DEPRECATED_KEYS: &[&str] = &["cache_capacity"]; const DEPRECATED_KEYS: &[&str] = &["cache_capacity"];
impl Config { impl Config {
/// Iterates over all the keys in the config file and warns if there is a /// Iterates over all the keys in the config file and warns if there is a deprecated key specified
/// deprecated key specified
pub fn warn_deprecated(&self) { pub fn warn_deprecated(&self) {
debug!("Checking for deprecated config keys"); debug!("Checking for deprecated config keys");
let mut was_deprecated = false; let mut was_deprecated = false;
for key in self.catchall.keys().filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key)) { for key in self
.catchall
.keys()
.filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key))
{
warn!("Config parameter \"{}\" is deprecated, ignoring.", key); warn!("Config parameter \"{}\" is deprecated, ignoring.", key);
was_deprecated = true; was_deprecated = true;
} }
if was_deprecated { if was_deprecated {
warn!("Read conduit documentation and check your configuration if any new configuration parameters should be adjusted");
}
}
/// iterates over all the catchall keys (unknown config options) and warns if there are any.
pub fn warn_unknown_key(&self) {
debug!("Checking for unknown config keys");
for key in self.catchall.keys().filter(
|key| "config".to_owned().ne(key.to_owned()), /* "config" is expected */
) {
warn!( warn!(
"Read conduit documentation and check your configuration if any new configuration parameters should \ "Config parameter \"{}\" is unknown to conduwuit, ignoring.",
be adjusted" key
); );
} }
} }
/// iterates over all the catchall keys (unknown config options) and warns /// Checks the presence of the `address` and `unix_socket_path` keys in the raw_config, exiting the process if both keys were detected.
/// if there are any. pub fn is_dual_listening(&self, raw_config: Figment) -> bool {
pub fn warn_unknown_key(&self) {
debug!("Checking for unknown config keys");
for key in
self.catchall.keys().filter(|key| "config".to_owned().ne(key.to_owned()) /* "config" is expected */)
{
warn!("Config parameter \"{}\" is unknown to conduwuit, ignoring.", key);
}
}
/// Checks the presence of the `address` and `unix_socket_path` keys in the
/// raw_config, exiting the process if both keys were detected.
pub fn is_dual_listening(&self, raw_config: &Figment) -> bool {
let check_address = raw_config.find_value("address"); let check_address = raw_config.find_value("address");
let check_unix_socket = raw_config.find_value("unix_socket_path"); let check_unix_socket = raw_config.find_value("unix_socket_path");
// are the check_address and check_unix_socket keys both Ok (specified) at the // are the check_address and check_unix_socket keys both Ok (specified) at the same time?
// same time?
if check_address.is_ok() && check_unix_socket.is_ok() { if check_address.is_ok() && check_unix_socket.is_ok() {
error!("TOML keys \"address\" and \"unix_socket_path\" were both defined. Please specify only one option."); error!("TOML keys \"address\" and \"unix_socket_path\" were both defined. Please specify only one option.");
return true; return true;
@@ -252,25 +219,36 @@ impl fmt::Display for Config {
("Server name", self.server_name.host()), ("Server name", self.server_name.host()),
("Database backend", &self.database_backend), ("Database backend", &self.database_backend),
("Database path", &self.database_path), ("Database path", &self.database_path),
("Database cache capacity (MB)", &self.db_cache_capacity_mb.to_string()),
("Cache capacity modifier", &self.conduit_cache_capacity_modifier.to_string()),
("PDU cache capacity", &self.pdu_cache_capacity.to_string()),
("Cleanup interval in seconds", &self.cleanup_second_interval.to_string()),
("Maximum request size (bytes)", &self.max_request_size.to_string()),
("Maximum concurrent requests", &self.max_concurrent_requests.to_string()),
("Allow registration", &self.allow_registration.to_string()),
( (
"Registration token", "Database cache capacity (MB)",
match self.registration_token { &self.db_cache_capacity_mb.to_string(),
Some(_) => "set",
None => "not set (open registration!)",
},
), ),
( (
"Allow guest registration (inherently false if allow registration is false)", "Cache capacity modifier",
&self.conduit_cache_capacity_modifier.to_string(),
),
("PDU cache capacity", &self.pdu_cache_capacity.to_string()),
(
"Cleanup interval in seconds",
&self.cleanup_second_interval.to_string(),
),
("Maximum request size", &self.max_request_size.to_string()),
(
"Maximum concurrent requests",
&self.max_concurrent_requests.to_string(),
),
(
"Allow registration (open registration)",
&self.allow_registration.to_string(),
),
(
"Allow guest registration",
&self.allow_guest_registration.to_string(), &self.allow_guest_registration.to_string(),
), ),
("New user display name suffix", &self.new_user_displayname_suffix), (
"Enabled lightning bolt",
&self.enable_lightning_bolt.to_string(),
),
("Allow encryption", &self.allow_encryption.to_string()), ("Allow encryption", &self.allow_encryption.to_string()),
("Allow federation", &self.allow_federation.to_string()), ("Allow federation", &self.allow_federation.to_string()),
( (
@@ -286,14 +264,9 @@ impl fmt::Display for Config {
&self.allow_local_presence.to_string(), &self.allow_local_presence.to_string(),
), ),
( (
"Allow incoming remote read receipts", "Allow device name federation",
&self.allow_incoming_read_receipts.to_string(), &self.allow_device_name_federation.to_string(),
), ),
(
"Block non-admin room invites (local and remote, admins can still send and receive invites)",
&self.block_non_admin_invites.to_string(),
),
("Allow device name federation", &self.allow_device_name_federation.to_string()),
("Notification push path", &self.notification_push_path), ("Notification push path", &self.notification_push_path),
("Allow room creation", &self.allow_room_creation.to_string()), ("Allow room creation", &self.allow_room_creation.to_string()),
( (
@@ -311,17 +284,13 @@ impl fmt::Display for Config {
None => "not set", None => "not set",
}, },
), ),
("Trusted key servers", { ("Trusted servers", {
let mut lst = vec![]; let mut lst = vec![];
for server in &self.trusted_servers { for server in &self.trusted_servers {
lst.push(server.host()); lst.push(server.host());
} }
&lst.join(", ") &lst.join(", ")
}), }),
(
"Query Trusted Key Servers First",
&self.query_trusted_key_servers_first.to_string(),
),
( (
"TURN username", "TURN username",
if self.turn_username.is_empty() { if self.turn_username.is_empty() {
@@ -353,40 +322,23 @@ impl fmt::Display for Config {
} }
&lst.join(", ") &lst.join(", ")
}), }),
#[cfg(feature = "compression-zstd")] (
("zstd Response Body Compression", &self.zstd_compression.to_string()), "zstd Response Body Compression",
#[cfg(feature = "rocksdb")] &self.zstd_compression.to_string(),
),
("RocksDB database log level", &self.rocksdb_log_level), ("RocksDB database log level", &self.rocksdb_log_level),
#[cfg(feature = "rocksdb")] (
("RocksDB database log time-to-roll", &self.rocksdb_log_time_to_roll.to_string()), "RocksDB database log time-to-roll",
#[cfg(feature = "rocksdb")] &self.rocksdb_log_time_to_roll.to_string(),
("RocksDB Max LOG Files", &self.rocksdb_max_log_files.to_string()), ),
#[cfg(feature = "rocksdb")]
( (
"RocksDB database max log file size", "RocksDB database max log file size",
&self.rocksdb_max_log_file_size.to_string(), &self.rocksdb_max_log_file_size.to_string(),
), ),
#[cfg(feature = "rocksdb")]
( (
"RocksDB database optimize for spinning disks", "RocksDB database optimize for spinning disks",
&self.rocksdb_optimize_for_spinning_disks.to_string(), &self.rocksdb_optimize_for_spinning_disks.to_string(),
), ),
#[cfg(feature = "rocksdb")]
("RocksDB Parallelism Threads", &self.rocksdb_parallelism_threads.to_string()),
#[cfg(feature = "rocksdb")]
("RocksDB Compression Algorithm", &self.rocksdb_compression_algo),
#[cfg(feature = "rocksdb")]
("RocksDB Compression Level", &self.rocksdb_compression_level.to_string()),
#[cfg(feature = "rocksdb")]
(
"RocksDB Bottommost Compression Level",
&self.rocksdb_bottommost_compression_level.to_string(),
),
#[cfg(feature = "rocksdb")]
(
"RocksDB Bottommost Level Compression",
&self.rocksdb_bottommost_compression.to_string(),
),
("Prevent Media Downloads From", { ("Prevent Media Downloads From", {
let mut lst = vec![]; let mut lst = vec![];
for domain in &self.prevent_media_downloads_from { for domain in &self.prevent_media_downloads_from {
@@ -420,92 +372,116 @@ impl fmt::Display for Config {
"URL preview URL contains allowlist", "URL preview URL contains allowlist",
&self.url_preview_url_contains_allowlist.join(", "), &self.url_preview_url_contains_allowlist.join(", "),
), ),
("URL preview maximum spider size", &self.url_preview_max_spider_size.to_string()), (
("URL preview check root domain", &self.url_preview_check_root_domain.to_string()), "URL preview maximum spider size",
&self.url_preview_max_spider_size.to_string(),
),
(
"URL preview check root domain",
&self.url_preview_check_root_domain.to_string(),
),
]; ];
let mut msg: String = "Active config values:\n\n".to_owned(); let mut msg: String = "Active config values:\n\n".to_owned();
for line in lines.into_iter().enumerate() { for line in lines.into_iter().enumerate() {
let _ = writeln!(msg, "{}: {}", line.1 .0, line.1 .1); msg += &format!("{}: {}\n", line.1 .0, line.1 .1);
} }
write!(f, "{msg}") write!(f, "{msg}")
} }
} }
fn true_fn() -> bool { true } fn true_fn() -> bool {
true
fn default_address() -> IpAddr { Ipv4Addr::LOCALHOST.into() }
fn default_port() -> ListeningPort {
ListeningPort {
ports: Either::Left(8008),
}
} }
fn default_unix_socket_perms() -> u32 { 660 } fn default_address() -> IpAddr {
Ipv4Addr::LOCALHOST.into()
}
fn default_database_backend() -> String { "rocksdb".to_owned() } fn default_port() -> u16 {
8000
}
fn default_db_cache_capacity_mb() -> f64 { 300.0 } fn default_unix_socket_perms() -> u32 {
660
}
fn default_conduit_cache_capacity_modifier() -> f64 { 1.0 } fn default_database_backend() -> String {
"rocksdb".to_owned()
}
fn default_pdu_cache_capacity() -> u32 { 150_000 } fn default_db_cache_capacity_mb() -> f64 {
300.0
}
fn default_conduit_cache_capacity_modifier() -> f64 {
1.0
}
fn default_pdu_cache_capacity() -> u32 {
150_000
}
fn default_cleanup_second_interval() -> u32 { fn default_cleanup_second_interval() -> u32 {
1800 // every 30 minutes 60 // every minute
} }
fn default_max_request_size() -> u32 { fn default_max_request_size() -> u32 {
20 * 1024 * 1024 // Default to 20 MB 20 * 1024 * 1024 // Default to 20 MB
} }
fn default_max_concurrent_requests() -> u16 { 500 } fn default_max_concurrent_requests() -> u16 {
500
}
fn default_max_fetch_prev_events() -> u16 { 100_u16 } fn default_max_fetch_prev_events() -> u16 {
100_u16
}
fn default_trusted_servers() -> Vec<OwnedServerName> { vec![OwnedServerName::try_from("matrix.org").unwrap()] } fn default_trusted_servers() -> Vec<OwnedServerName> {
vec![OwnedServerName::try_from("matrix.org").unwrap()]
}
fn default_log() -> String { "warn,state_res=warn".to_owned() } fn default_log() -> String {
"warn,state_res=warn".to_owned()
}
fn default_notification_push_path() -> String { "/_matrix/push/v1/notify".to_owned() } fn default_notification_push_path() -> String {
"/_matrix/push/v1/notify".to_owned()
}
fn default_turn_ttl() -> u64 { 60 * 60 * 24 } fn default_turn_ttl() -> u64 {
60 * 60 * 24
}
fn default_presence_idle_timeout_s() -> u64 { 5 * 60 } fn default_presence_idle_timeout_s() -> u64 {
5 * 60
}
fn default_presence_offline_timeout_s() -> u64 { 30 * 60 } fn default_presence_offline_timeout_s() -> u64 {
30 * 60
}
fn default_rocksdb_log_level() -> String { "error".to_owned() } fn default_rocksdb_log_level() -> String {
"warn".to_owned()
}
fn default_rocksdb_log_time_to_roll() -> usize { 0 } fn default_rocksdb_log_time_to_roll() -> usize {
0
}
fn default_rocksdb_max_log_files() -> usize { 3 } // I know, it's a great name
pub(crate) fn default_default_room_version() -> RoomVersionId {
RoomVersionId::V10
}
fn default_rocksdb_max_log_file_size() -> usize { fn default_rocksdb_max_log_file_size() -> usize {
// 4 megabytes // 4 megabytes
4 * 1024 * 1024 4 * 1024 * 1024
} }
fn default_rocksdb_parallelism_threads() -> usize { num_cpus::get_physical() / 2 }
fn default_rocksdb_compression_algo() -> String { "zstd".to_owned() }
/// Default RocksDB compression level is 32767, which is internally read by
/// RocksDB as the default magic number and translated to the library's default
/// compression level as they all differ. See their `kDefaultCompressionLevel`.
fn default_rocksdb_compression_level() -> i32 { 32767 }
/// Default RocksDB compression level is 32767, which is internally read by
/// RocksDB as the default magic number and translated to the library's default
/// compression level as they all differ. See their `kDefaultCompressionLevel`.
fn default_rocksdb_bottommost_compression_level() -> i32 { 32767 }
// I know, it's a great name
pub(crate) fn default_default_room_version() -> RoomVersionId { RoomVersionId::V10 }
fn default_ip_range_denylist() -> Vec<String> { fn default_ip_range_denylist() -> Vec<String> {
vec![ vec![
"127.0.0.0/8".to_owned(), "127.0.0.0/8".to_owned(),
@@ -533,5 +509,3 @@ fn default_ip_range_denylist() -> Vec<String> {
fn default_url_preview_max_spider_size() -> usize { fn default_url_preview_max_spider_size() -> usize {
1_000_000 // 1MB 1_000_000 // 1MB
} }
fn default_new_user_displayname_suffix() -> String { "🏳️‍⚧️".to_owned() }
+10 -15
View File
@@ -24,10 +24,9 @@ use crate::Result;
/// ## Include vs. Exclude /// ## Include vs. Exclude
/// If include is an empty list, it is assumed to be `["*"]`. /// If include is an empty list, it is assumed to be `["*"]`.
/// ///
/// If a domain matches both the exclude and include list, the proxy will only /// If a domain matches both the exclude and include list, the proxy will only be used if it was
/// be used if it was included because of a more specific rule than it was /// included because of a more specific rule than it was excluded. In the above example, the proxy
/// excluded. In the above example, the proxy would be used for /// would be used for `ordinary.onion`, `matrix.myspecial.onion`, but not `hello.myspecial.onion`.
/// `ordinary.onion`, `matrix.myspecial.onion`, but not `hello.myspecial.onion`.
#[derive(Clone, Default, Debug, Deserialize)] #[derive(Clone, Default, Debug, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum ProxyConfig { pub enum ProxyConfig {
@@ -43,12 +42,9 @@ impl ProxyConfig {
pub fn to_proxy(&self) -> Result<Option<Proxy>> { pub fn to_proxy(&self) -> Result<Option<Proxy>> {
Ok(match self.clone() { Ok(match self.clone() {
ProxyConfig::None => None, ProxyConfig::None => None,
ProxyConfig::Global { ProxyConfig::Global { url } => Some(Proxy::all(url)?),
url,
} => Some(Proxy::all(url)?),
ProxyConfig::ByDomain(proxies) => Some(Proxy::custom(move |url| { ProxyConfig::ByDomain(proxies) => Some(Proxy::custom(move |url| {
proxies.iter().find_map(|proxy| proxy.for_url(url)).cloned() // first matching proxies.iter().find_map(|proxy| proxy.for_url(url)).cloned() // first matching proxy
// proxy
})), })),
}) })
} }
@@ -70,7 +66,7 @@ impl PartialProxyConfig {
let mut excluded_because = None; // most specific reason it was excluded let mut excluded_because = None; // most specific reason it was excluded
if self.include.is_empty() { if self.include.is_empty() {
// treat empty include list as `*` // treat empty include list as `*`
included_because = Some(&WildCardedDomain::WildCard); included_because = Some(&WildCardedDomain::WildCard)
} }
for wc_domain in &self.include { for wc_domain in &self.include {
if wc_domain.matches(domain) { if wc_domain.matches(domain) {
@@ -89,8 +85,7 @@ impl PartialProxyConfig {
} }
} }
match (included_because, excluded_because) { match (included_because, excluded_because) {
(Some(a), Some(b)) if a.more_specific_than(b) => Some(&self.url), /* included for a more specific reason */ (Some(a), Some(b)) if a.more_specific_than(b) => Some(&self.url), // included for a more specific reason than excluded
// than excluded
(Some(_), None) => Some(&self.url), (Some(_), None) => Some(&self.url),
_ => None, _ => None,
} }
@@ -112,20 +107,20 @@ impl WildCardedDomain {
WildCardedDomain::Exact(d) => domain == d, WildCardedDomain::Exact(d) => domain == d,
} }
} }
fn more_specific_than(&self, other: &Self) -> bool { fn more_specific_than(&self, other: &Self) -> bool {
match (self, other) { match (self, other) {
(WildCardedDomain::WildCard, WildCardedDomain::WildCard) => false, (WildCardedDomain::WildCard, WildCardedDomain::WildCard) => false,
(_, WildCardedDomain::WildCard) => true, (_, WildCardedDomain::WildCard) => true,
(WildCardedDomain::Exact(a), WildCardedDomain::WildCarded(_)) => other.matches(a), (WildCardedDomain::Exact(a), WildCardedDomain::WildCarded(_)) => other.matches(a),
(WildCardedDomain::WildCarded(a), WildCardedDomain::WildCarded(b)) => a != b && a.ends_with(b), (WildCardedDomain::WildCarded(a), WildCardedDomain::WildCarded(b)) => {
a != b && a.ends_with(b)
}
_ => false, _ => false,
} }
} }
} }
impl std::str::FromStr for WildCardedDomain { impl std::str::FromStr for WildCardedDomain {
type Err = std::convert::Infallible; type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
// maybe do some domain validation? // maybe do some domain validation?
Ok(if s.starts_with("*.") { Ok(if s.starts_with("*.") {
+14 -19
View File
@@ -1,8 +1,8 @@
use std::{future::Future, pin::Pin, sync::Arc};
use super::Config; use super::Config;
use crate::Result; use crate::Result;
use std::{future::Future, pin::Pin, sync::Arc};
#[cfg(feature = "sqlite")] #[cfg(feature = "sqlite")]
pub mod sqlite; pub mod sqlite;
@@ -18,43 +18,38 @@ pub(crate) trait KeyValueDatabaseEngine: Send + Sync {
Self: Sized; Self: Sized;
fn open_tree(&self, name: &'static str) -> Result<Arc<dyn KvTree>>; fn open_tree(&self, name: &'static str) -> Result<Arc<dyn KvTree>>;
fn flush(&self) -> Result<()>; fn flush(&self) -> Result<()>;
fn cleanup(&self) -> Result<()> { Ok(()) } fn cleanup(&self) -> Result<()> {
Ok(())
}
fn memory_usage(&self) -> Result<String> { fn memory_usage(&self) -> Result<String> {
Ok("Current database engine does not support memory usage reporting.".to_owned()) Ok("Current database engine does not support memory usage reporting.".to_owned())
} }
#[allow(dead_code)]
fn clear_caches(&self) {} fn clear_caches(&self) {}
} }
pub(crate) trait KvTree: Send + Sync { pub(crate) trait KvTree: Send + Sync {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>; fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
#[allow(dead_code)]
#[cfg(feature = "rocksdb")]
fn multi_get(
&self, _iter: Vec<(&Arc<rust_rocksdb::BoundColumnFamily<'_>>, Vec<u8>)>,
) -> Vec<std::result::Result<Option<Vec<u8>>, rust_rocksdb::Error>> {
unimplemented!()
}
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()>; fn insert(&self, key: &[u8], value: &[u8]) -> Result<()>;
fn insert_batch(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()>; fn insert_batch(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()>;
fn remove(&self, key: &[u8]) -> Result<()>; fn remove(&self, key: &[u8]) -> Result<()>;
#[allow(dead_code)]
#[cfg(feature = "rocksdb")]
fn remove_batch(&self, _iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> { unimplemented!() }
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>; fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
fn iter_from<'a>(&'a self, from: &[u8], backwards: bool) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>; fn iter_from<'a>(
&'a self,
from: &[u8],
backwards: bool,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
fn increment(&self, key: &[u8]) -> Result<Vec<u8>>; fn increment(&self, key: &[u8]) -> Result<Vec<u8>>;
fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()>; fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()>;
fn scan_prefix<'a>(&'a self, prefix: Vec<u8>) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>; fn scan_prefix<'a>(
&'a self,
prefix: Vec<u8>,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>; fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
+82 -161
View File
@@ -1,21 +1,17 @@
use super::{super::Config, watchers::Watchers, KeyValueDatabaseEngine, KvTree};
use crate::{utils, Result};
use std::{ use std::{
future::Future, future::Future,
pin::Pin, pin::Pin,
sync::{Arc, RwLock}, sync::{Arc, RwLock},
}; };
use rust_rocksdb::{ use rocksdb::LogLevel::{Debug, Error, Fatal, Info, Warn};
LogLevel::{Debug, Error, Fatal, Info, Warn},
WriteBatchWithTransaction,
};
use tracing::{debug, info}; use tracing::{debug, info};
use super::{super::Config, watchers::Watchers, KeyValueDatabaseEngine, KvTree};
use crate::{utils, Result};
pub(crate) struct Engine { pub(crate) struct Engine {
rocks: rust_rocksdb::DBWithThreadMode<rust_rocksdb::MultiThreaded>, rocks: rocksdb::DBWithThreadMode<rocksdb::MultiThreaded>,
cache: rust_rocksdb::Cache, cache: rocksdb::Cache,
old_cfs: Vec<String>, old_cfs: Vec<String>,
config: Config, config: Config,
} }
@@ -27,9 +23,9 @@ struct RocksDbEngineTree<'a> {
write_lock: RwLock<()>, write_lock: RwLock<()>,
} }
fn db_options(rocksdb_cache: &rust_rocksdb::Cache, config: &Config) -> rust_rocksdb::Options { fn db_options(rocksdb_cache: &rocksdb::Cache, config: &Config) -> rocksdb::Options {
// block-based options: https://docs.rs/rocksdb/latest/rocksdb/struct.BlockBasedOptions.html# // block-based options: https://docs.rs/rocksdb/latest/rocksdb/struct.BlockBasedOptions.html#
let mut block_based_options = rust_rocksdb::BlockBasedOptions::default(); let mut block_based_options = rocksdb::BlockBasedOptions::default();
block_based_options.set_block_cache(rocksdb_cache); block_based_options.set_block_cache(rocksdb_cache);
@@ -38,84 +34,59 @@ fn db_options(rocksdb_cache: &rust_rocksdb::Cache, config: &Config) -> rust_rock
block_based_options.set_block_size(64 * 1024); block_based_options.set_block_size(64 * 1024);
block_based_options.set_cache_index_and_filter_blocks(true); block_based_options.set_cache_index_and_filter_blocks(true);
block_based_options.set_bloom_filter(10.0, false);
block_based_options.set_pin_l0_filter_and_index_blocks_in_cache(true);
block_based_options.set_optimize_filters_for_memory(true);
// database options: https://docs.rs/rocksdb/latest/rocksdb/struct.Options.html# // database options: https://docs.rs/rocksdb/latest/rocksdb/struct.Options.html#
let mut db_opts = rust_rocksdb::Options::default(); let mut db_opts = rocksdb::Options::default();
let rocksdb_log_level = match config.rocksdb_log_level.as_ref() { let rocksdb_log_level = match config.rocksdb_log_level.as_ref() {
"debug" => Debug, "debug" => Debug,
"info" => Info, "info" => Info,
"warn" => Warn, "warn" => Warn,
"error" => Error,
"fatal" => Fatal, "fatal" => Fatal,
_ => Error, _ => Warn,
};
let rocksdb_compression_algo = match config.rocksdb_compression_algo.as_ref() {
"zstd" => rust_rocksdb::DBCompressionType::Zstd,
"zlib" => rust_rocksdb::DBCompressionType::Zlib,
"lz4" => rust_rocksdb::DBCompressionType::Lz4,
"bz2" => rust_rocksdb::DBCompressionType::Bz2,
_ => rust_rocksdb::DBCompressionType::Zstd,
};
let threads = if config.rocksdb_parallelism_threads == 0 {
num_cpus::get_physical() // max cores if user specified 0
} else {
config.rocksdb_parallelism_threads
}; };
db_opts.set_log_level(rocksdb_log_level); db_opts.set_log_level(rocksdb_log_level);
db_opts.set_max_log_file_size(config.rocksdb_max_log_file_size); db_opts.set_max_log_file_size(config.rocksdb_max_log_file_size);
db_opts.set_log_file_time_to_roll(config.rocksdb_log_time_to_roll); db_opts.set_log_file_time_to_roll(config.rocksdb_log_time_to_roll);
db_opts.set_keep_log_file_num(config.rocksdb_max_log_files);
if config.rocksdb_optimize_for_spinning_disks { if config.rocksdb_optimize_for_spinning_disks {
db_opts.set_skip_stats_update_on_db_open(true); // speeds up opening DB on hard drives // useful for hard drives but on literally any half-decent SSD this is not useful
db_opts.set_compaction_readahead_size(4 * 1024 * 1024); // "If youre running RocksDB on spinning disks, you should set this to at least // and the benefits of improved compaction based on up to date stats are good.
// 2MB. That way RocksDBs compaction is doing sequential instead of random // current conduwut users have NVMe/SSDs.
// reads." db_opts.set_skip_stats_update_on_db_open(true);
db_opts.set_target_file_size_base(256 * 1024 * 1024);
db_opts.set_compaction_readahead_size(2 * 1024 * 1024); // default compaction_readahead_size is 0 which is good for SSDs
db_opts.set_target_file_size_base(256 * 1024 * 1024); // default target_file_size is 64MB which is good for SSDs
db_opts.set_optimize_filters_for_hits(true); // doesn't really seem useful for fast storage
} else { } else {
db_opts.set_skip_stats_update_on_db_open(false);
db_opts.set_max_bytes_for_level_base(512 * 1024 * 1024); db_opts.set_max_bytes_for_level_base(512 * 1024 * 1024);
db_opts.set_use_direct_reads(true); db_opts.set_use_direct_reads(true);
db_opts.set_use_direct_io_for_flush_and_compaction(true); db_opts.set_use_direct_io_for_flush_and_compaction(true);
} }
if config.rocksdb_bottommost_compression {
db_opts.set_bottommost_compression_type(rocksdb_compression_algo);
db_opts.set_bottommost_zstd_max_train_bytes(0, true);
// -14 w_bits is only read by zlib.
db_opts.set_bottommost_compression_options(-14, config.rocksdb_bottommost_compression_level, 0, 0, true);
}
// -14 w_bits is only read by zlib.
db_opts.set_compression_options(-14, config.rocksdb_compression_level, 0, 0);
db_opts.set_block_based_table_factory(&block_based_options); db_opts.set_block_based_table_factory(&block_based_options);
db_opts.set_level_compaction_dynamic_level_bytes(true);
db_opts.create_if_missing(true); db_opts.create_if_missing(true);
db_opts.increase_parallelism( db_opts.increase_parallelism(num_cpus::get() as i32);
threads.try_into().expect("Failed to convert \"rocksdb_parallelism_threads\" usize into i32"), //db_opts.set_max_open_files(config.rocksdb_max_open_files);
); db_opts.set_compression_type(rocksdb::DBCompressionType::Zstd);
db_opts.set_compression_type(rocksdb_compression_algo); db_opts.set_compaction_style(rocksdb::DBCompactionStyle::Level);
db_opts.optimize_level_style_compaction(10 * 1024 * 1024);
// https://github.com/facebook/rocksdb/wiki/Setup-Options-and-Basic-Tuning // https://github.com/facebook/rocksdb/wiki/Setup-Options-and-Basic-Tuning
db_opts.set_level_compaction_dynamic_level_bytes(true);
db_opts.set_max_background_jobs(6); db_opts.set_max_background_jobs(6);
db_opts.set_bytes_per_sync(1_048_576); db_opts.set_bytes_per_sync(1048576);
// https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes#ktoleratecorruptedtailrecords // https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes#ktoleratecorruptedtailrecords
// //
// Unclean shutdowns of a Matrix homeserver are likely to be fine when // Unclean shutdowns of a Matrix homeserver are likely to be fine when
// recovered in this manner as it's likely any lost information will be // recovered in this manner as it's likely any lost information will be
// restored via federation. // restored via federation.
db_opts.set_wal_recovery_mode(rust_rocksdb::DBRecoveryMode::TolerateCorruptedTailRecords); db_opts.set_wal_recovery_mode(rocksdb::DBRecoveryMode::TolerateCorruptedTailRecords);
// TODO: remove me? https://gitlab.com/famedly/conduit/-/merge_requests/602/diffs#a3a261d6a9014330581b5bdecd586dab5ae00245_62_54 let prefix_extractor = rocksdb::SliceTransform::create_fixed_prefix(1);
let prefix_extractor = rust_rocksdb::SliceTransform::create_fixed_prefix(1);
db_opts.set_prefix_extractor(prefix_extractor); db_opts.set_prefix_extractor(prefix_extractor);
db_opts db_opts
@@ -124,21 +95,25 @@ fn db_options(rocksdb_cache: &rust_rocksdb::Cache, config: &Config) -> rust_rock
impl KeyValueDatabaseEngine for Arc<Engine> { impl KeyValueDatabaseEngine for Arc<Engine> {
fn open(config: &Config) -> Result<Self> { fn open(config: &Config) -> Result<Self> {
let cache_capacity_bytes = (config.db_cache_capacity_mb * 1024.0 * 1024.0) as usize; let cache_capacity_bytes = (config.db_cache_capacity_mb * 1024.0 * 1024.0) as usize;
let rocksdb_cache = rust_rocksdb::Cache::new_lru_cache(cache_capacity_bytes); let rocksdb_cache = rocksdb::Cache::new_lru_cache(cache_capacity_bytes);
let db_opts = db_options(&rocksdb_cache, config); let db_opts = db_options(&rocksdb_cache, config);
debug!("Listing column families in database"); debug!("Listing column families in database");
let cfs = let cfs = rocksdb::DBWithThreadMode::<rocksdb::MultiThreaded>::list_cf(
rust_rocksdb::DBWithThreadMode::<rust_rocksdb::MultiThreaded>::list_cf(&db_opts, &config.database_path) &db_opts,
&config.database_path,
)
.unwrap_or_default(); .unwrap_or_default();
debug!("Opening column family descriptors in database"); debug!("Opening column family descriptors in database");
info!("RocksDB database compaction will take place now, a delay in startup is expected"); info!("RocksDB database compaction will take place now, a delay in startup is expected");
let db = rust_rocksdb::DBWithThreadMode::<rust_rocksdb::MultiThreaded>::open_cf_descriptors( let db = rocksdb::DBWithThreadMode::<rocksdb::MultiThreaded>::open_cf_descriptors(
&db_opts, &db_opts,
&config.database_path, &config.database_path,
cfs.iter().map(|name| rust_rocksdb::ColumnFamilyDescriptor::new(name, db_options(&rocksdb_cache, config))), cfs.iter().map(|name| {
rocksdb::ColumnFamilyDescriptor::new(name, db_options(&rocksdb_cache, config))
}),
)?; )?;
Ok(Arc::new(Engine { Ok(Arc::new(Engine {
@@ -153,7 +128,9 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
if !self.old_cfs.contains(&name.to_owned()) { if !self.old_cfs.contains(&name.to_owned()) {
// Create if it didn't exist // Create if it didn't exist
debug!("Creating new column family in database: {}", name); debug!("Creating new column family in database: {}", name);
let _ = self.rocks.create_cf(name, &db_options(&self.cache, &self.config)); let _ = self
.rocks
.create_cf(name, &db_options(&self.cache, &self.config));
} }
Ok(Arc::new(RocksDbEngineTree { Ok(Arc::new(RocksDbEngineTree {
@@ -165,18 +142,20 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
} }
fn flush(&self) -> Result<()> { fn flush(&self) -> Result<()> {
debug!("Running flush_wal (no sync)"); // TODO?
rust_rocksdb::DBCommon::flush_wal(&self.rocks, false)?;
Ok(()) Ok(())
} }
fn memory_usage(&self) -> Result<String> { fn memory_usage(&self) -> Result<String> {
let stats = rust_rocksdb::perf::get_memory_usage_stats(Some(&[&self.rocks]), Some(&[&self.cache]))?; let stats =
rocksdb::perf::get_memory_usage_stats(Some(&[&self.rocks]), Some(&[&self.cache]))?;
Ok(format!( Ok(format!(
"Approximate memory usage of all the mem-tables: {:.3} MB\nApproximate memory usage of un-flushed \ "Approximate memory usage of all the mem-tables: {:.3} MB\n\
mem-tables: {:.3} MB\nApproximate memory usage of all the table readers: {:.3} MB\nApproximate memory \ Approximate memory usage of un-flushed mem-tables: {:.3} MB\n\
usage by cache: {:.3} MB\nApproximate memory usage by cache pinned: {:.3} MB\n", Approximate memory usage of all the table readers: {:.3} MB\n\
Approximate memory usage by cache: {:.3} MB\n\
Approximate memory usage by cache pinned: {:.3} MB\n\
",
stats.mem_table_total as f64 / 1024.0 / 1024.0, stats.mem_table_total as f64 / 1024.0 / 1024.0,
stats.mem_table_unflushed as f64 / 1024.0 / 1024.0, stats.mem_table_unflushed as f64 / 1024.0 / 1024.0,
stats.mem_table_readers_total as f64 / 1024.0 / 1024.0, stats.mem_table_readers_total as f64 / 1024.0 / 1024.0,
@@ -185,47 +164,23 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
)) ))
} }
fn cleanup(&self) -> Result<()> {
debug!("Running flush_opt");
let flushoptions = rust_rocksdb::FlushOptions::default();
rust_rocksdb::DBCommon::flush_opt(&self.rocks, &flushoptions)?;
Ok(())
}
// TODO: figure out if this is needed for rocksdb
#[allow(dead_code)]
fn clear_caches(&self) {} fn clear_caches(&self) {}
} }
impl RocksDbEngineTree<'_> { impl RocksDbEngineTree<'_> {
fn cf(&self) -> Arc<rust_rocksdb::BoundColumnFamily<'_>> { self.db.rocks.cf_handle(self.name).unwrap() } fn cf(&self) -> Arc<rocksdb::BoundColumnFamily<'_>> {
self.db.rocks.cf_handle(self.name).unwrap()
}
} }
impl KvTree for RocksDbEngineTree<'_> { impl KvTree for RocksDbEngineTree<'_> {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> { fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
let mut readoptions = rust_rocksdb::ReadOptions::default(); Ok(self.db.rocks.get_cf(&self.cf(), key)?)
readoptions.set_total_order_seek(true);
Ok(self.db.rocks.get_cf_opt(&self.cf(), key, &readoptions)?)
}
fn multi_get(
&self, iter: Vec<(&Arc<rust_rocksdb::BoundColumnFamily<'_>>, Vec<u8>)>,
) -> Vec<std::result::Result<Option<Vec<u8>>, rust_rocksdb::Error>> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
self.db.rocks.multi_get_cf_opt(iter, &readoptions)
} }
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> { fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
let writeoptions = rust_rocksdb::WriteOptions::default();
let lock = self.write_lock.read().unwrap(); let lock = self.write_lock.read().unwrap();
self.db.rocks.put_cf(&self.cf(), key, value)?;
self.db.rocks.put_cf_opt(&self.cf(), key, value, &writeoptions)?;
drop(lock); drop(lock);
self.watchers.wake(key); self.watchers.wake(key);
@@ -233,123 +188,89 @@ impl KvTree for RocksDbEngineTree<'_> {
Ok(()) Ok(())
} }
fn insert_batch(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> { fn insert_batch<'a>(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> {
let writeoptions = rust_rocksdb::WriteOptions::default();
let mut batch = WriteBatchWithTransaction::<false>::default();
for (key, value) in iter { for (key, value) in iter {
batch.put_cf(&self.cf(), key, value); self.db.rocks.put_cf(&self.cf(), key, value)?;
} }
Ok(self.db.rocks.write_opt(batch, &writeoptions)?) Ok(())
} }
fn remove(&self, key: &[u8]) -> Result<()> { fn remove(&self, key: &[u8]) -> Result<()> {
let writeoptions = rust_rocksdb::WriteOptions::default(); Ok(self.db.rocks.delete_cf(&self.cf(), key)?)
Ok(self.db.rocks.delete_cf_opt(&self.cf(), key, &writeoptions)?)
}
fn remove_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> {
let writeoptions = rust_rocksdb::WriteOptions::default();
let mut batch = WriteBatchWithTransaction::<false>::default();
for key in iter {
batch.delete_cf(&self.cf(), key);
}
Ok(self.db.rocks.write_opt(batch, &writeoptions)?)
} }
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> { fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
Box::new( Box::new(
self.db self.db
.rocks .rocks
.iterator_cf_opt(&self.cf(), readoptions, rust_rocksdb::IteratorMode::Start) .iterator_cf(&self.cf(), rocksdb::IteratorMode::Start)
.map(std::result::Result::unwrap) .map(|r| r.unwrap())
.map(|(k, v)| (Vec::from(k), Vec::from(v))), .map(|(k, v)| (Vec::from(k), Vec::from(v))),
) )
} }
fn iter_from<'a>(&'a self, from: &[u8], backwards: bool) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> { fn iter_from<'a>(
let mut readoptions = rust_rocksdb::ReadOptions::default(); &'a self,
readoptions.set_total_order_seek(true); from: &[u8],
backwards: bool,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
Box::new( Box::new(
self.db self.db
.rocks .rocks
.iterator_cf_opt( .iterator_cf(
&self.cf(), &self.cf(),
readoptions, rocksdb::IteratorMode::From(
rust_rocksdb::IteratorMode::From(
from, from,
if backwards { if backwards {
rust_rocksdb::Direction::Reverse rocksdb::Direction::Reverse
} else { } else {
rust_rocksdb::Direction::Forward rocksdb::Direction::Forward
}, },
), ),
) )
.map(std::result::Result::unwrap) .map(|r| r.unwrap())
.map(|(k, v)| (Vec::from(k), Vec::from(v))), .map(|(k, v)| (Vec::from(k), Vec::from(v))),
) )
} }
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> { fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
let writeoptions = rust_rocksdb::WriteOptions::default();
let lock = self.write_lock.write().unwrap(); let lock = self.write_lock.write().unwrap();
let old = self.db.rocks.get_cf_opt(&self.cf(), key, &readoptions)?; let old = self.db.rocks.get_cf(&self.cf(), key)?;
let new = utils::increment(old.as_deref()).unwrap(); let new = utils::increment(old.as_deref()).unwrap();
self.db.rocks.put_cf_opt(&self.cf(), key, &new, &writeoptions)?; self.db.rocks.put_cf(&self.cf(), key, &new)?;
drop(lock); drop(lock);
Ok(new) Ok(new)
} }
fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> { fn increment_batch<'a>(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
let writeoptions = rust_rocksdb::WriteOptions::default();
let mut batch = WriteBatchWithTransaction::<false>::default();
let lock = self.write_lock.write().unwrap(); let lock = self.write_lock.write().unwrap();
for key in iter { for key in iter {
let old = self.db.rocks.get_cf_opt(&self.cf(), &key, &readoptions)?; let old = self.db.rocks.get_cf(&self.cf(), &key)?;
let new = utils::increment(old.as_deref()).unwrap(); let new = utils::increment(old.as_deref()).unwrap();
batch.put_cf(&self.cf(), key, new); self.db.rocks.put_cf(&self.cf(), key, new)?;
} }
self.db.rocks.write_opt(batch, &writeoptions)?;
drop(lock); drop(lock);
Ok(()) Ok(())
} }
fn scan_prefix<'a>(&'a self, prefix: Vec<u8>) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> { fn scan_prefix<'a>(
let mut readoptions = rust_rocksdb::ReadOptions::default(); &'a self,
readoptions.set_total_order_seek(true); prefix: Vec<u8>,
) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
Box::new( Box::new(
self.db self.db
.rocks .rocks
.iterator_cf_opt( .iterator_cf(
&self.cf(), &self.cf(),
readoptions, rocksdb::IteratorMode::From(&prefix, rocksdb::Direction::Forward),
rust_rocksdb::IteratorMode::From(&prefix, rust_rocksdb::Direction::Forward),
) )
.map(std::result::Result::unwrap) .map(|r| r.unwrap())
.map(|(k, v)| (Vec::from(k), Vec::from(v))) .map(|(k, v)| (Vec::from(k), Vec::from(v)))
.take_while(move |(k, _)| k.starts_with(&prefix)), .take_while(move |(k, _)| k.starts_with(&prefix)),
) )
+69 -41
View File
@@ -1,3 +1,7 @@
use super::{watchers::Watchers, KeyValueDatabaseEngine, KvTree};
use crate::{database::Config, Result};
use parking_lot::{Mutex, MutexGuard};
use rusqlite::{Connection, DatabaseName::Main, OptionalExtension};
use std::{ use std::{
cell::RefCell, cell::RefCell,
future::Future, future::Future,
@@ -5,18 +9,12 @@ use std::{
pin::Pin, pin::Pin,
sync::Arc, sync::Arc,
}; };
use parking_lot::{Mutex, MutexGuard};
use rusqlite::{Connection, DatabaseName::Main, OptionalExtension};
use thread_local::ThreadLocal; use thread_local::ThreadLocal;
use tracing::debug; use tracing::debug;
use super::{watchers::Watchers, KeyValueDatabaseEngine, KvTree};
use crate::{database::Config, Result};
thread_local! { thread_local! {
static READ_CONNECTION: RefCell<Option<&'static Connection>> = const { RefCell::new(None) }; static READ_CONNECTION: RefCell<Option<&'static Connection>> = RefCell::new(None);
static READ_CONNECTION_ITERATOR: RefCell<Option<&'static Connection>> = const { RefCell::new(None) }; static READ_CONNECTION_ITERATOR: RefCell<Option<&'static Connection>> = RefCell::new(None);
} }
struct PreparedStatementIterator<'a> { struct PreparedStatementIterator<'a> {
@@ -27,16 +25,14 @@ struct PreparedStatementIterator<'a> {
impl Iterator for PreparedStatementIterator<'_> { impl Iterator for PreparedStatementIterator<'_> {
type Item = TupleOfBytes; type Item = TupleOfBytes;
fn next(&mut self) -> Option<Self::Item> { self.iterator.next() } fn next(&mut self) -> Option<Self::Item> {
self.iterator.next()
}
} }
struct NonAliasingBox<T>(*mut T); struct NonAliasingBox<T>(*mut T);
impl<T> Drop for NonAliasingBox<T> { impl<T> Drop for NonAliasingBox<T> {
fn drop(&mut self) { fn drop(&mut self) {
// TODO: figure out why this is necessary, but also this is sqlite so dont think
// i care that much. i tried checking commit history but couldn't find out why
// this was done.
#[allow(clippy::undocumented_unsafe_blocks)]
unsafe { unsafe {
let _ = Box::from_raw(self.0); let _ = Box::from_raw(self.0);
}; };
@@ -65,18 +61,23 @@ impl Engine {
Ok(conn) Ok(conn)
} }
fn write_lock(&self) -> MutexGuard<'_, Connection> { self.writer.lock() } fn write_lock(&self) -> MutexGuard<'_, Connection> {
self.writer.lock()
}
fn read_lock(&self) -> &Connection { fn read_lock(&self) -> &Connection {
self.read_conn_tls.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap()) self.read_conn_tls
.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap())
} }
fn read_lock_iterator(&self) -> &Connection { fn read_lock_iterator(&self) -> &Connection {
self.read_iterator_conn_tls.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap()) self.read_iterator_conn_tls
.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap())
} }
pub fn flush_wal(self: &Arc<Self>) -> Result<()> { pub fn flush_wal(self: &Arc<Self>) -> Result<()> {
self.write_lock().pragma_update(Some(Main), "wal_checkpoint", "RESTART")?; self.write_lock()
.pragma_update(Some(Main), "wal_checkpoint", "RESTART")?;
Ok(()) Ok(())
} }
} }
@@ -87,11 +88,11 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
// calculates cache-size per permanent connection // calculates cache-size per permanent connection
// 1. convert MB to KiB // 1. convert MB to KiB
// 2. divide by permanent connections + permanent iter connections + write // 2. divide by permanent connections + permanent iter connections + write connection
// connection
// 3. round down to nearest integer // 3. round down to nearest integer
let cache_size_per_thread: u32 = let cache_size_per_thread: u32 = ((config.db_cache_capacity_mb * 1024.0)
((config.db_cache_capacity_mb * 1024.0) / ((num_cpus::get().max(1) * 2) + 1) as f64) as u32; / ((num_cpus::get().max(1) * 2) + 1) as f64)
as u32;
let writer = Mutex::new(Engine::prepare_conn(&path, cache_size_per_thread)?); let writer = Mutex::new(Engine::prepare_conn(&path, cache_size_per_thread)?);
@@ -107,10 +108,7 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
} }
fn open_tree(&self, name: &str) -> Result<Arc<dyn KvTree>> { fn open_tree(&self, name: &str) -> Result<Arc<dyn KvTree>> {
self.write_lock().execute( self.write_lock().execute(&format!("CREATE TABLE IF NOT EXISTS {name} ( \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL )"), [])?;
&format!("CREATE TABLE IF NOT EXISTS {name} ( \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL )"),
[],
)?;
Ok(Arc::new(SqliteTable { Ok(Arc::new(SqliteTable {
engine: Arc::clone(self), engine: Arc::clone(self),
@@ -124,7 +122,9 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
Ok(()) Ok(())
} }
fn cleanup(&self) -> Result<()> { self.flush_wal() } fn cleanup(&self) -> Result<()> {
self.flush_wal()
}
} }
pub struct SqliteTable { pub struct SqliteTable {
@@ -145,15 +145,27 @@ impl SqliteTable {
fn insert_with_guard(&self, guard: &Connection, key: &[u8], value: &[u8]) -> Result<()> { fn insert_with_guard(&self, guard: &Connection, key: &[u8], value: &[u8]) -> Result<()> {
guard.execute( guard.execute(
format!("INSERT OR REPLACE INTO {} (key, value) VALUES (?, ?)", self.name).as_str(), format!(
"INSERT OR REPLACE INTO {} (key, value) VALUES (?, ?)",
self.name
)
.as_str(),
[key, value], [key, value],
)?; )?;
Ok(()) Ok(())
} }
pub fn iter_with_guard<'a>(&'a self, guard: &'a Connection) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> { pub fn iter_with_guard<'a>(
&'a self,
guard: &'a Connection,
) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
let statement = Box::leak(Box::new( let statement = Box::leak(Box::new(
guard.prepare(&format!("SELECT key, value FROM {} ORDER BY key ASC", &self.name)).unwrap(), guard
.prepare(&format!(
"SELECT key, value FROM {} ORDER BY key ASC",
&self.name
))
.unwrap(),
)); ));
let statement_ref = NonAliasingBox(statement); let statement_ref = NonAliasingBox(statement);
@@ -164,7 +176,7 @@ impl SqliteTable {
statement statement
.query_map([], |row| Ok((row.get_unwrap(0), row.get_unwrap(1)))) .query_map([], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap() .unwrap()
.map(std::result::Result::unwrap), .map(move |r| r.unwrap()),
); );
Box::new(PreparedStatementIterator { Box::new(PreparedStatementIterator {
@@ -175,7 +187,9 @@ impl SqliteTable {
} }
impl KvTree for SqliteTable { impl KvTree for SqliteTable {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> { self.get_with_guard(self.engine.read_lock(), key) } fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
self.get_with_guard(self.engine.read_lock(), key)
}
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> { fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
let guard = self.engine.write_lock(); let guard = self.engine.write_lock();
@@ -185,7 +199,7 @@ impl KvTree for SqliteTable {
Ok(()) Ok(())
} }
fn insert_batch(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> { fn insert_batch<'a>(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> {
let guard = self.engine.write_lock(); let guard = self.engine.write_lock();
guard.execute("BEGIN", [])?; guard.execute("BEGIN", [])?;
@@ -199,13 +213,14 @@ impl KvTree for SqliteTable {
Ok(()) Ok(())
} }
fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> { fn increment_batch<'a>(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> {
let guard = self.engine.write_lock(); let guard = self.engine.write_lock();
guard.execute("BEGIN", [])?; guard.execute("BEGIN", [])?;
for key in iter { for key in iter {
let old = self.get_with_guard(&guard, &key)?; let old = self.get_with_guard(&guard, &key)?;
let new = crate::utils::increment(old.as_deref()).expect("utils::increment always returns Some"); let new = crate::utils::increment(old.as_deref())
.expect("utils::increment always returns Some");
self.insert_with_guard(&guard, &key, &new)?; self.insert_with_guard(&guard, &key, &new)?;
} }
guard.execute("COMMIT", [])?; guard.execute("COMMIT", [])?;
@@ -218,7 +233,10 @@ impl KvTree for SqliteTable {
fn remove(&self, key: &[u8]) -> Result<()> { fn remove(&self, key: &[u8]) -> Result<()> {
let guard = self.engine.write_lock(); let guard = self.engine.write_lock();
guard.execute(format!("DELETE FROM {} WHERE key = ?", self.name).as_str(), [key])?; guard.execute(
format!("DELETE FROM {} WHERE key = ?", self.name).as_str(),
[key],
)?;
Ok(()) Ok(())
} }
@@ -229,7 +247,11 @@ impl KvTree for SqliteTable {
self.iter_with_guard(guard) self.iter_with_guard(guard)
} }
fn iter_from<'a>(&'a self, from: &[u8], backwards: bool) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> { fn iter_from<'a>(
&'a self,
from: &[u8],
backwards: bool,
) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
let guard = self.engine.read_lock_iterator(); let guard = self.engine.read_lock_iterator();
let from = from.to_vec(); // TODO change interface? let from = from.to_vec(); // TODO change interface?
@@ -251,7 +273,7 @@ impl KvTree for SqliteTable {
statement statement
.query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1)))) .query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap() .unwrap()
.map(std::result::Result::unwrap), .map(move |r| r.unwrap()),
); );
Box::new(PreparedStatementIterator { Box::new(PreparedStatementIterator {
iterator, iterator,
@@ -273,7 +295,7 @@ impl KvTree for SqliteTable {
statement statement
.query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1)))) .query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap() .unwrap()
.map(std::result::Result::unwrap), .map(move |r| r.unwrap()),
); );
Box::new(PreparedStatementIterator { Box::new(PreparedStatementIterator {
@@ -288,7 +310,8 @@ impl KvTree for SqliteTable {
let old = self.get_with_guard(&guard, key)?; let old = self.get_with_guard(&guard, key)?;
let new = crate::utils::increment(old.as_deref()).expect("utils::increment always returns Some"); let new =
crate::utils::increment(old.as_deref()).expect("utils::increment always returns Some");
self.insert_with_guard(&guard, key, &new)?; self.insert_with_guard(&guard, key, &new)?;
@@ -296,7 +319,10 @@ impl KvTree for SqliteTable {
} }
fn scan_prefix<'a>(&'a self, prefix: Vec<u8>) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> { fn scan_prefix<'a>(&'a self, prefix: Vec<u8>) -> Box<dyn Iterator<Item = TupleOfBytes> + 'a> {
Box::new(self.iter_from(&prefix, false).take_while(move |(key, _)| key.starts_with(&prefix))) Box::new(
self.iter_from(&prefix, false)
.take_while(move |(key, _)| key.starts_with(&prefix)),
)
} }
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> { fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
@@ -305,7 +331,9 @@ impl KvTree for SqliteTable {
fn clear(&self) -> Result<()> { fn clear(&self) -> Result<()> {
debug!("clear: running"); debug!("clear: running");
self.engine.write_lock().execute(format!("DELETE FROM {}", self.name).as_str(), [])?; self.engine
.write_lock()
.execute(format!("DELETE FROM {}", self.name).as_str(), [])?;
debug!("clear: ran"); debug!("clear: ran");
Ok(()) Ok(())
} }
+6 -5
View File
@@ -4,7 +4,6 @@ use std::{
pin::Pin, pin::Pin,
sync::RwLock, sync::RwLock,
}; };
use tokio::sync::watch; use tokio::sync::watch;
type Watcher = RwLock<HashMap<Vec<u8>, (watch::Sender<()>, watch::Receiver<()>)>>; type Watcher = RwLock<HashMap<Vec<u8>, (watch::Sender<()>, watch::Receiver<()>)>>;
@@ -15,14 +14,17 @@ pub(super) struct Watchers {
} }
impl Watchers { impl Watchers {
pub(super) fn watch<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> { pub(super) fn watch<'a>(
&'a self,
prefix: &[u8],
) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
let mut rx = match self.watchers.write().unwrap().entry(prefix.to_vec()) { let mut rx = match self.watchers.write().unwrap().entry(prefix.to_vec()) {
hash_map::Entry::Occupied(o) => o.get().1.clone(), hash_map::Entry::Occupied(o) => o.get().1.clone(),
hash_map::Entry::Vacant(v) => { hash_map::Entry::Vacant(v) => {
let (tx, rx) = watch::channel(()); let (tx, rx) = tokio::sync::watch::channel(());
v.insert((tx, rx.clone())); v.insert((tx, rx.clone()));
rx rx
}, }
}; };
Box::pin(async move { Box::pin(async move {
@@ -30,7 +32,6 @@ impl Watchers {
rx.changed().await.unwrap(); rx.changed().await.unwrap();
}) })
} }
pub(super) fn wake(&self, key: &[u8]) { pub(super) fn wake(&self, key: &[u8]) {
let watchers = self.watchers.read().unwrap(); let watchers = self.watchers.read().unwrap();
let mut triggered = Vec::new(); let mut triggered = Vec::new();
+54 -26
View File
@@ -11,21 +11,27 @@ use tracing::warn;
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
impl service::account_data::Data for KeyValueDatabase { impl service::account_data::Data for KeyValueDatabase {
/// Places one event in the account data of the user and removes the /// Places one event in the account data of the user and removes the previous entry.
/// previous entry.
#[tracing::instrument(skip(self, room_id, user_id, event_type, data))] #[tracing::instrument(skip(self, room_id, user_id, event_type, data))]
fn update( fn update(
&self, room_id: Option<&RoomId>, user_id: &UserId, event_type: RoomAccountDataEventType, &self,
room_id: Option<&RoomId>,
user_id: &UserId,
event_type: RoomAccountDataEventType,
data: &serde_json::Value, data: &serde_json::Value,
) -> Result<()> { ) -> Result<()> {
let mut prefix = room_id.map(ToString::to_string).unwrap_or_default().as_bytes().to_vec(); let mut prefix = room_id
prefix.push(0xFF); .map(|r| r.to_string())
.unwrap_or_default()
.as_bytes()
.to_vec();
prefix.push(0xff);
prefix.extend_from_slice(user_id.as_bytes()); prefix.extend_from_slice(user_id.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
let mut roomuserdataid = prefix.clone(); let mut roomuserdataid = prefix.clone();
roomuserdataid.extend_from_slice(&services().globals.next_count()?.to_be_bytes()); roomuserdataid.extend_from_slice(&services().globals.next_count()?.to_be_bytes());
roomuserdataid.push(0xFF); roomuserdataid.push(0xff);
roomuserdataid.extend_from_slice(event_type.to_string().as_bytes()); roomuserdataid.extend_from_slice(event_type.to_string().as_bytes());
let mut key = prefix; let mut key = prefix;
@@ -45,7 +51,8 @@ impl service::account_data::Data for KeyValueDatabase {
let prev = self.roomusertype_roomuserdataid.get(&key)?; let prev = self.roomusertype_roomuserdataid.get(&key)?;
self.roomusertype_roomuserdataid.insert(&key, &roomuserdataid)?; self.roomusertype_roomuserdataid
.insert(&key, &roomuserdataid)?;
// Remove old entry // Remove old entry
if let Some(prev) = prev { if let Some(prev) = prev {
@@ -58,33 +65,54 @@ impl service::account_data::Data for KeyValueDatabase {
/// Searches the account data for a specific kind. /// Searches the account data for a specific kind.
#[tracing::instrument(skip(self, room_id, user_id, kind))] #[tracing::instrument(skip(self, room_id, user_id, kind))]
fn get( fn get(
&self, room_id: Option<&RoomId>, user_id: &UserId, kind: RoomAccountDataEventType, &self,
room_id: Option<&RoomId>,
user_id: &UserId,
kind: RoomAccountDataEventType,
) -> Result<Option<Box<serde_json::value::RawValue>>> { ) -> Result<Option<Box<serde_json::value::RawValue>>> {
let mut key = room_id.map(ToString::to_string).unwrap_or_default().as_bytes().to_vec(); let mut key = room_id
key.push(0xFF); .map(|r| r.to_string())
.unwrap_or_default()
.as_bytes()
.to_vec();
key.push(0xff);
key.extend_from_slice(user_id.as_bytes()); key.extend_from_slice(user_id.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(kind.to_string().as_bytes()); key.extend_from_slice(kind.to_string().as_bytes());
self.roomusertype_roomuserdataid self.roomusertype_roomuserdataid
.get(&key)? .get(&key)?
.and_then(|roomuserdataid| self.roomuserdataid_accountdata.get(&roomuserdataid).transpose()) .and_then(|roomuserdataid| {
self.roomuserdataid_accountdata
.get(&roomuserdataid)
.transpose()
})
.transpose()? .transpose()?
.map(|data| serde_json::from_slice(&data).map_err(|_| Error::bad_database("could not deserialize"))) .map(|data| {
serde_json::from_slice(&data)
.map_err(|_| Error::bad_database("could not deserialize"))
})
.transpose() .transpose()
} }
/// Returns all changes to the account data that happened after `since`. /// Returns all changes to the account data that happened after `since`.
#[tracing::instrument(skip(self, room_id, user_id, since))] #[tracing::instrument(skip(self, room_id, user_id, since))]
fn changes_since( fn changes_since(
&self, room_id: Option<&RoomId>, user_id: &UserId, since: u64, &self,
room_id: Option<&RoomId>,
user_id: &UserId,
since: u64,
) -> Result<HashMap<RoomAccountDataEventType, Raw<AnyEphemeralRoomEvent>>> { ) -> Result<HashMap<RoomAccountDataEventType, Raw<AnyEphemeralRoomEvent>>> {
let mut userdata = HashMap::new(); let mut userdata = HashMap::new();
let mut prefix = room_id.map(ToString::to_string).unwrap_or_default().as_bytes().to_vec(); let mut prefix = room_id
prefix.push(0xFF); .map(|r| r.to_string())
.unwrap_or_default()
.as_bytes()
.to_vec();
prefix.push(0xff);
prefix.extend_from_slice(user_id.as_bytes()); prefix.extend_from_slice(user_id.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
// Skip the data that's exactly at since, because we sent that last time // Skip the data that's exactly at since, because we sent that last time
let mut first_possible = prefix.clone(); let mut first_possible = prefix.clone();
@@ -97,20 +125,20 @@ impl service::account_data::Data for KeyValueDatabase {
.map(|(k, v)| { .map(|(k, v)| {
Ok::<_, Error>(( Ok::<_, Error>((
RoomAccountDataEventType::from( RoomAccountDataEventType::from(
utils::string_from_bytes( utils::string_from_bytes(k.rsplit(|&b| b == 0xff).next().ok_or_else(
k.rsplit(|&b| b == 0xFF) || Error::bad_database("RoomUserData ID in db is invalid."),
.next() )?)
.ok_or_else(|| Error::bad_database("RoomUserData ID in db is invalid."))?,
)
.map_err(|e| { .map_err(|e| {
warn!("RoomUserData ID in database is invalid: {}", e); warn!("RoomUserData ID in database is invalid: {}", e);
Error::bad_database("RoomUserData ID in db is invalid.") Error::bad_database("RoomUserData ID in db is invalid.")
})?, })?,
), ),
serde_json::from_slice::<Raw<AnyEphemeralRoomEvent>>(&v) serde_json::from_slice::<Raw<AnyEphemeralRoomEvent>>(&v).map_err(|_| {
.map_err(|_| Error::bad_database("Database contains invalid account data."))?, Error::bad_database("Database contains invalid account data.")
})?,
)) ))
}) { })
{
let (kind, data) = r?; let (kind, data) = r?;
userdata.insert(kind, data); userdata.insert(kind, data);
} }
+32 -12
View File
@@ -6,8 +6,14 @@ impl service::appservice::Data for KeyValueDatabase {
/// Registers an appservice and returns the ID to the caller /// Registers an appservice and returns the ID to the caller
fn register_appservice(&self, yaml: Registration) -> Result<String> { fn register_appservice(&self, yaml: Registration) -> Result<String> {
let id = yaml.id.as_str(); let id = yaml.id.as_str();
self.id_appserviceregistrations.insert(id.as_bytes(), serde_yaml::to_string(&yaml).unwrap().as_bytes())?; self.id_appserviceregistrations.insert(
self.cached_registrations.write().unwrap().insert(id.to_owned(), yaml.clone()); id.as_bytes(),
serde_yaml::to_string(&yaml).unwrap().as_bytes(),
)?;
self.cached_registrations
.write()
.unwrap()
.insert(id.to_owned(), yaml.to_owned());
Ok(id.to_owned()) Ok(id.to_owned())
} }
@@ -18,19 +24,29 @@ impl service::appservice::Data for KeyValueDatabase {
/// ///
/// * `service_name` - the name you send to register the service previously /// * `service_name` - the name you send to register the service previously
fn unregister_appservice(&self, service_name: &str) -> Result<()> { fn unregister_appservice(&self, service_name: &str) -> Result<()> {
self.id_appserviceregistrations.remove(service_name.as_bytes())?; self.id_appserviceregistrations
self.cached_registrations.write().unwrap().remove(service_name); .remove(service_name.as_bytes())?;
self.cached_registrations
.write()
.unwrap()
.remove(service_name);
Ok(()) Ok(())
} }
fn get_registration(&self, id: &str) -> Result<Option<Registration>> { fn get_registration(&self, id: &str) -> Result<Option<Registration>> {
self.cached_registrations.read().unwrap().get(id).map_or_else( self.cached_registrations
.read()
.unwrap()
.get(id)
.map_or_else(
|| { || {
self.id_appserviceregistrations self.id_appserviceregistrations
.get(id.as_bytes())? .get(id.as_bytes())?
.map(|bytes| { .map(|bytes| {
serde_yaml::from_slice(&bytes).map_err(|_| { serde_yaml::from_slice(&bytes).map_err(|_| {
Error::bad_database("Invalid registration bytes in id_appserviceregistrations.") Error::bad_database(
"Invalid registration bytes in id_appserviceregistrations.",
)
}) })
}) })
.transpose() .transpose()
@@ -40,19 +56,23 @@ impl service::appservice::Data for KeyValueDatabase {
} }
fn iter_ids<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<String>> + 'a>> { fn iter_ids<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<String>> + 'a>> {
Ok(Box::new(self.id_appserviceregistrations.iter().map(|(id, _)| { Ok(Box::new(self.id_appserviceregistrations.iter().map(
utils::string_from_bytes(&id) |(id, _)| {
.map_err(|_| Error::bad_database("Invalid id bytes in id_appserviceregistrations.")) utils::string_from_bytes(&id).map_err(|_| {
}))) Error::bad_database("Invalid id bytes in id_appserviceregistrations.")
})
},
)))
} }
fn all(&self) -> Result<Vec<(String, Registration)>> { fn all(&self) -> Result<Vec<(String, Registration)>> {
self.iter_ids()? self.iter_ids()?
.filter_map(std::result::Result::ok) .filter_map(|id| id.ok())
.map(move |id| { .map(move |id| {
Ok(( Ok((
id.clone(), id.clone(),
self.get_registration(&id)?.expect("iter_ids only returns appservices that exist"), self.get_registration(&id)?
.expect("iter_ids only returns appservices that exist"),
)) ))
}) })
.collect() .collect()
+69 -40
View File
@@ -8,7 +8,6 @@ use ruma::{
signatures::Ed25519KeyPair, signatures::Ed25519KeyPair,
DeviceId, MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId, ServerName, UserId, DeviceId, MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId, ServerName, UserId,
}; };
use tracing::debug;
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
@@ -24,32 +23,36 @@ impl service::globals::Data for KeyValueDatabase {
fn current_count(&self) -> Result<u64> { fn current_count(&self) -> Result<u64> {
self.global.get(COUNTER)?.map_or(Ok(0_u64), |bytes| { self.global.get(COUNTER)?.map_or(Ok(0_u64), |bytes| {
utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Count has invalid bytes.")) utils::u64_from_bytes(&bytes)
.map_err(|_| Error::bad_database("Count has invalid bytes."))
}) })
} }
fn last_check_for_updates_id(&self) -> Result<u64> { fn last_check_for_updates_id(&self) -> Result<u64> {
self.global.get(LAST_CHECK_FOR_UPDATES_COUNT)?.map_or(Ok(0_u64), |bytes| { self.global
utils::u64_from_bytes(&bytes) .get(LAST_CHECK_FOR_UPDATES_COUNT)?
.map_err(|_| Error::bad_database("last check for updates count has invalid bytes.")) .map_or(Ok(0_u64), |bytes| {
utils::u64_from_bytes(&bytes).map_err(|_| {
Error::bad_database("last check for updates count has invalid bytes.")
})
}) })
} }
fn update_check_for_updates_id(&self, id: u64) -> Result<()> { fn update_check_for_updates_id(&self, id: u64) -> Result<()> {
self.global.insert(LAST_CHECK_FOR_UPDATES_COUNT, &id.to_be_bytes())?; self.global
.insert(LAST_CHECK_FOR_UPDATES_COUNT, &id.to_be_bytes())?;
Ok(()) Ok(())
} }
#[allow(unused_qualifications)] // async traits
async fn watch(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> { async fn watch(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> {
let userid_bytes = user_id.as_bytes().to_vec(); let userid_bytes = user_id.as_bytes().to_vec();
let mut userid_prefix = userid_bytes.clone(); let mut userid_prefix = userid_bytes.clone();
userid_prefix.push(0xFF); userid_prefix.push(0xff);
let mut userdeviceid_prefix = userid_prefix.clone(); let mut userdeviceid_prefix = userid_prefix.clone();
userdeviceid_prefix.extend_from_slice(device_id.as_bytes()); userdeviceid_prefix.extend_from_slice(device_id.as_bytes());
userdeviceid_prefix.push(0xFF); userdeviceid_prefix.push(0xff);
let mut futures = FuturesUnordered::new(); let mut futures = FuturesUnordered::new();
@@ -60,11 +63,19 @@ impl service::globals::Data for KeyValueDatabase {
futures.push(self.userroomid_joined.watch_prefix(&userid_prefix)); futures.push(self.userroomid_joined.watch_prefix(&userid_prefix));
futures.push(self.userroomid_invitestate.watch_prefix(&userid_prefix)); futures.push(self.userroomid_invitestate.watch_prefix(&userid_prefix));
futures.push(self.userroomid_leftstate.watch_prefix(&userid_prefix)); futures.push(self.userroomid_leftstate.watch_prefix(&userid_prefix));
futures.push(self.userroomid_notificationcount.watch_prefix(&userid_prefix)); futures.push(
self.userroomid_notificationcount
.watch_prefix(&userid_prefix),
);
futures.push(self.userroomid_highlightcount.watch_prefix(&userid_prefix)); futures.push(self.userroomid_highlightcount.watch_prefix(&userid_prefix));
// Events for rooms we are in // Events for rooms we are in
for room_id in services().rooms.state_cache.rooms_joined(user_id).filter_map(Result::ok) { for room_id in services()
.rooms
.state_cache
.rooms_joined(user_id)
.filter_map(|r| r.ok())
{
let short_roomid = services() let short_roomid = services()
.rooms .rooms
.short .short
@@ -77,7 +88,7 @@ impl service::globals::Data for KeyValueDatabase {
let roomid_bytes = room_id.as_bytes().to_vec(); let roomid_bytes = room_id.as_bytes().to_vec();
let mut roomid_prefix = roomid_bytes.clone(); let mut roomid_prefix = roomid_bytes.clone();
roomid_prefix.push(0xFF); roomid_prefix.push(0xff);
// PDUs // PDUs
futures.push(self.pduid_pdu.watch_prefix(&short_roomid)); futures.push(self.pduid_pdu.watch_prefix(&short_roomid));
@@ -94,13 +105,19 @@ impl service::globals::Data for KeyValueDatabase {
let mut roomuser_prefix = roomid_prefix.clone(); let mut roomuser_prefix = roomid_prefix.clone();
roomuser_prefix.extend_from_slice(&userid_prefix); roomuser_prefix.extend_from_slice(&userid_prefix);
futures.push(self.roomusertype_roomuserdataid.watch_prefix(&roomuser_prefix)); futures.push(
self.roomusertype_roomuserdataid
.watch_prefix(&roomuser_prefix),
);
} }
let mut globaluserdata_prefix = vec![0xFF]; let mut globaluserdata_prefix = vec![0xff];
globaluserdata_prefix.extend_from_slice(&userid_prefix); globaluserdata_prefix.extend_from_slice(&userid_prefix);
futures.push(self.roomusertype_roomuserdataid.watch_prefix(&globaluserdata_prefix)); futures.push(
self.roomusertype_roomuserdataid
.watch_prefix(&globaluserdata_prefix),
);
// More key changes (used when user is not joined to any rooms) // More key changes (used when user is not joined to any rooms)
futures.push(self.keychangeid_userid.watch_prefix(&userid_prefix)); futures.push(self.keychangeid_userid.watch_prefix(&userid_prefix));
@@ -116,9 +133,9 @@ impl service::globals::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
fn cleanup(&self) -> Result<()> { self.db.cleanup() } fn cleanup(&self) -> Result<()> {
self._db.cleanup()
fn flush(&self) -> Result<()> { self.db.flush() } }
fn memory_usage(&self) -> String { fn memory_usage(&self) -> String {
let pdu_cache = self.pdu_cache.lock().unwrap().len(); let pdu_cache = self.pdu_cache.lock().unwrap().len();
@@ -141,7 +158,7 @@ our_real_users_cache: {our_real_users_cache}
appservice_in_room_cache: {appservice_in_room_cache} appservice_in_room_cache: {appservice_in_room_cache}
lasttimelinecount_cache: {lasttimelinecount_cache}\n" lasttimelinecount_cache: {lasttimelinecount_cache}\n"
); );
if let Ok(db_stats) = self.db.memory_usage() { if let Ok(db_stats) = self._db.memory_usage() {
response += &db_stats; response += &db_stats;
} }
@@ -186,24 +203,23 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
fn load_keypair(&self) -> Result<Ed25519KeyPair> { fn load_keypair(&self) -> Result<Ed25519KeyPair> {
let keypair_bytes = self.global.get(b"keypair")?.map_or_else( let keypair_bytes = self.global.get(b"keypair")?.map_or_else(
|| { || {
debug!("No keypair found in database, assuming this is a new deployment and generating one.");
let keypair = utils::generate_keypair(); let keypair = utils::generate_keypair();
debug!("Generated keypair bytes: {:?}", keypair);
self.global.insert(b"keypair", &keypair)?; self.global.insert(b"keypair", &keypair)?;
Ok::<_, Error>(keypair) Ok::<_, Error>(keypair)
}, },
Ok, |s| Ok(s.to_vec()),
)?; )?;
let mut parts = keypair_bytes.splitn(2, |&b| b == 0xFF); let mut parts = keypair_bytes.splitn(2, |&b| b == 0xff);
utils::string_from_bytes( utils::string_from_bytes(
// 1. version // 1. version
parts.next().expect("splitn always returns at least one element"), parts
.next()
.expect("splitn always returns at least one element"),
) )
.map_err(|_| Error::bad_database("Invalid version bytes in keypair.")) .map_err(|_| Error::bad_database("Invalid version bytes in keypair."))
.and_then(|version| { .and_then(|version| {
debug!("Keypair version: {version}");
// 2. key // 2. key
parts parts
.next() .next()
@@ -211,23 +227,25 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
.map(|key| (version, key)) .map(|key| (version, key))
}) })
.and_then(|(version, key)| { .and_then(|(version, key)| {
debug!("Keypair bytes: {:?}", key); Ed25519KeyPair::from_der(key, version)
let keypair = Ed25519KeyPair::from_der(key, version) .map_err(|_| Error::bad_database("Private or public keys are invalid."))
.map_err(|_| Error::bad_database("Private or public keys are invalid."));
debug!("Private and public key: {keypair:?}");
keypair
}) })
} }
fn remove_keypair(&self) -> Result<()> {
fn remove_keypair(&self) -> Result<()> { self.global.remove(b"keypair") } self.global.remove(b"keypair")
}
fn add_signing_key( fn add_signing_key(
&self, origin: &ServerName, new_keys: ServerSigningKeys, &self,
origin: &ServerName,
new_keys: ServerSigningKeys,
) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> { ) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
// Not atomic, but this is not critical // Not atomic, but this is not critical
let signingkeys = self.server_signingkeys.get(origin.as_bytes())?; let signingkeys = self.server_signingkeys.get(origin.as_bytes())?;
let mut keys = signingkeys.and_then(|keys| serde_json::from_slice(&keys).ok()).unwrap_or_else(|| { let mut keys = signingkeys
.and_then(|keys| serde_json::from_slice(&keys).ok())
.unwrap_or_else(|| {
// Just insert "now", it doesn't matter // Just insert "now", it doesn't matter
ServerSigningKeys::new(origin.to_owned(), MilliSecondsSinceUnixEpoch::now()) ServerSigningKeys::new(origin.to_owned(), MilliSecondsSinceUnixEpoch::now())
}); });
@@ -247,21 +265,31 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
)?; )?;
let mut tree = keys.verify_keys; let mut tree = keys.verify_keys;
tree.extend(keys.old_verify_keys.into_iter().map(|old| (old.0, VerifyKey::new(old.1.key)))); tree.extend(
keys.old_verify_keys
.into_iter()
.map(|old| (old.0, VerifyKey::new(old.1.key))),
);
Ok(tree) Ok(tree)
} }
/// This returns an empty `Ok(BTreeMap<..>)` when there are no keys found /// This returns an empty `Ok(BTreeMap<..>)` when there are no keys found for the server.
/// for the server. fn signing_keys_for(
fn signing_keys_for(&self, origin: &ServerName) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> { &self,
origin: &ServerName,
) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
let signingkeys = self let signingkeys = self
.server_signingkeys .server_signingkeys
.get(origin.as_bytes())? .get(origin.as_bytes())?
.and_then(|bytes| serde_json::from_slice(&bytes).ok()) .and_then(|bytes| serde_json::from_slice(&bytes).ok())
.map(|keys: ServerSigningKeys| { .map(|keys: ServerSigningKeys| {
let mut tree = keys.verify_keys; let mut tree = keys.verify_keys;
tree.extend(keys.old_verify_keys.into_iter().map(|old| (old.0, VerifyKey::new(old.1.key)))); tree.extend(
keys.old_verify_keys
.into_iter()
.map(|old| (old.0, VerifyKey::new(old.1.key))),
);
tree tree
}) })
.unwrap_or_else(BTreeMap::new); .unwrap_or_else(BTreeMap::new);
@@ -271,7 +299,8 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
fn database_version(&self) -> Result<u64> { fn database_version(&self) -> Result<u64> {
self.global.get(b"version")?.map_or(Ok(0), |version| { self.global.get(b"version")?.map_or(Ok(0), |version| {
utils::u64_from_bytes(&version).map_err(|_| Error::bad_database("Database version id is invalid.")) utils::u64_from_bytes(&version)
.map_err(|_| Error::bad_database("Database version id is invalid."))
}) })
} }
+144 -72
View File
@@ -12,30 +12,35 @@ use ruma::{
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
impl service::key_backups::Data for KeyValueDatabase { impl service::key_backups::Data for KeyValueDatabase {
fn create_backup(&self, user_id: &UserId, backup_metadata: &Raw<BackupAlgorithm>) -> Result<String> { fn create_backup(
&self,
user_id: &UserId,
backup_metadata: &Raw<BackupAlgorithm>,
) -> Result<String> {
let version = services().globals.next_count()?.to_string(); let version = services().globals.next_count()?.to_string();
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
self.backupid_algorithm.insert( self.backupid_algorithm.insert(
&key, &key,
&serde_json::to_vec(backup_metadata).expect("BackupAlgorithm::to_vec always works"), &serde_json::to_vec(backup_metadata).expect("BackupAlgorithm::to_vec always works"),
)?; )?;
self.backupid_etag.insert(&key, &services().globals.next_count()?.to_be_bytes())?; self.backupid_etag
.insert(&key, &services().globals.next_count()?.to_be_bytes())?;
Ok(version) Ok(version)
} }
fn delete_backup(&self, user_id: &UserId, version: &str) -> Result<()> { fn delete_backup(&self, user_id: &UserId, version: &str) -> Result<()> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
self.backupid_algorithm.remove(&key)?; self.backupid_algorithm.remove(&key)?;
self.backupid_etag.remove(&key)?; self.backupid_etag.remove(&key)?;
key.push(0xFF); key.push(0xff);
for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) { for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) {
self.backupkeyid_backup.remove(&outdated_key)?; self.backupkeyid_backup.remove(&outdated_key)?;
@@ -44,23 +49,33 @@ impl service::key_backups::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
fn update_backup(&self, user_id: &UserId, version: &str, backup_metadata: &Raw<BackupAlgorithm>) -> Result<String> { fn update_backup(
&self,
user_id: &UserId,
version: &str,
backup_metadata: &Raw<BackupAlgorithm>,
) -> Result<String> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
if self.backupid_algorithm.get(&key)?.is_none() { if self.backupid_algorithm.get(&key)?.is_none() {
return Err(Error::BadRequest(ErrorKind::NotFound, "Tried to update nonexistent backup.")); return Err(Error::BadRequest(
ErrorKind::NotFound,
"Tried to update nonexistent backup.",
));
} }
self.backupid_algorithm.insert(&key, backup_metadata.json().get().as_bytes())?; self.backupid_algorithm
self.backupid_etag.insert(&key, &services().globals.next_count()?.to_be_bytes())?; .insert(&key, backup_metadata.json().get().as_bytes())?;
self.backupid_etag
.insert(&key, &services().globals.next_count()?.to_be_bytes())?;
Ok(version.to_owned()) Ok(version.to_owned())
} }
fn get_latest_backup_version(&self, user_id: &UserId) -> Result<Option<String>> { fn get_latest_backup_version(&self, user_id: &UserId) -> Result<Option<String>> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
let mut last_possible_key = prefix.clone(); let mut last_possible_key = prefix.clone();
last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes()); last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes());
@@ -69,15 +84,22 @@ impl service::key_backups::Data for KeyValueDatabase {
.take_while(move |(k, _)| k.starts_with(&prefix)) .take_while(move |(k, _)| k.starts_with(&prefix))
.next() .next()
.map(|(key, _)| { .map(|(key, _)| {
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element")) utils::string_from_bytes(
key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| Error::bad_database("backupid_algorithm key is invalid.")) .map_err(|_| Error::bad_database("backupid_algorithm key is invalid."))
}) })
.transpose() .transpose()
} }
fn get_latest_backup(&self, user_id: &UserId) -> Result<Option<(String, Raw<BackupAlgorithm>)>> { fn get_latest_backup(
&self,
user_id: &UserId,
) -> Result<Option<(String, Raw<BackupAlgorithm>)>> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
let mut last_possible_key = prefix.clone(); let mut last_possible_key = prefix.clone();
last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes()); last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes());
@@ -87,14 +109,17 @@ impl service::key_backups::Data for KeyValueDatabase {
.next() .next()
.map(|(key, value)| { .map(|(key, value)| {
let version = utils::string_from_bytes( let version = utils::string_from_bytes(
key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element"), key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
) )
.map_err(|_| Error::bad_database("backupid_algorithm key is invalid."))?; .map_err(|_| Error::bad_database("backupid_algorithm key is invalid."))?;
Ok(( Ok((
version, version,
serde_json::from_slice(&value) serde_json::from_slice(&value).map_err(|_| {
.map_err(|_| Error::bad_database("Algorithm in backupid_algorithm is invalid."))?, Error::bad_database("Algorithm in backupid_algorithm is invalid.")
})?,
)) ))
}) })
.transpose() .transpose()
@@ -102,41 +127,53 @@ impl service::key_backups::Data for KeyValueDatabase {
fn get_backup(&self, user_id: &UserId, version: &str) -> Result<Option<Raw<BackupAlgorithm>>> { fn get_backup(&self, user_id: &UserId, version: &str) -> Result<Option<Raw<BackupAlgorithm>>> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
self.backupid_algorithm.get(&key)?.map_or(Ok(None), |bytes| { self.backupid_algorithm
.get(&key)?
.map_or(Ok(None), |bytes| {
serde_json::from_slice(&bytes) serde_json::from_slice(&bytes)
.map_err(|_| Error::bad_database("Algorithm in backupid_algorithm is invalid.")) .map_err(|_| Error::bad_database("Algorithm in backupid_algorithm is invalid."))
}) })
} }
fn add_key( fn add_key(
&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str, key_data: &Raw<KeyBackupData>, &self,
user_id: &UserId,
version: &str,
room_id: &RoomId,
session_id: &str,
key_data: &Raw<KeyBackupData>,
) -> Result<()> { ) -> Result<()> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
if self.backupid_algorithm.get(&key)?.is_none() { if self.backupid_algorithm.get(&key)?.is_none() {
return Err(Error::BadRequest(ErrorKind::NotFound, "Tried to update nonexistent backup.")); return Err(Error::BadRequest(
ErrorKind::NotFound,
"Tried to update nonexistent backup.",
));
} }
self.backupid_etag.insert(&key, &services().globals.next_count()?.to_be_bytes())?; self.backupid_etag
.insert(&key, &services().globals.next_count()?.to_be_bytes())?;
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(session_id.as_bytes()); key.extend_from_slice(session_id.as_bytes());
self.backupkeyid_backup.insert(&key, key_data.json().get().as_bytes())?; self.backupkeyid_backup
.insert(&key, key_data.json().get().as_bytes())?;
Ok(()) Ok(())
} }
fn count_keys(&self, user_id: &UserId, version: &str) -> Result<usize> { fn count_keys(&self, user_id: &UserId, version: &str) -> Result<usize> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(version.as_bytes()); prefix.extend_from_slice(version.as_bytes());
Ok(self.backupkeyid_backup.scan_prefix(prefix).count()) Ok(self.backupkeyid_backup.scan_prefix(prefix).count())
@@ -144,45 +181,62 @@ impl service::key_backups::Data for KeyValueDatabase {
fn get_etag(&self, user_id: &UserId, version: &str) -> Result<String> { fn get_etag(&self, user_id: &UserId, version: &str) -> Result<String> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
Ok(utils::u64_from_bytes( Ok(utils::u64_from_bytes(
&self.backupid_etag.get(&key)?.ok_or_else(|| Error::bad_database("Backup has no etag."))?, &self
.backupid_etag
.get(&key)?
.ok_or_else(|| Error::bad_database("Backup has no etag."))?,
) )
.map_err(|_| Error::bad_database("etag in backupid_etag invalid."))? .map_err(|_| Error::bad_database("etag in backupid_etag invalid."))?
.to_string()) .to_string())
} }
fn get_all(&self, user_id: &UserId, version: &str) -> Result<BTreeMap<OwnedRoomId, RoomKeyBackup>> { fn get_all(
&self,
user_id: &UserId,
version: &str,
) -> Result<BTreeMap<OwnedRoomId, RoomKeyBackup>> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(version.as_bytes()); prefix.extend_from_slice(version.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
let mut rooms = BTreeMap::<OwnedRoomId, RoomKeyBackup>::new(); let mut rooms = BTreeMap::<OwnedRoomId, RoomKeyBackup>::new();
for result in self.backupkeyid_backup.scan_prefix(prefix).map(|(key, value)| { for result in self
let mut parts = key.rsplit(|&b| b == 0xFF); .backupkeyid_backup
.scan_prefix(prefix)
.map(|(key, value)| {
let mut parts = key.rsplit(|&b| b == 0xff);
let session_id = utils::string_from_bytes( let session_id =
parts.next().ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?, utils::string_from_bytes(parts.next().ok_or_else(|| {
) Error::bad_database("backupkeyid_backup key is invalid.")
.map_err(|_| Error::bad_database("backupkeyid_backup session_id is invalid."))?; })?)
.map_err(|_| {
Error::bad_database("backupkeyid_backup session_id is invalid.")
})?;
let room_id = RoomId::parse( let room_id = RoomId::parse(
utils::string_from_bytes( utils::string_from_bytes(parts.next().ok_or_else(|| {
parts.next().ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?, Error::bad_database("backupkeyid_backup key is invalid.")
) })?)
.map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid."))?, .map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid."))?,
) )
.map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid room id."))?; .map_err(|_| {
Error::bad_database("backupkeyid_backup room_id is invalid room id.")
})?;
let key_data = serde_json::from_slice(&value) let key_data = serde_json::from_slice(&value).map_err(|_| {
.map_err(|_| Error::bad_database("KeyBackupData in backupkeyid_backup is invalid."))?; Error::bad_database("KeyBackupData in backupkeyid_backup is invalid.")
})?;
Ok::<_, Error>((room_id, session_id, key_data)) Ok::<_, Error>((room_id, session_id, key_data))
}) { })
{
let (room_id, session_id, key_data) = result?; let (room_id, session_id, key_data) = result?;
rooms rooms
.entry(room_id) .entry(room_id)
@@ -197,60 +251,72 @@ impl service::key_backups::Data for KeyValueDatabase {
} }
fn get_room( fn get_room(
&self, user_id: &UserId, version: &str, room_id: &RoomId, &self,
user_id: &UserId,
version: &str,
room_id: &RoomId,
) -> Result<BTreeMap<String, Raw<KeyBackupData>>> { ) -> Result<BTreeMap<String, Raw<KeyBackupData>>> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(version.as_bytes()); prefix.extend_from_slice(version.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(room_id.as_bytes()); prefix.extend_from_slice(room_id.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
Ok(self Ok(self
.backupkeyid_backup .backupkeyid_backup
.scan_prefix(prefix) .scan_prefix(prefix)
.map(|(key, value)| { .map(|(key, value)| {
let mut parts = key.rsplit(|&b| b == 0xFF); let mut parts = key.rsplit(|&b| b == 0xff);
let session_id = utils::string_from_bytes( let session_id =
parts.next().ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?, utils::string_from_bytes(parts.next().ok_or_else(|| {
) Error::bad_database("backupkeyid_backup key is invalid.")
.map_err(|_| Error::bad_database("backupkeyid_backup session_id is invalid."))?; })?)
.map_err(|_| {
Error::bad_database("backupkeyid_backup session_id is invalid.")
})?;
let key_data = serde_json::from_slice(&value) let key_data = serde_json::from_slice(&value).map_err(|_| {
.map_err(|_| Error::bad_database("KeyBackupData in backupkeyid_backup is invalid."))?; Error::bad_database("KeyBackupData in backupkeyid_backup is invalid.")
})?;
Ok::<_, Error>((session_id, key_data)) Ok::<_, Error>((session_id, key_data))
}) })
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.collect()) .collect())
} }
fn get_session( fn get_session(
&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str, &self,
user_id: &UserId,
version: &str,
room_id: &RoomId,
session_id: &str,
) -> Result<Option<Raw<KeyBackupData>>> { ) -> Result<Option<Raw<KeyBackupData>>> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(session_id.as_bytes()); key.extend_from_slice(session_id.as_bytes());
self.backupkeyid_backup self.backupkeyid_backup
.get(&key)? .get(&key)?
.map(|value| { .map(|value| {
serde_json::from_slice(&value) serde_json::from_slice(&value).map_err(|_| {
.map_err(|_| Error::bad_database("KeyBackupData in backupkeyid_backup is invalid.")) Error::bad_database("KeyBackupData in backupkeyid_backup is invalid.")
})
}) })
.transpose() .transpose()
} }
fn delete_all_keys(&self, user_id: &UserId, version: &str) -> Result<()> { fn delete_all_keys(&self, user_id: &UserId, version: &str) -> Result<()> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
key.push(0xFF); key.push(0xff);
for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) { for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) {
self.backupkeyid_backup.remove(&outdated_key)?; self.backupkeyid_backup.remove(&outdated_key)?;
@@ -261,11 +327,11 @@ impl service::key_backups::Data for KeyValueDatabase {
fn delete_room_keys(&self, user_id: &UserId, version: &str, room_id: &RoomId) -> Result<()> { fn delete_room_keys(&self, user_id: &UserId, version: &str, room_id: &RoomId) -> Result<()> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
key.push(0xFF); key.push(0xff);
for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) { for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) {
self.backupkeyid_backup.remove(&outdated_key)?; self.backupkeyid_backup.remove(&outdated_key)?;
@@ -274,13 +340,19 @@ impl service::key_backups::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
fn delete_room_key(&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str) -> Result<()> { fn delete_room_key(
&self,
user_id: &UserId,
version: &str,
room_id: &RoomId,
session_id: &str,
) -> Result<()> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(version.as_bytes()); key.extend_from_slice(version.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(session_id.as_bytes()); key.extend_from_slice(session_id.as_bytes());
for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) { for (outdated_key, _) in self.backupkeyid_backup.scan_prefix(key) {
+110 -119
View File
@@ -1,95 +1,55 @@
use ruma::api::client::error::ErrorKind; use ruma::api::client::error::ErrorKind;
use tracing::debug;
use crate::{ use crate::{
database::KeyValueDatabase, database::KeyValueDatabase,
service::{self, media::UrlPreviewData}, service::{self, media::UrlPreviewData},
utils::string_from_bytes, utils, Error, Result,
Error, Result,
}; };
impl service::media::Data for KeyValueDatabase { impl service::media::Data for KeyValueDatabase {
fn create_file_metadata( fn create_file_metadata(
&self, sender_user: Option<&str>, mxc: String, width: u32, height: u32, content_disposition: Option<&str>, &self,
mxc: String,
width: u32,
height: u32,
content_disposition: Option<&str>,
content_type: Option<&str>, content_type: Option<&str>,
) -> Result<Vec<u8>> { ) -> Result<Vec<u8>> {
let mut key = mxc.as_bytes().to_vec(); let mut key = mxc.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(&width.to_be_bytes()); key.extend_from_slice(&width.to_be_bytes());
key.extend_from_slice(&height.to_be_bytes()); key.extend_from_slice(&height.to_be_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(content_disposition.as_ref().map(|f| f.as_bytes()).unwrap_or_default()); key.extend_from_slice(
key.push(0xFF); content_disposition
key.extend_from_slice(content_type.as_ref().map(|c| c.as_bytes()).unwrap_or_default()); .as_ref()
.map(|f| f.as_bytes())
.unwrap_or_default(),
);
key.push(0xff);
key.extend_from_slice(
content_type
.as_ref()
.map(|c| c.as_bytes())
.unwrap_or_default(),
);
self.mediaid_file.insert(&key, &[])?; self.mediaid_file.insert(&key, &[])?;
if let Some(user) = sender_user {
let key = mxc.as_bytes().to_vec();
let user = user.as_bytes().to_vec();
self.mediaid_user.insert(&key, &user)?;
}
Ok(key) Ok(key)
} }
fn delete_file_mxc(&self, mxc: String) -> Result<()> {
debug!("MXC URI: {:?}", mxc);
let mut prefix = mxc.as_bytes().to_vec();
prefix.push(0xFF);
debug!("MXC db prefix: {prefix:?}");
for (key, _) in self.mediaid_file.scan_prefix(prefix) {
debug!("Deleting key: {:?}", key);
self.mediaid_file.remove(&key)?;
}
for (key, value) in self.mediaid_user.scan_prefix(mxc.as_bytes().to_vec()) {
if key == mxc.as_bytes().to_vec() {
let user = string_from_bytes(&value).unwrap_or_default();
debug!("Deleting key \"{key:?}\" which was uploaded by user {user}");
self.mediaid_user.remove(&key)?;
}
}
Ok(())
}
/// Searches for all files with the given MXC
fn search_mxc_metadata_prefix(&self, mxc: String) -> Result<Vec<Vec<u8>>> {
debug!("MXC URI: {:?}", mxc);
let mut prefix = mxc.as_bytes().to_vec();
prefix.push(0xFF);
let mut keys: Vec<Vec<u8>> = vec![];
for (key, _) in self.mediaid_file.scan_prefix(prefix) {
keys.push(key);
}
if keys.is_empty() {
return Err(Error::bad_database(
"Failed to find any keys in database with the provided MXC.",
));
}
debug!("Got the following keys: {:?}", keys);
Ok(keys)
}
fn search_file_metadata( fn search_file_metadata(
&self, mxc: String, width: u32, height: u32, &self,
mxc: String,
width: u32,
height: u32,
) -> Result<(Option<String>, Option<String>, Vec<u8>)> { ) -> Result<(Option<String>, Option<String>, Vec<u8>)> {
let mut prefix = mxc.as_bytes().to_vec(); let mut prefix = mxc.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(&width.to_be_bytes()); prefix.extend_from_slice(&width.to_be_bytes());
prefix.extend_from_slice(&height.to_be_bytes()); prefix.extend_from_slice(&height.to_be_bytes());
prefix.push(0xFF); prefix.push(0xff);
let (key, _) = self let (key, _) = self
.mediaid_file .mediaid_file
@@ -97,58 +57,71 @@ impl service::media::Data for KeyValueDatabase {
.next() .next()
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Media not found"))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Media not found"))?;
let mut parts = key.rsplit(|&b| b == 0xFF); let mut parts = key.rsplit(|&b| b == 0xff);
let content_type = parts let content_type = parts
.next() .next()
.map(|bytes| { .map(|bytes| {
string_from_bytes(bytes) utils::string_from_bytes(bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Content type in mediaid_file is invalid unicode.")) Error::bad_database("Content type in mediaid_file is invalid unicode.")
})
}) })
.transpose()?; .transpose()?;
let content_disposition_bytes = let content_disposition_bytes = parts
parts.next().ok_or_else(|| Error::bad_database("Media ID in db is invalid."))?; .next()
.ok_or_else(|| Error::bad_database("Media ID in db is invalid."))?;
let content_disposition = if content_disposition_bytes.is_empty() { let content_disposition = if content_disposition_bytes.is_empty() {
None None
} else { } else {
Some( Some(
string_from_bytes(content_disposition_bytes) utils::string_from_bytes(content_disposition_bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Content Disposition in mediaid_file is invalid unicode."))?, Error::bad_database("Content Disposition in mediaid_file is invalid unicode.")
})?,
) )
}; };
Ok((content_disposition, content_type, key)) Ok((content_disposition, content_type, key))
} }
/// Gets all the media keys in our database (this includes all the metadata fn remove_url_preview(&self, url: &str) -> Result<()> {
/// associated with it such as width, height, content-type, etc) self.url_previews.remove(url.as_bytes())
fn get_all_media_keys(&self) -> Result<Vec<Vec<u8>>> {
let mut keys: Vec<Vec<u8>> = vec![];
for (key, _) in self.mediaid_file.iter() {
keys.push(key);
} }
Ok(keys) fn set_url_preview(
} &self,
url: &str,
fn remove_url_preview(&self, url: &str) -> Result<()> { self.url_previews.remove(url.as_bytes()) } data: &UrlPreviewData,
timestamp: std::time::Duration,
fn set_url_preview(&self, url: &str, data: &UrlPreviewData, timestamp: std::time::Duration) -> Result<()> { ) -> Result<()> {
let mut value = Vec::<u8>::new(); let mut value = Vec::<u8>::new();
value.extend_from_slice(&timestamp.as_secs().to_be_bytes()); value.extend_from_slice(&timestamp.as_secs().to_be_bytes());
value.push(0xFF); value.push(0xff);
value.extend_from_slice(data.title.as_ref().map(String::as_bytes).unwrap_or_default()); value.extend_from_slice(
value.push(0xFF); data.title
value.extend_from_slice(data.description.as_ref().map(String::as_bytes).unwrap_or_default()); .as_ref()
value.push(0xFF); .map(|t| t.as_bytes())
value.extend_from_slice(data.image.as_ref().map(String::as_bytes).unwrap_or_default()); .unwrap_or_default(),
value.push(0xFF); );
value.push(0xff);
value.extend_from_slice(
data.description
.as_ref()
.map(|d| d.as_bytes())
.unwrap_or_default(),
);
value.push(0xff);
value.extend_from_slice(
data.image
.as_ref()
.map(|i| i.as_bytes())
.unwrap_or_default(),
);
value.push(0xff);
value.extend_from_slice(&data.image_size.unwrap_or(0).to_be_bytes()); value.extend_from_slice(&data.image_size.unwrap_or(0).to_be_bytes());
value.push(0xFF); value.push(0xff);
value.extend_from_slice(&data.image_width.unwrap_or(0).to_be_bytes()); value.extend_from_slice(&data.image_width.unwrap_or(0).to_be_bytes());
value.push(0xFF); value.push(0xff);
value.extend_from_slice(&data.image_height.unwrap_or(0).to_be_bytes()); value.extend_from_slice(&data.image_height.unwrap_or(0).to_be_bytes());
self.url_previews.insert(url.as_bytes(), &value) self.url_previews.insert(url.as_bytes(), &value)
@@ -157,36 +130,54 @@ impl service::media::Data for KeyValueDatabase {
fn get_url_preview(&self, url: &str) -> Option<UrlPreviewData> { fn get_url_preview(&self, url: &str) -> Option<UrlPreviewData> {
let values = self.url_previews.get(url.as_bytes()).ok()??; let values = self.url_previews.get(url.as_bytes()).ok()??;
let mut values = values.split(|&b| b == 0xFF); let mut values = values.split(|&b| b == 0xff);
let _ts = values.next(); let _ts = match values
/* if we ever decide to use timestamp, this is here. .next()
match values.next().map(|b| u64::from_be_bytes(b.try_into().expect("valid BE array"))) { .map(|b| u64::from_be_bytes(b.try_into().expect("valid BE array")))
Some(0) => None, {
x => x,
};*/
let title = match values.next().and_then(|b| String::from_utf8(b.to_vec()).ok()) {
Some(s) if s.is_empty() => None,
x => x,
};
let description = match values.next().and_then(|b| String::from_utf8(b.to_vec()).ok()) {
Some(s) if s.is_empty() => None,
x => x,
};
let image = match values.next().and_then(|b| String::from_utf8(b.to_vec()).ok()) {
Some(s) if s.is_empty() => None,
x => x,
};
let image_size = match values.next().map(|b| usize::from_be_bytes(b.try_into().unwrap_or_default())) {
Some(0) => None, Some(0) => None,
x => x, x => x,
}; };
let image_width = match values.next().map(|b| u32::from_be_bytes(b.try_into().unwrap_or_default())) { let title = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
{
Some(s) if s.is_empty() => None,
x => x,
};
let description = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
{
Some(s) if s.is_empty() => None,
x => x,
};
let image = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
{
Some(s) if s.is_empty() => None,
x => x,
};
let image_size = match values
.next()
.map(|b| usize::from_be_bytes(b.try_into().expect("valid BE array")))
{
Some(0) => None, Some(0) => None,
x => x, x => x,
}; };
let image_height = match values.next().map(|b| u32::from_be_bytes(b.try_into().unwrap_or_default())) { let image_width = match values
.next()
.map(|b| u32::from_be_bytes(b.try_into().expect("valid BE array")))
{
Some(0) => None,
x => x,
};
let image_height = match values
.next()
.map(|b| u32::from_be_bytes(b.try_into().expect("valid BE array")))
{
Some(0) => None, Some(0) => None,
x => x, x => x,
}; };
+31 -15
View File
@@ -10,50 +10,66 @@ impl service::pusher::Data for KeyValueDatabase {
match &pusher { match &pusher {
set_pusher::v3::PusherAction::Post(data) => { set_pusher::v3::PusherAction::Post(data) => {
let mut key = sender.as_bytes().to_vec(); let mut key = sender.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(data.pusher.ids.pushkey.as_bytes()); key.extend_from_slice(data.pusher.ids.pushkey.as_bytes());
self.senderkey_pusher self.senderkey_pusher.insert(
.insert(&key, &serde_json::to_vec(&pusher).expect("Pusher is valid JSON value"))?; &key,
&serde_json::to_vec(&pusher).expect("Pusher is valid JSON value"),
)?;
Ok(()) Ok(())
}, }
set_pusher::v3::PusherAction::Delete(ids) => { set_pusher::v3::PusherAction::Delete(ids) => {
let mut key = sender.as_bytes().to_vec(); let mut key = sender.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(ids.pushkey.as_bytes()); key.extend_from_slice(ids.pushkey.as_bytes());
self.senderkey_pusher.remove(&key).map(|_| ()).map_err(Into::into) self.senderkey_pusher
}, .remove(&key)
.map(|_| ())
.map_err(Into::into)
}
} }
} }
fn get_pusher(&self, sender: &UserId, pushkey: &str) -> Result<Option<Pusher>> { fn get_pusher(&self, sender: &UserId, pushkey: &str) -> Result<Option<Pusher>> {
let mut senderkey = sender.as_bytes().to_vec(); let mut senderkey = sender.as_bytes().to_vec();
senderkey.push(0xFF); senderkey.push(0xff);
senderkey.extend_from_slice(pushkey.as_bytes()); senderkey.extend_from_slice(pushkey.as_bytes());
self.senderkey_pusher self.senderkey_pusher
.get(&senderkey)? .get(&senderkey)?
.map(|push| serde_json::from_slice(&push).map_err(|_| Error::bad_database("Invalid Pusher in db."))) .map(|push| {
serde_json::from_slice(&push)
.map_err(|_| Error::bad_database("Invalid Pusher in db."))
})
.transpose() .transpose()
} }
fn get_pushers(&self, sender: &UserId) -> Result<Vec<Pusher>> { fn get_pushers(&self, sender: &UserId) -> Result<Vec<Pusher>> {
let mut prefix = sender.as_bytes().to_vec(); let mut prefix = sender.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
self.senderkey_pusher self.senderkey_pusher
.scan_prefix(prefix) .scan_prefix(prefix)
.map(|(_, push)| serde_json::from_slice(&push).map_err(|_| Error::bad_database("Invalid Pusher in db."))) .map(|(_, push)| {
serde_json::from_slice(&push)
.map_err(|_| Error::bad_database("Invalid Pusher in db."))
})
.collect() .collect()
} }
fn get_pushkeys<'a>(&'a self, sender: &UserId) -> Box<dyn Iterator<Item = Result<String>> + 'a> { fn get_pushkeys<'a>(
&'a self,
sender: &UserId,
) -> Box<dyn Iterator<Item = Result<String>> + 'a> {
let mut prefix = sender.as_bytes().to_vec(); let mut prefix = sender.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
Box::new(self.senderkey_pusher.scan_prefix(prefix).map(|(k, _)| { Box::new(self.senderkey_pusher.scan_prefix(prefix).map(|(k, _)| {
let mut parts = k.splitn(2, |&b| b == 0xFF); let mut parts = k.splitn(2, |&b| b == 0xff);
let _senderkey = parts.next(); let _senderkey = parts.next();
let push_key = parts.next().ok_or_else(|| Error::bad_database("Invalid senderkey_pusher in db"))?; let push_key = parts
.next()
.ok_or_else(|| Error::bad_database("Invalid senderkey_pusher in db"))?;
let push_key_string = utils::string_from_bytes(push_key) let push_key_string = utils::string_from_bytes(push_key)
.map_err(|_| Error::bad_database("Invalid pusher bytes in senderkey_pusher"))?; .map_err(|_| Error::bad_database("Invalid pusher bytes in senderkey_pusher"))?;
+30 -16
View File
@@ -4,9 +4,10 @@ use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}
impl service::rooms::alias::Data for KeyValueDatabase { impl service::rooms::alias::Data for KeyValueDatabase {
fn set_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> Result<()> { fn set_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> Result<()> {
self.alias_roomid.insert(alias.alias().as_bytes(), room_id.as_bytes())?; self.alias_roomid
.insert(alias.alias().as_bytes(), room_id.as_bytes())?;
let mut aliasid = room_id.as_bytes().to_vec(); let mut aliasid = room_id.as_bytes().to_vec();
aliasid.push(0xFF); aliasid.push(0xff);
aliasid.extend_from_slice(&services().globals.next_count()?.to_be_bytes()); aliasid.extend_from_slice(&services().globals.next_count()?.to_be_bytes());
self.aliasid_alias.insert(&aliasid, alias.as_bytes())?; self.aliasid_alias.insert(&aliasid, alias.as_bytes())?;
Ok(()) Ok(())
@@ -14,15 +15,18 @@ impl service::rooms::alias::Data for KeyValueDatabase {
fn remove_alias(&self, alias: &RoomAliasId) -> Result<()> { fn remove_alias(&self, alias: &RoomAliasId) -> Result<()> {
if let Some(room_id) = self.alias_roomid.get(alias.alias().as_bytes())? { if let Some(room_id) = self.alias_roomid.get(alias.alias().as_bytes())? {
let mut prefix = room_id; let mut prefix = room_id.to_vec();
prefix.push(0xFF); prefix.push(0xff);
for (key, _) in self.aliasid_alias.scan_prefix(prefix) { for (key, _) in self.aliasid_alias.scan_prefix(prefix) {
self.aliasid_alias.remove(&key)?; self.aliasid_alias.remove(&key)?;
} }
self.alias_roomid.remove(alias.alias().as_bytes())?; self.alias_roomid.remove(alias.alias().as_bytes())?;
} else { } else {
return Err(Error::BadRequest(ErrorKind::NotFound, "Alias does not exist.")); return Err(Error::BadRequest(
ErrorKind::NotFound,
"Alias does not exist.",
));
} }
Ok(()) Ok(())
} }
@@ -31,20 +35,20 @@ impl service::rooms::alias::Data for KeyValueDatabase {
self.alias_roomid self.alias_roomid
.get(alias.alias().as_bytes())? .get(alias.alias().as_bytes())?
.map(|bytes| { .map(|bytes| {
RoomId::parse( RoomId::parse(utils::string_from_bytes(&bytes).map_err(|_| {
utils::string_from_bytes(&bytes) Error::bad_database("Room ID in alias_roomid is invalid unicode.")
.map_err(|_| Error::bad_database("Room ID in alias_roomid is invalid unicode."))?, })?)
)
.map_err(|_| Error::bad_database("Room ID in alias_roomid is invalid.")) .map_err(|_| Error::bad_database("Room ID in alias_roomid is invalid."))
}) })
.transpose() .transpose()
} }
fn local_aliases_for_room<'a>( fn local_aliases_for_room<'a>(
&'a self, room_id: &RoomId, &'a self,
room_id: &RoomId,
) -> Box<dyn Iterator<Item = Result<OwnedRoomAliasId>> + 'a> { ) -> Box<dyn Iterator<Item = Result<OwnedRoomAliasId>> + 'a> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
Box::new(self.aliasid_alias.scan_prefix(prefix).map(|(_, bytes)| { Box::new(self.aliasid_alias.scan_prefix(prefix).map(|(_, bytes)| {
utils::string_from_bytes(&bytes) utils::string_from_bytes(&bytes)
@@ -54,17 +58,27 @@ impl service::rooms::alias::Data for KeyValueDatabase {
})) }))
} }
fn all_local_aliases<'a>(&'a self) -> Box<dyn Iterator<Item = Result<(OwnedRoomId, String)>> + 'a> { fn all_local_aliases<'a>(
Box::new(self.alias_roomid.iter().map(|(room_alias_bytes, room_id_bytes)| { &'a self,
) -> Box<dyn Iterator<Item = Result<(OwnedRoomId, String)>> + 'a> {
Box::new(
self.alias_roomid
.iter()
.map(|(room_alias_bytes, room_id_bytes)| {
let room_alias_localpart = utils::string_from_bytes(&room_alias_bytes) let room_alias_localpart = utils::string_from_bytes(&room_alias_bytes)
.map_err(|_| Error::bad_database("Invalid alias bytes in aliasid_alias."))?; .map_err(|_| {
Error::bad_database("Invalid alias bytes in aliasid_alias.")
})?;
let room_id = utils::string_from_bytes(&room_id_bytes) let room_id = utils::string_from_bytes(&room_id_bytes)
.map_err(|_| Error::bad_database("Invalid room_id bytes in aliasid_alias."))? .map_err(|_| {
Error::bad_database("Invalid room_id bytes in aliasid_alias.")
})?
.try_into() .try_into()
.map_err(|_| Error::bad_database("Invalid room_id in aliasid_alias."))?; .map_err(|_| Error::bad_database("Invalid room_id in aliasid_alias."))?;
Ok((room_id, room_alias_localpart)) Ok((room_id, room_alias_localpart))
})) }),
)
} }
} }
+16 -4
View File
@@ -12,7 +12,10 @@ impl service::rooms::auth_chain::Data for KeyValueDatabase {
// We only save auth chains for single events in the db // We only save auth chains for single events in the db
if key.len() == 1 { if key.len() == 1 {
// Check DB cache // Check DB cache
let chain = self.shorteventid_authchain.get(&key[0].to_be_bytes())?.map(|chain| { let chain = self
.shorteventid_authchain
.get(&key[0].to_be_bytes())?
.map(|chain| {
chain chain
.chunks_exact(size_of::<u64>()) .chunks_exact(size_of::<u64>())
.map(|chunk| utils::u64_from_bytes(chunk).expect("byte length is correct")) .map(|chunk| utils::u64_from_bytes(chunk).expect("byte length is correct"))
@@ -23,7 +26,10 @@ impl service::rooms::auth_chain::Data for KeyValueDatabase {
let chain = Arc::new(chain); let chain = Arc::new(chain);
// Cache in RAM // Cache in RAM
self.auth_chain_cache.lock().unwrap().insert(vec![key[0]], Arc::clone(&chain)); self.auth_chain_cache
.lock()
.unwrap()
.insert(vec![key[0]], Arc::clone(&chain));
return Ok(Some(chain)); return Ok(Some(chain));
} }
@@ -37,12 +43,18 @@ impl service::rooms::auth_chain::Data for KeyValueDatabase {
if key.len() == 1 { if key.len() == 1 {
self.shorteventid_authchain.insert( self.shorteventid_authchain.insert(
&key[0].to_be_bytes(), &key[0].to_be_bytes(),
&auth_chain.iter().flat_map(|s| s.to_be_bytes().to_vec()).collect::<Vec<u8>>(), &auth_chain
.iter()
.flat_map(|s| s.to_be_bytes().to_vec())
.collect::<Vec<u8>>(),
)?; )?;
} }
// Cache in RAM // Cache in RAM
self.auth_chain_cache.lock().unwrap().insert(key, auth_chain); self.auth_chain_cache
.lock()
.unwrap()
.insert(key, auth_chain);
Ok(()) Ok(())
} }
+9 -4
View File
@@ -3,9 +3,13 @@ use ruma::{OwnedRoomId, RoomId};
use crate::{database::KeyValueDatabase, service, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, utils, Error, Result};
impl service::rooms::directory::Data for KeyValueDatabase { impl service::rooms::directory::Data for KeyValueDatabase {
fn set_public(&self, room_id: &RoomId) -> Result<()> { self.publicroomids.insert(room_id.as_bytes(), &[]) } fn set_public(&self, room_id: &RoomId) -> Result<()> {
self.publicroomids.insert(room_id.as_bytes(), &[])
}
fn set_not_public(&self, room_id: &RoomId) -> Result<()> { self.publicroomids.remove(room_id.as_bytes()) } fn set_not_public(&self, room_id: &RoomId) -> Result<()> {
self.publicroomids.remove(room_id.as_bytes())
}
fn is_public_room(&self, room_id: &RoomId) -> Result<bool> { fn is_public_room(&self, room_id: &RoomId) -> Result<bool> {
Ok(self.publicroomids.get(room_id.as_bytes())?.is_some()) Ok(self.publicroomids.get(room_id.as_bytes())?.is_some())
@@ -14,8 +18,9 @@ impl service::rooms::directory::Data for KeyValueDatabase {
fn public_rooms<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> { fn public_rooms<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> {
Box::new(self.publicroomids.iter().map(|(bytes, _)| { Box::new(self.publicroomids.iter().map(|(bytes, _)| {
RoomId::parse( RoomId::parse(
utils::string_from_bytes(&bytes) utils::string_from_bytes(&bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Room ID in publicroomids is invalid unicode."))?, Error::bad_database("Room ID in publicroomids is invalid unicode.")
})?,
) )
.map_err(|_| Error::bad_database("Room ID in publicroomids is invalid.")) .map_err(|_| Error::bad_database("Room ID in publicroomids is invalid."))
})) }))
+40 -17
View File
@@ -1,6 +1,8 @@
use std::time::Duration; use std::time::Duration;
use ruma::{events::presence::PresenceEvent, presence::PresenceState, OwnedUserId, RoomId, UInt, UserId}; use ruma::{
events::presence::PresenceEvent, presence::PresenceState, OwnedUserId, RoomId, UInt, UserId,
};
use tracing::error; use tracing::error;
use crate::{ use crate::{
@@ -61,11 +63,18 @@ impl service::rooms::edus::presence::Data for KeyValueDatabase {
presence.last_count = count; presence.last_count = count;
presence presence
}, }
None => Presence::new(new_state.clone(), new_state == PresenceState::Online, now, count, None), None => Presence::new(
new_state.clone(),
new_state == PresenceState::Online,
now,
count,
None,
),
}; };
self.roomuserid_presence.insert(&key, &new_presence.to_json_bytes()?)?; self.roomuserid_presence
.insert(&key, &new_presence.to_json_bytes()?)?;
} }
let timeout = match new_state { let timeout = match new_state {
@@ -73,15 +82,22 @@ impl service::rooms::edus::presence::Data for KeyValueDatabase {
_ => services().globals.config.presence_offline_timeout_s, _ => services().globals.config.presence_offline_timeout_s,
}; };
self.presence_timer_sender.send((user_id.to_owned(), Duration::from_secs(timeout))).map_err(|e| { self.presence_timer_sender
.send((user_id.to_owned(), Duration::from_secs(timeout)))
.map_err(|e| {
error!("Failed to add presence timer: {}", e); error!("Failed to add presence timer: {}", e);
Error::bad_database("Failed to add presence timer") Error::bad_database("Failed to add presence timer")
}) })
} }
fn set_presence( fn set_presence(
&self, room_id: &RoomId, user_id: &UserId, presence_state: PresenceState, currently_active: Option<bool>, &self,
last_active_ago: Option<UInt>, status_msg: Option<String>, room_id: &RoomId,
user_id: &UserId,
presence_state: PresenceState,
currently_active: Option<bool>,
last_active_ago: Option<UInt>,
status_msg: Option<String>,
) -> Result<()> { ) -> Result<()> {
let now = utils::millis_since_unix_epoch(); let now = utils::millis_since_unix_epoch();
let last_active_ts = match last_active_ago { let last_active_ts = match last_active_ago {
@@ -104,12 +120,15 @@ impl service::rooms::edus::presence::Data for KeyValueDatabase {
_ => services().globals.config.presence_offline_timeout_s, _ => services().globals.config.presence_offline_timeout_s,
}; };
self.presence_timer_sender.send((user_id.to_owned(), Duration::from_secs(timeout))).map_err(|e| { self.presence_timer_sender
.send((user_id.to_owned(), Duration::from_secs(timeout)))
.map_err(|e| {
error!("Failed to add presence timer: {}", e); error!("Failed to add presence timer: {}", e);
Error::bad_database("Failed to add presence timer") Error::bad_database("Failed to add presence timer")
})?; })?;
self.roomuserid_presence.insert(&key, &presence.to_json_bytes()?)?; self.roomuserid_presence
.insert(&key, &presence.to_json_bytes()?)?;
Ok(()) Ok(())
} }
@@ -125,25 +144,29 @@ impl service::rooms::edus::presence::Data for KeyValueDatabase {
} }
fn presence_since<'a>( fn presence_since<'a>(
&'a self, room_id: &RoomId, since: u64, &'a self,
room_id: &RoomId,
since: u64,
) -> Box<dyn Iterator<Item = (OwnedUserId, u64, PresenceEvent)> + 'a> { ) -> Box<dyn Iterator<Item = (OwnedUserId, u64, PresenceEvent)> + 'a> {
let prefix = [room_id.as_bytes(), &[0xFF]].concat(); let prefix = [room_id.as_bytes(), &[0xff]].concat();
Box::new( Box::new(
self.roomuserid_presence self.roomuserid_presence
.scan_prefix(prefix) .scan_prefix(prefix)
.flat_map(|(key, presence_bytes)| -> Result<(OwnedUserId, u64, PresenceEvent)> { .flat_map(
|(key, presence_bytes)| -> Result<(OwnedUserId, u64, PresenceEvent)> {
let user_id = user_id_from_bytes( let user_id = user_id_from_bytes(
key.rsplit(|byte| *byte == 0xFF) key.rsplit(|byte| *byte == 0xff).next().ok_or_else(|| {
.next() Error::bad_database("No UserID bytes in presence key")
.ok_or_else(|| Error::bad_database("No UserID bytes in presence key"))?, })?,
)?; )?;
let presence = Presence::from_json_bytes(&presence_bytes)?; let presence = Presence::from_json_bytes(&presence_bytes)?;
let presence_event = presence.to_presence_event(&user_id)?; let presence_event = presence.to_presence_event(&user_id)?;
Ok((user_id, presence.last_count, presence_event)) Ok((user_id, presence.last_count, presence_event))
}) },
)
.filter(move |(_, count, _)| *count > since), .filter(move |(_, count, _)| *count > since),
) )
} }
@@ -151,5 +174,5 @@ impl service::rooms::edus::presence::Data for KeyValueDatabase {
#[inline] #[inline]
fn presence_key(room_id: &RoomId, user_id: &UserId) -> Vec<u8> { fn presence_key(room_id: &RoomId, user_id: &UserId) -> Vec<u8> {
[room_id.as_bytes(), &[0xFF], user_id.as_bytes()].concat() [room_id.as_bytes(), &[0xff], user_id.as_bytes()].concat()
} }
@@ -1,13 +1,21 @@
use std::mem; use std::mem;
use ruma::{events::receipt::ReceiptEvent, serde::Raw, CanonicalJsonObject, OwnedUserId, RoomId, UserId}; use ruma::{
events::receipt::ReceiptEvent, serde::Raw, CanonicalJsonObject, OwnedUserId, RoomId, UserId,
};
use tracing::debug;
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
impl service::rooms::edus::read_receipt::Data for KeyValueDatabase { impl service::rooms::edus::read_receipt::Data for KeyValueDatabase {
fn readreceipt_update(&self, user_id: &UserId, room_id: &RoomId, event: ReceiptEvent) -> Result<()> { fn readreceipt_update(
&self,
user_id: &UserId,
room_id: &RoomId,
event: ReceiptEvent,
) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
let mut last_possible_key = prefix.clone(); let mut last_possible_key = prefix.clone();
last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes()); last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes());
@@ -18,15 +26,19 @@ impl service::rooms::edus::read_receipt::Data for KeyValueDatabase {
.iter_from(&last_possible_key, true) .iter_from(&last_possible_key, true)
.take_while(|(key, _)| key.starts_with(&prefix)) .take_while(|(key, _)| key.starts_with(&prefix))
.find(|(key, _)| { .find(|(key, _)| {
key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element") == user_id.as_bytes() key.rsplit(|&b| b == 0xff)
}) { .next()
.expect("rsplit always returns an element")
== user_id.as_bytes()
})
{
// This is the old room_latest // This is the old room_latest
self.readreceiptid_readreceipt.remove(&old)?; self.readreceiptid_readreceipt.remove(&old)?;
} }
let mut room_latest_id = prefix; let mut room_latest_id = prefix;
room_latest_id.extend_from_slice(&services().globals.next_count()?.to_be_bytes()); room_latest_id.extend_from_slice(&services().globals.next_count()?.to_be_bytes());
room_latest_id.push(0xFF); room_latest_id.push(0xff);
room_latest_id.extend_from_slice(user_id.as_bytes()); room_latest_id.extend_from_slice(user_id.as_bytes());
self.readreceiptid_readreceipt.insert( self.readreceiptid_readreceipt.insert(
@@ -38,10 +50,20 @@ impl service::rooms::edus::read_receipt::Data for KeyValueDatabase {
} }
fn readreceipts_since<'a>( fn readreceipts_since<'a>(
&'a self, room_id: &RoomId, since: u64, &'a self,
) -> Box<dyn Iterator<Item = Result<(OwnedUserId, u64, Raw<ruma::events::AnySyncEphemeralRoomEvent>)>> + 'a> { room_id: &RoomId,
since: u64,
) -> Box<
dyn Iterator<
Item = Result<(
OwnedUserId,
u64,
Raw<ruma::events::AnySyncEphemeralRoomEvent>,
)>,
> + 'a,
> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
let prefix2 = prefix.clone(); let prefix2 = prefix.clone();
let mut first_possible_edu = prefix.clone(); let mut first_possible_edu = prefix.clone();
@@ -52,22 +74,33 @@ impl service::rooms::edus::read_receipt::Data for KeyValueDatabase {
.iter_from(&first_possible_edu, false) .iter_from(&first_possible_edu, false)
.take_while(move |(k, _)| k.starts_with(&prefix2)) .take_while(move |(k, _)| k.starts_with(&prefix2))
.map(move |(k, v)| { .map(move |(k, v)| {
let count = utils::u64_from_bytes(&k[prefix.len()..prefix.len() + mem::size_of::<u64>()]) let count = utils::u64_from_bytes(
&k[prefix.len()..prefix.len() + mem::size_of::<u64>()],
)
.map_err(|_| Error::bad_database("Invalid readreceiptid count in db."))?; .map_err(|_| Error::bad_database("Invalid readreceiptid count in db."))?;
let user_id = UserId::parse( let user_id = UserId::parse(
utils::string_from_bytes(&k[prefix.len() + mem::size_of::<u64>() + 1..]) utils::string_from_bytes(&k[prefix.len() + mem::size_of::<u64>() + 1..])
.map_err(|_| Error::bad_database("Invalid readreceiptid userid bytes in db."))?, .map_err(|_| {
Error::bad_database("Invalid readreceiptid userid bytes in db.")
})?,
) )
.map_err(|_| Error::bad_database("Invalid readreceiptid userid in db."))?; .map_err(|_| Error::bad_database("Invalid readreceiptid userid in db."))?;
let mut json = serde_json::from_slice::<CanonicalJsonObject>(&v) let mut json =
.map_err(|_| Error::bad_database("Read receipt in roomlatestid_roomlatest is invalid json."))?; serde_json::from_slice::<CanonicalJsonObject>(&v).map_err(|_| {
Error::bad_database(
"Read receipt in roomlatestid_roomlatest is invalid json.",
)
})?;
json.remove("room_id"); json.remove("room_id");
Ok(( Ok((
user_id, user_id,
count, count,
Raw::from_json(serde_json::value::to_raw_value(&json).expect("json is valid raw value")), Raw::from_json(
serde_json::value::to_raw_value(&json)
.expect("json is valid raw value"),
),
)) ))
}), }),
) )
@@ -75,37 +108,59 @@ impl service::rooms::edus::read_receipt::Data for KeyValueDatabase {
fn private_read_set(&self, room_id: &RoomId, user_id: &UserId, count: u64) -> Result<()> { fn private_read_set(&self, room_id: &RoomId, user_id: &UserId, count: u64) -> Result<()> {
let mut key = room_id.as_bytes().to_vec(); let mut key = room_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(user_id.as_bytes()); key.extend_from_slice(user_id.as_bytes());
self.roomuserid_privateread.insert(&key, &count.to_be_bytes())?; self.roomuserid_privateread
.insert(&key, &count.to_be_bytes())?;
self.roomuserid_lastprivatereadupdate.insert(&key, &services().globals.next_count()?.to_be_bytes()) self.roomuserid_lastprivatereadupdate
.insert(&key, &services().globals.next_count()?.to_be_bytes())
}
fn delete_all_private_read_receipts(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
for (key, _) in self.roomuserid_privateread.scan_prefix(prefix.clone()) {
debug!("Removing key {:?}", key);
self.roomuserid_privateread.remove(&key)?;
}
for (key, _) in self.roomuserid_lastprivatereadupdate.scan_prefix(prefix) {
debug!("Removing key {:?}", key);
self.roomuserid_lastprivatereadupdate.remove(&key)?;
}
Ok(())
} }
fn private_read_get(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> { fn private_read_get(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
let mut key = room_id.as_bytes().to_vec(); let mut key = room_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(user_id.as_bytes()); key.extend_from_slice(user_id.as_bytes());
self.roomuserid_privateread.get(&key)?.map_or(Ok(None), |v| { self.roomuserid_privateread
Ok(Some( .get(&key)?
utils::u64_from_bytes(&v).map_err(|_| Error::bad_database("Invalid private read marker bytes"))?, .map_or(Ok(None), |v| {
)) Ok(Some(utils::u64_from_bytes(&v).map_err(|_| {
Error::bad_database("Invalid private read marker bytes")
})?))
}) })
} }
fn last_privateread_update(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> { fn last_privateread_update(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
let mut key = room_id.as_bytes().to_vec(); let mut key = room_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(user_id.as_bytes()); key.extend_from_slice(user_id.as_bytes());
Ok(self Ok(self
.roomuserid_lastprivatereadupdate .roomuserid_lastprivatereadupdate
.get(&key)? .get(&key)?
.map(|bytes| { .map(|bytes| {
utils::u64_from_bytes(&bytes) utils::u64_from_bytes(&bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Count in roomuserid_lastprivatereadupdate is invalid.")) Error::bad_database("Count in roomuserid_lastprivatereadupdate is invalid.")
})
}) })
.transpose()? .transpose()?
.unwrap_or(0)) .unwrap_or(0))
+45 -20
View File
@@ -1,44 +1,54 @@
use std::{collections::HashSet, mem}; use std::{collections::HashSet, mem};
use ruma::{OwnedUserId, RoomId, UserId}; use ruma::{OwnedUserId, RoomId, UserId};
use tracing::debug;
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
impl service::rooms::edus::typing::Data for KeyValueDatabase { impl service::rooms::edus::typing::Data for KeyValueDatabase {
fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result<()> { fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
let count = services().globals.next_count()?.to_be_bytes(); let count = services().globals.next_count()?.to_be_bytes();
let mut room_typing_id = prefix; let mut room_typing_id = prefix;
room_typing_id.extend_from_slice(&timeout.to_be_bytes()); room_typing_id.extend_from_slice(&timeout.to_be_bytes());
room_typing_id.push(0xFF); room_typing_id.push(0xff);
room_typing_id.extend_from_slice(&count); room_typing_id.extend_from_slice(&count);
self.typingid_userid.insert(&room_typing_id, user_id.as_bytes())?; self.typingid_userid
.insert(&room_typing_id, user_id.as_bytes())?;
self.roomid_lasttypingupdate.insert(room_id.as_bytes(), &count)?; self.roomid_lasttypingupdate
.insert(room_id.as_bytes(), &count)?;
Ok(()) Ok(())
} }
fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> { fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
let user_id = user_id.to_string(); let user_id = user_id.to_string();
let mut found_outdated = false; let mut found_outdated = false;
// Maybe there are multiple ones from calling roomtyping_add multiple times // Maybe there are multiple ones from calling roomtyping_add multiple times
for outdated_edu in self.typingid_userid.scan_prefix(prefix).filter(|(_, v)| &**v == user_id.as_bytes()) { for outdated_edu in self
.typingid_userid
.scan_prefix(prefix)
.filter(|(_, v)| &**v == user_id.as_bytes())
{
self.typingid_userid.remove(&outdated_edu.0)?; self.typingid_userid.remove(&outdated_edu.0)?;
found_outdated = true; found_outdated = true;
} }
if found_outdated { if found_outdated {
self.roomid_lasttypingupdate.insert(room_id.as_bytes(), &services().globals.next_count()?.to_be_bytes())?; self.roomid_lasttypingupdate.insert(
room_id.as_bytes(),
&services().globals.next_count()?.to_be_bytes(),
)?;
} }
Ok(()) Ok(())
@@ -46,7 +56,7 @@ impl service::rooms::edus::typing::Data for KeyValueDatabase {
fn typings_maintain(&self, room_id: &RoomId) -> Result<()> { fn typings_maintain(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
let current_timestamp = utils::millis_since_unix_epoch(); let current_timestamp = utils::millis_since_unix_epoch();
@@ -60,14 +70,14 @@ impl service::rooms::edus::typing::Data for KeyValueDatabase {
Ok::<_, Error>(( Ok::<_, Error>((
key.clone(), key.clone(),
utils::u64_from_bytes( utils::u64_from_bytes(
&key.splitn(2, |&b| b == 0xFF) &key.splitn(2, |&b| b == 0xff).nth(1).ok_or_else(|| {
.nth(1) Error::bad_database("RoomTyping has invalid timestamp or delimiters.")
.ok_or_else(|| Error::bad_database("RoomTyping has invalid timestamp or delimiters."))?[0..mem::size_of::<u64>()], })?[0..mem::size_of::<u64>()],
) )
.map_err(|_| Error::bad_database("RoomTyping has invalid timestamp bytes."))?, .map_err(|_| Error::bad_database("RoomTyping has invalid timestamp bytes."))?,
)) ))
}) })
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.take_while(|&(_, timestamp)| timestamp < current_timestamp) .take_while(|&(_, timestamp)| timestamp < current_timestamp)
{ {
// This is an outdated edu (time > timestamp) // This is an outdated edu (time > timestamp)
@@ -76,7 +86,10 @@ impl service::rooms::edus::typing::Data for KeyValueDatabase {
} }
if found_outdated { if found_outdated {
self.roomid_lasttypingupdate.insert(room_id.as_bytes(), &services().globals.next_count()?.to_be_bytes())?; self.roomid_lasttypingupdate.insert(
room_id.as_bytes(),
&services().globals.next_count()?.to_be_bytes(),
)?;
} }
Ok(()) Ok(())
@@ -87,24 +100,36 @@ impl service::rooms::edus::typing::Data for KeyValueDatabase {
.roomid_lasttypingupdate .roomid_lasttypingupdate
.get(room_id.as_bytes())? .get(room_id.as_bytes())?
.map(|bytes| { .map(|bytes| {
utils::u64_from_bytes(&bytes) utils::u64_from_bytes(&bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Count in roomid_lastroomactiveupdate is invalid.")) Error::bad_database("Count in roomid_lastroomactiveupdate is invalid.")
})
}) })
.transpose()? .transpose()?
.unwrap_or(0)) .unwrap_or(0))
} }
fn delete_all_typing_updates(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
for (key, _) in self.roomid_lasttypingupdate.scan_prefix(prefix) {
debug!("Removing key {:?}", key);
self.roomid_lasttypingupdate.remove(&key)?;
}
Ok(())
}
fn typings_all(&self, room_id: &RoomId) -> Result<HashSet<OwnedUserId>> { fn typings_all(&self, room_id: &RoomId) -> Result<HashSet<OwnedUserId>> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
let mut user_ids = HashSet::new(); let mut user_ids = HashSet::new();
for (_, user_id) in self.typingid_userid.scan_prefix(prefix) { for (_, user_id) in self.typingid_userid.scan_prefix(prefix) {
let user_id = UserId::parse( let user_id = UserId::parse(utils::string_from_bytes(&user_id).map_err(|_| {
utils::string_from_bytes(&user_id) Error::bad_database("User ID in typingid_userid is invalid unicode.")
.map_err(|_| Error::bad_database("User ID in typingid_userid is invalid unicode."))?, })?)
)
.map_err(|_| Error::bad_database("User ID in typingid_userid is invalid."))?; .map_err(|_| Error::bad_database("User ID in typingid_userid is invalid."))?;
user_ids.insert(user_id); user_ids.insert(user_id);
+24 -12
View File
@@ -4,28 +4,35 @@ use crate::{database::KeyValueDatabase, service, Result};
impl service::rooms::lazy_loading::Data for KeyValueDatabase { impl service::rooms::lazy_loading::Data for KeyValueDatabase {
fn lazy_load_was_sent_before( fn lazy_load_was_sent_before(
&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId, ll_user: &UserId, &self,
user_id: &UserId,
device_id: &DeviceId,
room_id: &RoomId,
ll_user: &UserId,
) -> Result<bool> { ) -> Result<bool> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(device_id.as_bytes()); key.extend_from_slice(device_id.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(ll_user.as_bytes()); key.extend_from_slice(ll_user.as_bytes());
Ok(self.lazyloadedids.get(&key)?.is_some()) Ok(self.lazyloadedids.get(&key)?.is_some())
} }
fn lazy_load_confirm_delivery( fn lazy_load_confirm_delivery(
&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId, &self,
user_id: &UserId,
device_id: &DeviceId,
room_id: &RoomId,
confirmed_user_ids: &mut dyn Iterator<Item = &UserId>, confirmed_user_ids: &mut dyn Iterator<Item = &UserId>,
) -> Result<()> { ) -> Result<()> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(device_id.as_bytes()); prefix.extend_from_slice(device_id.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(room_id.as_bytes()); prefix.extend_from_slice(room_id.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
for ll_id in confirmed_user_ids { for ll_id in confirmed_user_ids {
let mut key = prefix.clone(); let mut key = prefix.clone();
@@ -36,13 +43,18 @@ impl service::rooms::lazy_loading::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
fn lazy_load_reset(&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId) -> Result<()> { fn lazy_load_reset(
&self,
user_id: &UserId,
device_id: &DeviceId,
room_id: &RoomId,
) -> Result<()> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(device_id.as_bytes()); prefix.extend_from_slice(device_id.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
prefix.extend_from_slice(room_id.as_bytes()); prefix.extend_from_slice(room_id.as_bytes());
prefix.push(0xFF); prefix.push(0xff);
for (key, _) in self.lazyloadedids.scan_prefix(prefix) { for (key, _) in self.lazyloadedids.scan_prefix(prefix) {
self.lazyloadedids.remove(&key)?; self.lazyloadedids.remove(&key)?;
+12 -4
View File
@@ -11,14 +11,20 @@ impl service::rooms::metadata::Data for KeyValueDatabase {
}; };
// Look for PDUs in that room. // Look for PDUs in that room.
Ok(self.pduid_pdu.iter_from(&prefix, false).next().filter(|(k, _)| k.starts_with(&prefix)).is_some()) Ok(self
.pduid_pdu
.iter_from(&prefix, false)
.next()
.filter(|(k, _)| k.starts_with(&prefix))
.is_some())
} }
fn iter_ids<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> { fn iter_ids<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> {
Box::new(self.roomid_shortroomid.iter().map(|(bytes, _)| { Box::new(self.roomid_shortroomid.iter().map(|(bytes, _)| {
RoomId::parse( RoomId::parse(
utils::string_from_bytes(&bytes) utils::string_from_bytes(&bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Room ID in publicroomids is invalid unicode."))?, Error::bad_database("Room ID in publicroomids is invalid unicode.")
})?,
) )
.map_err(|_| Error::bad_database("Room ID in roomid_shortroomid is invalid.")) .map_err(|_| Error::bad_database("Room ID in roomid_shortroomid is invalid."))
})) }))
@@ -38,7 +44,9 @@ impl service::rooms::metadata::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
fn is_banned(&self, room_id: &RoomId) -> Result<bool> { Ok(self.bannedroomids.get(room_id.as_bytes())?.is_some()) } fn is_banned(&self, room_id: &RoomId) -> Result<bool> {
Ok(self.bannedroomids.get(room_id.as_bytes())?.is_some())
}
fn ban_room(&self, room_id: &RoomId, banned: bool) -> Result<()> { fn ban_room(&self, room_id: &RoomId, banned: bool) -> Result<()> {
if banned { if banned {
+6 -2
View File
@@ -4,13 +4,17 @@ use crate::{database::KeyValueDatabase, service, Error, PduEvent, Result};
impl service::rooms::outlier::Data for KeyValueDatabase { impl service::rooms::outlier::Data for KeyValueDatabase {
fn get_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> { fn get_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
self.eventid_outlierpdu.get(event_id.as_bytes())?.map_or(Ok(None), |pdu| { self.eventid_outlierpdu
.get(event_id.as_bytes())?
.map_or(Ok(None), |pdu| {
serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db.")) serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))
}) })
} }
fn get_outlier_pdu(&self, event_id: &EventId) -> Result<Option<PduEvent>> { fn get_outlier_pdu(&self, event_id: &EventId) -> Result<Option<PduEvent>> {
self.eventid_outlierpdu.get(event_id.as_bytes())?.map_or(Ok(None), |pdu| { self.eventid_outlierpdu
.get(event_id.as_bytes())?
.map_or(Ok(None), |pdu| {
serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db.")) serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))
}) })
} }
+33 -10
View File
@@ -1,11 +1,15 @@
use std::{mem, sync::Arc}; use std::{mem, sync::Arc};
use ruma::{EventId, RoomId, UserId}; use ruma::{EventId, RoomId, UserId};
use tracing::debug;
use crate::{ use crate::{
database::KeyValueDatabase, database::KeyValueDatabase,
service::{self, rooms::timeline::PduCount}, service::{
services, utils, Error, PduEvent, Result, self,
rooms::timeline::{data::PduData, PduCount},
},
services, utils, Error, Result,
}; };
impl service::rooms::pdu_metadata::Data for KeyValueDatabase { impl service::rooms::pdu_metadata::Data for KeyValueDatabase {
@@ -17,8 +21,12 @@ impl service::rooms::pdu_metadata::Data for KeyValueDatabase {
} }
fn relations_until<'a>( fn relations_until<'a>(
&'a self, user_id: &'a UserId, shortroomid: u64, target: u64, until: PduCount, &'a self,
) -> Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>> { user_id: &'a UserId,
shortroomid: u64,
target: u64,
until: PduCount,
) -> PduData<'a> {
let prefix = target.to_be_bytes().to_vec(); let prefix = target.to_be_bytes().to_vec();
let mut current = prefix.clone(); let mut current = prefix.clone();
@@ -27,13 +35,15 @@ impl service::rooms::pdu_metadata::Data for KeyValueDatabase {
PduCount::Backfilled(x) => { PduCount::Backfilled(x) => {
current.extend_from_slice(&0_u64.to_be_bytes()); current.extend_from_slice(&0_u64.to_be_bytes());
u64::MAX - x - 1 u64::MAX - x - 1
}, }
}; };
current.extend_from_slice(&count_raw.to_be_bytes()); current.extend_from_slice(&count_raw.to_be_bytes());
Ok(Box::new( Ok(Box::new(
self.tofrom_relation.iter_from(&current, true).take_while(move |(k, _)| k.starts_with(&prefix)).map( self.tofrom_relation
move |(tofrom, _data)| { .iter_from(&current, true)
.take_while(move |(k, _)| k.starts_with(&prefix))
.map(move |(tofrom, _data)| {
let from = utils::u64_from_bytes(&tofrom[(mem::size_of::<u64>())..]) let from = utils::u64_from_bytes(&tofrom[(mem::size_of::<u64>())..])
.map_err(|_| Error::bad_database("Invalid count in tofrom_relation."))?; .map_err(|_| Error::bad_database("Invalid count in tofrom_relation."))?;
@@ -49,8 +59,7 @@ impl service::rooms::pdu_metadata::Data for KeyValueDatabase {
pdu.remove_transaction_id()?; pdu.remove_transaction_id()?;
} }
Ok((PduCount::Normal(from), pdu)) Ok((PduCount::Normal(from), pdu))
}, }),
),
)) ))
} }
@@ -64,6 +73,18 @@ impl service::rooms::pdu_metadata::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
fn delete_all_referenced_for_room(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
for (key, _) in self.referencedevents.scan_prefix(prefix) {
debug!("Removing key: {:?}", key);
self.referencedevents.remove(&key)?;
}
Ok(())
}
fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> Result<bool> { fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> Result<bool> {
let mut key = room_id.as_bytes().to_vec(); let mut key = room_id.as_bytes().to_vec();
key.extend_from_slice(event_id.as_bytes()); key.extend_from_slice(event_id.as_bytes());
@@ -75,6 +96,8 @@ impl service::rooms::pdu_metadata::Data for KeyValueDatabase {
} }
fn is_event_soft_failed(&self, event_id: &EventId) -> Result<bool> { fn is_event_soft_failed(&self, event_id: &EventId) -> Result<bool> {
self.softfailedeventids.get(event_id.as_bytes()).map(|o| o.is_some()) self.softfailedeventids
.get(event_id.as_bytes())
.map(|o| o.is_some())
} }
} }
+23 -4
View File
@@ -1,11 +1,12 @@
use ruma::RoomId; use ruma::RoomId;
use tracing::debug;
use crate::{database::KeyValueDatabase, service, services, utils, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Result};
type SearchPdusResult<'a> = Result<Option<(Box<dyn Iterator<Item = Vec<u8>> + 'a>, Vec<String>)>>; type SearchPdusResult<'a> = Result<Option<(Box<dyn Iterator<Item = Vec<u8>> + 'a>, Vec<String>)>>;
impl service::rooms::search::Data for KeyValueDatabase { impl service::rooms::search::Data for KeyValueDatabase {
fn index_pdu(&self, shortroomid: u64, pdu_id: &[u8], message_body: &str) -> Result<()> { fn index_pdu<'a>(&self, shortroomid: u64, pdu_id: &[u8], message_body: &str) -> Result<()> {
let mut batch = message_body let mut batch = message_body
.split_terminator(|c: char| !c.is_alphanumeric()) .split_terminator(|c: char| !c.is_alphanumeric())
.filter(|s| !s.is_empty()) .filter(|s| !s.is_empty())
@@ -14,7 +15,7 @@ impl service::rooms::search::Data for KeyValueDatabase {
.map(|word| { .map(|word| {
let mut key = shortroomid.to_be_bytes().to_vec(); let mut key = shortroomid.to_be_bytes().to_vec();
key.extend_from_slice(word.as_bytes()); key.extend_from_slice(word.as_bytes());
key.push(0xFF); key.push(0xff);
key.extend_from_slice(pdu_id); // TODO: currently we save the room id a second time here key.extend_from_slice(pdu_id); // TODO: currently we save the room id a second time here
(key, Vec::new()) (key, Vec::new())
}); });
@@ -22,8 +23,26 @@ impl service::rooms::search::Data for KeyValueDatabase {
self.tokenids.insert_batch(&mut batch) self.tokenids.insert_batch(&mut batch)
} }
fn delete_all_search_tokenids_for_room(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
for (key, _) in self.tokenids.scan_prefix(prefix) {
debug!("Removing key: {:?}", key);
self.tokenids.remove(&key)?;
}
Ok(())
}
fn search_pdus<'a>(&'a self, room_id: &RoomId, search_string: &str) -> SearchPdusResult<'a> { fn search_pdus<'a>(&'a self, room_id: &RoomId, search_string: &str) -> SearchPdusResult<'a> {
let prefix = services().rooms.short.get_shortroomid(room_id)?.expect("room exists").to_be_bytes().to_vec(); let prefix = services()
.rooms
.short
.get_shortroomid(room_id)?
.expect("room exists")
.to_be_bytes()
.to_vec();
let words: Vec<_> = search_string let words: Vec<_> = search_string
.split_terminator(|c: char| !c.is_alphanumeric()) .split_terminator(|c: char| !c.is_alphanumeric())
@@ -34,7 +53,7 @@ impl service::rooms::search::Data for KeyValueDatabase {
let iterators = words.clone().into_iter().map(move |word| { let iterators = words.clone().into_iter().map(move |word| {
let mut prefix2 = prefix.clone(); let mut prefix2 = prefix.clone();
prefix2.extend_from_slice(word.as_bytes()); prefix2.extend_from_slice(word.as_bytes());
prefix2.push(0xFF); prefix2.push(0xff);
let prefix3 = prefix2.clone(); let prefix3 = prefix2.clone();
let mut last_possible_id = prefix2.clone(); let mut last_possible_id = prefix2.clone();
+118 -50
View File
@@ -1,7 +1,7 @@
use std::sync::Arc; use std::sync::Arc;
use ruma::{events::StateEventType, EventId, RoomId}; use ruma::{events::StateEventType, EventId, RoomId};
use tracing::warn; use tracing::{error, warn};
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
@@ -12,77 +12,109 @@ impl service::rooms::short::Data for KeyValueDatabase {
} }
let short = match self.eventid_shorteventid.get(event_id.as_bytes())? { let short = match self.eventid_shorteventid.get(event_id.as_bytes())? {
Some(shorteventid) => { Some(shorteventid) => utils::u64_from_bytes(&shorteventid)
utils::u64_from_bytes(&shorteventid).map_err(|_| Error::bad_database("Invalid shorteventid in db."))? .map_err(|_| Error::bad_database("Invalid shorteventid in db."))?,
},
None => { None => {
let shorteventid = services().globals.next_count()?; let shorteventid = services().globals.next_count()?;
self.eventid_shorteventid.insert(event_id.as_bytes(), &shorteventid.to_be_bytes())?; self.eventid_shorteventid
self.shorteventid_eventid.insert(&shorteventid.to_be_bytes(), event_id.as_bytes())?; .insert(event_id.as_bytes(), &shorteventid.to_be_bytes())?;
self.shorteventid_eventid
.insert(&shorteventid.to_be_bytes(), event_id.as_bytes())?;
shorteventid shorteventid
}, }
}; };
self.eventidshort_cache.lock().unwrap().insert(event_id.to_owned(), short); self.eventidshort_cache
.lock()
.unwrap()
.insert(event_id.to_owned(), short);
Ok(short) Ok(short)
} }
fn get_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result<Option<u64>> { fn get_shortstatekey(
if let Some(short) = &self,
self.statekeyshort_cache.lock().unwrap().get_mut(&(event_type.clone(), state_key.to_owned())) event_type: &StateEventType,
state_key: &str,
) -> Result<Option<u64>> {
if let Some(short) = self
.statekeyshort_cache
.lock()
.unwrap()
.get_mut(&(event_type.clone(), state_key.to_owned()))
{ {
return Ok(Some(*short)); return Ok(Some(*short));
} }
let mut statekey_vec = event_type.to_string().as_bytes().to_vec(); let mut statekey = event_type.to_string().as_bytes().to_vec();
statekey_vec.push(0xFF); statekey.push(0xff);
statekey_vec.extend_from_slice(state_key.as_bytes()); statekey.extend_from_slice(state_key.as_bytes());
let short = self let short = self
.statekey_shortstatekey .statekey_shortstatekey
.get(&statekey_vec)? .get(&statekey)?
.map(|shortstatekey| { .map(|shortstatekey| {
utils::u64_from_bytes(&shortstatekey).map_err(|_| Error::bad_database("Invalid shortstatekey in db.")) utils::u64_from_bytes(&shortstatekey)
.map_err(|_| Error::bad_database("Invalid shortstatekey in db."))
}) })
.transpose()?; .transpose()?;
if let Some(s) = short { if let Some(s) = short {
self.statekeyshort_cache.lock().unwrap().insert((event_type.clone(), state_key.to_owned()), s); self.statekeyshort_cache
.lock()
.unwrap()
.insert((event_type.clone(), state_key.to_owned()), s);
} }
Ok(short) Ok(short)
} }
fn get_or_create_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result<u64> { fn get_or_create_shortstatekey(
if let Some(short) = &self,
self.statekeyshort_cache.lock().unwrap().get_mut(&(event_type.clone(), state_key.to_owned())) event_type: &StateEventType,
state_key: &str,
) -> Result<u64> {
if let Some(short) = self
.statekeyshort_cache
.lock()
.unwrap()
.get_mut(&(event_type.clone(), state_key.to_owned()))
{ {
return Ok(*short); return Ok(*short);
} }
let mut statekey_vec = event_type.to_string().as_bytes().to_vec(); let mut statekey = event_type.to_string().as_bytes().to_vec();
statekey_vec.push(0xFF); statekey.push(0xff);
statekey_vec.extend_from_slice(state_key.as_bytes()); statekey.extend_from_slice(state_key.as_bytes());
let short = match self.statekey_shortstatekey.get(&statekey_vec)? { let short = match self.statekey_shortstatekey.get(&statekey)? {
Some(shortstatekey) => utils::u64_from_bytes(&shortstatekey) Some(shortstatekey) => utils::u64_from_bytes(&shortstatekey)
.map_err(|_| Error::bad_database("Invalid shortstatekey in db."))?, .map_err(|_| Error::bad_database("Invalid shortstatekey in db."))?,
None => { None => {
let shortstatekey = services().globals.next_count()?; let shortstatekey = services().globals.next_count()?;
self.statekey_shortstatekey.insert(&statekey_vec, &shortstatekey.to_be_bytes())?; self.statekey_shortstatekey
self.shortstatekey_statekey.insert(&shortstatekey.to_be_bytes(), &statekey_vec)?; .insert(&statekey, &shortstatekey.to_be_bytes())?;
self.shortstatekey_statekey
.insert(&shortstatekey.to_be_bytes(), &statekey)?;
shortstatekey shortstatekey
}, }
}; };
self.statekeyshort_cache.lock().unwrap().insert((event_type.clone(), state_key.to_owned()), short); self.statekeyshort_cache
.lock()
.unwrap()
.insert((event_type.clone(), state_key.to_owned()), short);
Ok(short) Ok(short)
} }
fn get_eventid_from_short(&self, shorteventid: u64) -> Result<Arc<EventId>> { fn get_eventid_from_short(&self, shorteventid: u64) -> Result<Arc<EventId>> {
if let Some(id) = self.shorteventid_cache.lock().unwrap().get_mut(&shorteventid) { if let Some(id) = self
.shorteventid_cache
.lock()
.unwrap()
.get_mut(&shorteventid)
{
return Ok(Arc::clone(id)); return Ok(Arc::clone(id));
} }
@@ -91,19 +123,26 @@ impl service::rooms::short::Data for KeyValueDatabase {
.get(&shorteventid.to_be_bytes())? .get(&shorteventid.to_be_bytes())?
.ok_or_else(|| Error::bad_database("Shorteventid does not exist"))?; .ok_or_else(|| Error::bad_database("Shorteventid does not exist"))?;
let event_id = EventId::parse_arc( let event_id = EventId::parse_arc(utils::string_from_bytes(&bytes).map_err(|_| {
utils::string_from_bytes(&bytes) Error::bad_database("EventID in shorteventid_eventid is invalid unicode.")
.map_err(|_| Error::bad_database("EventID in shorteventid_eventid is invalid unicode."))?, })?)
)
.map_err(|_| Error::bad_database("EventId in shorteventid_eventid is invalid."))?; .map_err(|_| Error::bad_database("EventId in shorteventid_eventid is invalid."))?;
self.shorteventid_cache.lock().unwrap().insert(shorteventid, Arc::clone(&event_id)); self.shorteventid_cache
.lock()
.unwrap()
.insert(shorteventid, Arc::clone(&event_id));
Ok(event_id) Ok(event_id)
} }
fn get_statekey_from_short(&self, shortstatekey: u64) -> Result<(StateEventType, String)> { fn get_statekey_from_short(&self, shortstatekey: u64) -> Result<(StateEventType, String)> {
if let Some(id) = self.shortstatekey_cache.lock().unwrap().get_mut(&shortstatekey) { if let Some(id) = self
.shortstatekey_cache
.lock()
.unwrap()
.get_mut(&shortstatekey)
{
return Ok(id.clone()); return Ok(id.clone());
} }
@@ -112,22 +151,28 @@ impl service::rooms::short::Data for KeyValueDatabase {
.get(&shortstatekey.to_be_bytes())? .get(&shortstatekey.to_be_bytes())?
.ok_or_else(|| Error::bad_database("Shortstatekey does not exist"))?; .ok_or_else(|| Error::bad_database("Shortstatekey does not exist"))?;
let mut parts = bytes.splitn(2, |&b| b == 0xFF); let mut parts = bytes.splitn(2, |&b| b == 0xff);
let eventtype_bytes = parts.next().expect("split always returns one entry"); let eventtype_bytes = parts.next().expect("split always returns one entry");
let statekey_bytes = let statekey_bytes = parts
parts.next().ok_or_else(|| Error::bad_database("Invalid statekey in shortstatekey_statekey."))?; .next()
.ok_or_else(|| Error::bad_database("Invalid statekey in shortstatekey_statekey."))?;
let event_type = StateEventType::from(utils::string_from_bytes(eventtype_bytes).map_err(|e| { let event_type =
StateEventType::from(utils::string_from_bytes(eventtype_bytes).map_err(|e| {
warn!("Event type in shortstatekey_statekey is invalid: {}", e); warn!("Event type in shortstatekey_statekey is invalid: {}", e);
Error::bad_database("Event type in shortstatekey_statekey is invalid.") Error::bad_database("Event type in shortstatekey_statekey is invalid.")
})?); })?);
let state_key = utils::string_from_bytes(statekey_bytes) let state_key = utils::string_from_bytes(statekey_bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Statekey in shortstatekey_statekey is invalid unicode."))?; Error::bad_database("Statekey in shortstatekey_statekey is invalid unicode.")
})?;
let result = (event_type, state_key); let result = (event_type, state_key);
self.shortstatekey_cache.lock().unwrap().insert(shortstatekey, result.clone()); self.shortstatekey_cache
.lock()
.unwrap()
.insert(shortstatekey, result.clone());
Ok(result) Ok(result)
} }
@@ -142,29 +187,52 @@ impl service::rooms::short::Data for KeyValueDatabase {
), ),
None => { None => {
let shortstatehash = services().globals.next_count()?; let shortstatehash = services().globals.next_count()?;
self.statehash_shortstatehash.insert(state_hash, &shortstatehash.to_be_bytes())?; self.statehash_shortstatehash
.insert(state_hash, &shortstatehash.to_be_bytes())?;
(shortstatehash, false) (shortstatehash, false)
}, }
}) })
} }
fn get_shortroomid(&self, room_id: &RoomId) -> Result<Option<u64>> { fn get_shortroomid(&self, room_id: &RoomId) -> Result<Option<u64>> {
self.roomid_shortroomid self.roomid_shortroomid
.get(room_id.as_bytes())? .get(room_id.as_bytes())?
.map(|bytes| utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid shortroomid in db."))) .map(|bytes| {
utils::u64_from_bytes(&bytes)
.map_err(|_| Error::bad_database("Invalid shortroomid in db."))
})
.transpose() .transpose()
} }
fn get_or_create_shortroomid(&self, room_id: &RoomId) -> Result<u64> { fn get_or_create_shortroomid(&self, room_id: &RoomId) -> Result<u64> {
Ok(match self.roomid_shortroomid.get(room_id.as_bytes())? { Ok(match self.roomid_shortroomid.get(room_id.as_bytes())? {
Some(short) => { Some(short) => utils::u64_from_bytes(&short)
utils::u64_from_bytes(&short).map_err(|_| Error::bad_database("Invalid shortroomid in db."))? .map_err(|_| Error::bad_database("Invalid shortroomid in db."))?,
},
None => { None => {
let short = services().globals.next_count()?; let short = services().globals.next_count()?;
self.roomid_shortroomid.insert(room_id.as_bytes(), &short.to_be_bytes())?; self.roomid_shortroomid
.insert(room_id.as_bytes(), &short.to_be_bytes())?;
short short
}, }
}) })
} }
/// Attempts to delete a shortroomid from the kv database
fn delete_shortroomid(&self, room_id: &RoomId) -> Result<()> {
match self.roomid_shortroomid.get(room_id.as_bytes())? {
Some(short) => {
self.roomid_shortroomid.remove(&short).map_err(|e| {
error!("Failed to remove shortroomid in database: {e}");
Error::bad_database("Failed to remove shortroomid in database")
})?;
}
None => {
return Err(Error::bad_database(
"Invalid or non-existent shortroomid in db.",
))?
}
}
Ok(())
}
} }
+39 -13
View File
@@ -1,13 +1,17 @@
use std::{collections::HashSet, sync::Arc};
use ruma::{EventId, OwnedEventId, RoomId}; use ruma::{EventId, OwnedEventId, RoomId};
use std::collections::HashSet;
use tracing::debug;
use std::sync::Arc;
use tokio::sync::MutexGuard; use tokio::sync::MutexGuard;
use crate::{database::KeyValueDatabase, service, utils, Error, Result}; use crate::{database::KeyValueDatabase, service, utils, Error, Result};
impl service::rooms::state::Data for KeyValueDatabase { impl service::rooms::state::Data for KeyValueDatabase {
fn get_room_shortstatehash(&self, room_id: &RoomId) -> Result<Option<u64>> { fn get_room_shortstatehash(&self, room_id: &RoomId) -> Result<Option<u64>> {
self.roomid_shortstatehash.get(room_id.as_bytes())?.map_or(Ok(None), |bytes| { self.roomid_shortstatehash
.get(room_id.as_bytes())?
.map_or(Ok(None), |bytes| {
Ok(Some(utils::u64_from_bytes(&bytes).map_err(|_| { Ok(Some(utils::u64_from_bytes(&bytes).map_err(|_| {
Error::bad_database("Invalid shortstatehash in roomid_shortstatehash") Error::bad_database("Invalid shortstatehash in roomid_shortstatehash")
})?)) })?))
@@ -20,50 +24,72 @@ impl service::rooms::state::Data for KeyValueDatabase {
new_shortstatehash: u64, new_shortstatehash: u64,
_mutex_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room state mutex _mutex_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room state mutex
) -> Result<()> { ) -> Result<()> {
self.roomid_shortstatehash.insert(room_id.as_bytes(), &new_shortstatehash.to_be_bytes())?; self.roomid_shortstatehash
.insert(room_id.as_bytes(), &new_shortstatehash.to_be_bytes())?;
Ok(())
}
fn delete_room_shortstatehash(
&self,
room_id: &RoomId,
_mutex_lock: &MutexGuard<'_, ()>,
) -> Result<()> {
self.roomid_shortstatehash.remove(room_id.as_bytes())?;
Ok(()) Ok(())
} }
fn set_event_state(&self, shorteventid: u64, shortstatehash: u64) -> Result<()> { fn set_event_state(&self, shorteventid: u64, shortstatehash: u64) -> Result<()> {
self.shorteventid_shortstatehash.insert(&shorteventid.to_be_bytes(), &shortstatehash.to_be_bytes())?; self.shorteventid_shortstatehash
.insert(&shorteventid.to_be_bytes(), &shortstatehash.to_be_bytes())?;
Ok(()) Ok(())
} }
fn get_forward_extremities(&self, room_id: &RoomId) -> Result<HashSet<Arc<EventId>>> { fn get_forward_extremities(&self, room_id: &RoomId) -> Result<HashSet<Arc<EventId>>> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
self.roomid_pduleaves self.roomid_pduleaves
.scan_prefix(prefix) .scan_prefix(prefix)
.map(|(_, bytes)| { .map(|(_, bytes)| {
EventId::parse_arc( EventId::parse_arc(utils::string_from_bytes(&bytes).map_err(|_| {
utils::string_from_bytes(&bytes) Error::bad_database("EventID in roomid_pduleaves is invalid unicode.")
.map_err(|_| Error::bad_database("EventID in roomid_pduleaves is invalid unicode."))?, })?)
)
.map_err(|_| Error::bad_database("EventId in roomid_pduleaves is invalid.")) .map_err(|_| Error::bad_database("EventId in roomid_pduleaves is invalid."))
}) })
.collect() .collect()
} }
fn set_forward_extremities( fn set_forward_extremities<'a>(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
event_ids: Vec<OwnedEventId>, event_ids: Vec<OwnedEventId>,
_mutex_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room state mutex _mutex_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room state mutex
) -> Result<()> { ) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
for (key, _) in self.roomid_pduleaves.scan_prefix(prefix.clone()) { for (key, _) in self.roomid_pduleaves.scan_prefix(prefix.clone()) {
self.roomid_pduleaves.remove(&key)?; self.roomid_pduleaves.remove(&key)?;
} }
for event_id in event_ids { for event_id in event_ids {
let mut key = prefix.clone(); let mut key = prefix.to_owned();
key.extend_from_slice(event_id.as_bytes()); key.extend_from_slice(event_id.as_bytes());
self.roomid_pduleaves.insert(&key, event_id.as_bytes())?; self.roomid_pduleaves.insert(&key, event_id.as_bytes())?;
} }
Ok(()) Ok(())
} }
fn delete_all_rooms_forward_extremities(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
for (key, _) in self.roomid_pduleaves.scan_prefix(prefix) {
debug!("Removing key: {:?}", key);
self.roomid_pduleaves.remove(&key)?;
}
Ok(())
}
} }
+73 -34
View File
@@ -1,13 +1,11 @@
use std::{collections::HashMap, sync::Arc}; use std::{collections::HashMap, sync::Arc};
use crate::{database::KeyValueDatabase, service, services, utils, Error, PduEvent, Result};
use async_trait::async_trait; use async_trait::async_trait;
use ruma::{events::StateEventType, EventId, RoomId}; use ruma::{events::StateEventType, EventId, RoomId};
use crate::{database::KeyValueDatabase, service, services, utils, Error, PduEvent, Result};
#[async_trait] #[async_trait]
impl service::rooms::state_accessor::Data for KeyValueDatabase { impl service::rooms::state_accessor::Data for KeyValueDatabase {
#[allow(unused_qualifications)] // async traits
async fn state_full_ids(&self, shortstatehash: u64) -> Result<HashMap<u64, Arc<EventId>>> { async fn state_full_ids(&self, shortstatehash: u64) -> Result<HashMap<u64, Arc<EventId>>> {
let full_state = services() let full_state = services()
.rooms .rooms
@@ -19,7 +17,10 @@ impl service::rooms::state_accessor::Data for KeyValueDatabase {
let mut result = HashMap::new(); let mut result = HashMap::new();
let mut i = 0; let mut i = 0;
for compressed in full_state.iter() { for compressed in full_state.iter() {
let parsed = services().rooms.state_compressor.parse_compressed_state_event(compressed)?; let parsed = services()
.rooms
.state_compressor
.parse_compressed_state_event(compressed)?;
result.insert(parsed.0, parsed.1); result.insert(parsed.0, parsed.1);
i += 1; i += 1;
@@ -30,8 +31,10 @@ impl service::rooms::state_accessor::Data for KeyValueDatabase {
Ok(result) Ok(result)
} }
#[allow(unused_qualifications)] // async traits async fn state_full(
async fn state_full(&self, shortstatehash: u64) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> { &self,
shortstatehash: u64,
) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
let full_state = services() let full_state = services()
.rooms .rooms
.state_compressor .state_compressor
@@ -43,7 +46,10 @@ impl service::rooms::state_accessor::Data for KeyValueDatabase {
let mut result = HashMap::new(); let mut result = HashMap::new();
let mut i = 0; let mut i = 0;
for compressed in full_state.iter() { for compressed in full_state.iter() {
let (_, eventid) = services().rooms.state_compressor.parse_compressed_state_event(compressed)?; let (_, eventid) = services()
.rooms
.state_compressor
.parse_compressed_state_event(compressed)?;
if let Some(pdu) = services().rooms.timeline.get_pdu(&eventid)? { if let Some(pdu) = services().rooms.timeline.get_pdu(&eventid)? {
result.insert( result.insert(
( (
@@ -66,12 +72,18 @@ impl service::rooms::state_accessor::Data for KeyValueDatabase {
Ok(result) Ok(result)
} }
/// Returns a single PDU from `room_id` with key (`event_type`, /// Returns a single PDU from `room_id` with key (`event_type`, `state_key`).
/// `state_key`).
fn state_get_id( fn state_get_id(
&self, shortstatehash: u64, event_type: &StateEventType, state_key: &str, &self,
shortstatehash: u64,
event_type: &StateEventType,
state_key: &str,
) -> Result<Option<Arc<EventId>>> { ) -> Result<Option<Arc<EventId>>> {
let shortstatekey = match services().rooms.short.get_shortstatekey(event_type, state_key)? { let shortstatekey = match services()
.rooms
.short
.get_shortstatekey(event_type, state_key)?
{
Some(s) => s, Some(s) => s,
None => return Ok(None), None => return Ok(None),
}; };
@@ -82,63 +94,90 @@ impl service::rooms::state_accessor::Data for KeyValueDatabase {
.pop() .pop()
.expect("there is always one layer") .expect("there is always one layer")
.1; .1;
Ok( Ok(full_state
full_state.iter().find(|bytes| bytes.starts_with(&shortstatekey.to_be_bytes())).and_then(|compressed| { .iter()
services().rooms.state_compressor.parse_compressed_state_event(compressed).ok().map(|(_, id)| id) .find(|bytes| bytes.starts_with(&shortstatekey.to_be_bytes()))
}), .and_then(|compressed| {
) services()
.rooms
.state_compressor
.parse_compressed_state_event(compressed)
.ok()
.map(|(_, id)| id)
}))
} }
/// Returns a single PDU from `room_id` with key (`event_type`, /// Returns a single PDU from `room_id` with key (`event_type`, `state_key`).
/// `state_key`).
fn state_get( fn state_get(
&self, shortstatehash: u64, event_type: &StateEventType, state_key: &str, &self,
shortstatehash: u64,
event_type: &StateEventType,
state_key: &str,
) -> Result<Option<Arc<PduEvent>>> { ) -> Result<Option<Arc<PduEvent>>> {
self.state_get_id(shortstatehash, event_type, state_key)? self.state_get_id(shortstatehash, event_type, state_key)?
.map_or(Ok(None), |event_id| services().rooms.timeline.get_pdu(&event_id)) .map_or(Ok(None), |event_id| {
services().rooms.timeline.get_pdu(&event_id)
})
} }
/// Returns the state hash for this pdu. /// Returns the state hash for this pdu.
fn pdu_shortstatehash(&self, event_id: &EventId) -> Result<Option<u64>> { fn pdu_shortstatehash(&self, event_id: &EventId) -> Result<Option<u64>> {
self.eventid_shorteventid.get(event_id.as_bytes())?.map_or(Ok(None), |shorteventid| { self.eventid_shorteventid
.get(event_id.as_bytes())?
.map_or(Ok(None), |shorteventid| {
self.shorteventid_shortstatehash self.shorteventid_shortstatehash
.get(&shorteventid)? .get(&shorteventid)?
.map(|bytes| { .map(|bytes| {
utils::u64_from_bytes(&bytes) utils::u64_from_bytes(&bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Invalid shortstatehash bytes in shorteventid_shortstatehash")) Error::bad_database(
"Invalid shortstatehash bytes in shorteventid_shortstatehash",
)
})
}) })
.transpose() .transpose()
}) })
} }
/// Returns the full room state. /// Returns the full room state.
#[allow(unused_qualifications)] // async traits async fn room_state_full(
async fn room_state_full(&self, room_id: &RoomId) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> { &self,
if let Some(current_shortstatehash) = services().rooms.state.get_room_shortstatehash(room_id)? { room_id: &RoomId,
) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
if let Some(current_shortstatehash) =
services().rooms.state.get_room_shortstatehash(room_id)?
{
self.state_full(current_shortstatehash).await self.state_full(current_shortstatehash).await
} else { } else {
Ok(HashMap::new()) Ok(HashMap::new())
} }
} }
/// Returns a single PDU from `room_id` with key (`event_type`, /// Returns a single PDU from `room_id` with key (`event_type`, `state_key`).
/// `state_key`).
fn room_state_get_id( fn room_state_get_id(
&self, room_id: &RoomId, event_type: &StateEventType, state_key: &str, &self,
room_id: &RoomId,
event_type: &StateEventType,
state_key: &str,
) -> Result<Option<Arc<EventId>>> { ) -> Result<Option<Arc<EventId>>> {
if let Some(current_shortstatehash) = services().rooms.state.get_room_shortstatehash(room_id)? { if let Some(current_shortstatehash) =
services().rooms.state.get_room_shortstatehash(room_id)?
{
self.state_get_id(current_shortstatehash, event_type, state_key) self.state_get_id(current_shortstatehash, event_type, state_key)
} else { } else {
Ok(None) Ok(None)
} }
} }
/// Returns a single PDU from `room_id` with key (`event_type`, /// Returns a single PDU from `room_id` with key (`event_type`, `state_key`).
/// `state_key`).
fn room_state_get( fn room_state_get(
&self, room_id: &RoomId, event_type: &StateEventType, state_key: &str, &self,
room_id: &RoomId,
event_type: &StateEventType,
state_key: &str,
) -> Result<Option<Arc<PduEvent>>> { ) -> Result<Option<Arc<PduEvent>>> {
if let Some(current_shortstatehash) = services().rooms.state.get_room_shortstatehash(room_id)? { if let Some(current_shortstatehash) =
services().rooms.state.get_room_shortstatehash(room_id)?
{
self.state_get(current_shortstatehash, event_type, state_key) self.state_get(current_shortstatehash, event_type, state_key)
} else { } else {
Ok(None) Ok(None)
+283 -109
View File
@@ -1,36 +1,37 @@
use std::{collections::HashSet, sync::Arc}; use std::{collections::HashSet, sync::Arc};
use regex::Regex;
use ruma::{ use ruma::{
api::appservice::Registration,
events::{AnyStrippedStateEvent, AnySyncStateEvent}, events::{AnyStrippedStateEvent, AnySyncStateEvent},
serde::Raw, serde::Raw,
OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, ServerName, UserId, OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, ServerName, UserId,
}; };
use tracing::debug;
use crate::{ use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
database::KeyValueDatabase,
service::{self, appservice::RegistrationInfo},
services, utils, Error, Result,
};
type StrippedStateEventIter<'a> = Box<dyn Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnyStrippedStateEvent>>)>> + 'a>; type StrippedStateEventIter<'a> =
Box<dyn Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnyStrippedStateEvent>>)>> + 'a>;
type AnySyncStateEventIter<'a> = Box<dyn Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnySyncStateEvent>>)>> + 'a>; type AnySyncStateEventIter<'a> =
Box<dyn Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnySyncStateEvent>>)>> + 'a>;
impl service::rooms::state_cache::Data for KeyValueDatabase { impl service::rooms::state_cache::Data for KeyValueDatabase {
fn mark_as_once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> { fn mark_as_once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
self.roomuseroncejoinedids.insert(&userroom_id, &[]) self.roomuseroncejoinedids.insert(&userroom_id, &[])
} }
fn mark_as_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> { fn mark_as_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
let mut roomuser_id = room_id.as_bytes().to_vec(); let mut roomuser_id = room_id.as_bytes().to_vec();
roomuser_id.push(0xFF); roomuser_id.push(0xff);
roomuser_id.extend_from_slice(user_id.as_bytes()); roomuser_id.extend_from_slice(user_id.as_bytes());
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
self.userroomid_joined.insert(&userroom_id, &[])?; self.userroomid_joined.insert(&userroom_id, &[])?;
@@ -44,21 +45,28 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
} }
fn mark_as_invited( fn mark_as_invited(
&self, user_id: &UserId, room_id: &RoomId, last_state: Option<Vec<Raw<AnyStrippedStateEvent>>>, &self,
user_id: &UserId,
room_id: &RoomId,
last_state: Option<Vec<Raw<AnyStrippedStateEvent>>>,
) -> Result<()> { ) -> Result<()> {
let mut roomuser_id = room_id.as_bytes().to_vec(); let mut roomuser_id = room_id.as_bytes().to_vec();
roomuser_id.push(0xFF); roomuser_id.push(0xff);
roomuser_id.extend_from_slice(user_id.as_bytes()); roomuser_id.extend_from_slice(user_id.as_bytes());
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
self.userroomid_invitestate.insert( self.userroomid_invitestate.insert(
&userroom_id, &userroom_id,
&serde_json::to_vec(&last_state.unwrap_or_default()).expect("state to bytes always works"), &serde_json::to_vec(&last_state.unwrap_or_default())
.expect("state to bytes always works"),
)?;
self.roomuserid_invitecount.insert(
&roomuser_id,
&services().globals.next_count()?.to_be_bytes(),
)?; )?;
self.roomuserid_invitecount.insert(&roomuser_id, &services().globals.next_count()?.to_be_bytes())?;
self.userroomid_joined.remove(&userroom_id)?; self.userroomid_joined.remove(&userroom_id)?;
self.roomuserid_joined.remove(&roomuser_id)?; self.roomuserid_joined.remove(&roomuser_id)?;
self.userroomid_leftstate.remove(&userroom_id)?; self.userroomid_leftstate.remove(&userroom_id)?;
@@ -69,18 +77,21 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
fn mark_as_left(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> { fn mark_as_left(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
let mut roomuser_id = room_id.as_bytes().to_vec(); let mut roomuser_id = room_id.as_bytes().to_vec();
roomuser_id.push(0xFF); roomuser_id.push(0xff);
roomuser_id.extend_from_slice(user_id.as_bytes()); roomuser_id.extend_from_slice(user_id.as_bytes());
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
self.userroomid_leftstate.insert( self.userroomid_leftstate.insert(
&userroom_id, &userroom_id,
&serde_json::to_vec(&Vec::<Raw<AnySyncStateEvent>>::new()).unwrap(), &serde_json::to_vec(&Vec::<Raw<AnySyncStateEvent>>::new()).unwrap(),
)?; // TODO )?; // TODO
self.roomuserid_leftcount.insert(&roomuser_id, &services().globals.next_count()?.to_be_bytes())?; self.roomuserid_leftcount.insert(
&roomuser_id,
&services().globals.next_count()?.to_be_bytes(),
)?;
self.userroomid_joined.remove(&userroom_id)?; self.userroomid_joined.remove(&userroom_id)?;
self.roomuserid_joined.remove(&roomuser_id)?; self.roomuserid_joined.remove(&roomuser_id)?;
self.userroomid_invitestate.remove(&userroom_id)?; self.userroomid_invitestate.remove(&userroom_id)?;
@@ -89,13 +100,35 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
fn delete_room_join_counts(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
for (key, _) in self.roomid_joinedcount.scan_prefix(prefix.clone()) {
debug!("Removing key: {:?}", key);
self.roomid_joinedcount.remove(&key)?;
}
for (key, _) in self.roomid_invitedcount.scan_prefix(prefix.clone()) {
debug!("Removing key: {:?}", key);
self.roomid_invitedcount.remove(&key)?;
}
for (key, _) in self.roomserverids.scan_prefix(prefix.clone()) {
debug!("Removing key: {:?}", key);
self.roomserverids.remove(&key)?;
}
Ok(())
}
fn update_joined_count(&self, room_id: &RoomId) -> Result<()> { fn update_joined_count(&self, room_id: &RoomId) -> Result<()> {
let mut joinedcount = 0_u64; let mut joinedcount = 0_u64;
let mut invitedcount = 0_u64; let mut invitedcount = 0_u64;
let mut joined_servers = HashSet::new(); let mut joined_servers = HashSet::new();
let mut real_users = HashSet::new(); let mut real_users = HashSet::new();
for joined in self.room_members(room_id).filter_map(std::result::Result::ok) { for joined in self.room_members(room_id).filter_map(|r| r.ok()) {
joined_servers.insert(joined.server_name().to_owned()); joined_servers.insert(joined.server_name().to_owned());
if joined.server_name() == services().globals.server_name() if joined.server_name() == services().globals.server_name()
&& !services().users.is_deactivated(&joined).unwrap_or(true) && !services().users.is_deactivated(&joined).unwrap_or(true)
@@ -105,25 +138,30 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
joinedcount += 1; joinedcount += 1;
} }
for _invited in self.room_members_invited(room_id).filter_map(std::result::Result::ok) { for _invited in self.room_members_invited(room_id).filter_map(|r| r.ok()) {
invitedcount += 1; invitedcount += 1;
} }
self.roomid_joinedcount.insert(room_id.as_bytes(), &joinedcount.to_be_bytes())?; self.roomid_joinedcount
.insert(room_id.as_bytes(), &joinedcount.to_be_bytes())?;
self.roomid_invitedcount.insert(room_id.as_bytes(), &invitedcount.to_be_bytes())?; self.roomid_invitedcount
.insert(room_id.as_bytes(), &invitedcount.to_be_bytes())?;
self.our_real_users_cache.write().unwrap().insert(room_id.to_owned(), Arc::new(real_users)); self.our_real_users_cache
.write()
.unwrap()
.insert(room_id.to_owned(), Arc::new(real_users));
for old_joined_server in self.room_servers(room_id).filter_map(std::result::Result::ok) { for old_joined_server in self.room_servers(room_id).filter_map(|r| r.ok()) {
if !joined_servers.remove(&old_joined_server) { if !joined_servers.remove(&old_joined_server) {
// Server not in room anymore // Server not in room anymore
let mut roomserver_id = room_id.as_bytes().to_vec(); let mut roomserver_id = room_id.as_bytes().to_vec();
roomserver_id.push(0xFF); roomserver_id.push(0xff);
roomserver_id.extend_from_slice(old_joined_server.as_bytes()); roomserver_id.extend_from_slice(old_joined_server.as_bytes());
let mut serverroom_id = old_joined_server.as_bytes().to_vec(); let mut serverroom_id = old_joined_server.as_bytes().to_vec();
serverroom_id.push(0xFF); serverroom_id.push(0xff);
serverroom_id.extend_from_slice(room_id.as_bytes()); serverroom_id.extend_from_slice(room_id.as_bytes());
self.roomserverids.remove(&roomserver_id)?; self.roomserverids.remove(&roomserver_id)?;
@@ -134,63 +172,91 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
// Now only new servers are in joined_servers anymore // Now only new servers are in joined_servers anymore
for server in joined_servers { for server in joined_servers {
let mut roomserver_id = room_id.as_bytes().to_vec(); let mut roomserver_id = room_id.as_bytes().to_vec();
roomserver_id.push(0xFF); roomserver_id.push(0xff);
roomserver_id.extend_from_slice(server.as_bytes()); roomserver_id.extend_from_slice(server.as_bytes());
let mut serverroom_id = server.as_bytes().to_vec(); let mut serverroom_id = server.as_bytes().to_vec();
serverroom_id.push(0xFF); serverroom_id.push(0xff);
serverroom_id.extend_from_slice(room_id.as_bytes()); serverroom_id.extend_from_slice(room_id.as_bytes());
self.roomserverids.insert(&roomserver_id, &[])?; self.roomserverids.insert(&roomserver_id, &[])?;
self.serverroomids.insert(&serverroom_id, &[])?; self.serverroomids.insert(&serverroom_id, &[])?;
} }
self.appservice_in_room_cache.write().unwrap().remove(room_id); self.appservice_in_room_cache
.write()
.unwrap()
.remove(room_id);
Ok(()) Ok(())
} }
#[tracing::instrument(skip(self, room_id))] #[tracing::instrument(skip(self, room_id))]
fn get_our_real_users(&self, room_id: &RoomId) -> Result<Arc<HashSet<OwnedUserId>>> { fn get_our_real_users(&self, room_id: &RoomId) -> Result<Arc<HashSet<OwnedUserId>>> {
let maybe = self.our_real_users_cache.read().unwrap().get(room_id).cloned(); let maybe = self
.our_real_users_cache
.read()
.unwrap()
.get(room_id)
.cloned();
if let Some(users) = maybe { if let Some(users) = maybe {
Ok(users) Ok(users)
} else { } else {
self.update_joined_count(room_id)?; self.update_joined_count(room_id)?;
Ok(Arc::clone(self.our_real_users_cache.read().unwrap().get(room_id).unwrap())) Ok(Arc::clone(
self.our_real_users_cache
.read()
.unwrap()
.get(room_id)
.unwrap(),
))
} }
} }
#[tracing::instrument(skip(self, room_id, appservice))] /// Check our room state cache if an appservice is in the room ID
fn appservice_in_room(&self, room_id: &RoomId, appservice: &RegistrationInfo) -> Result<bool> { fn appservice_in_room(
&self,
room_id: &RoomId,
appservice: &(String, Registration),
) -> Result<bool> {
let maybe = self let maybe = self
.appservice_in_room_cache .appservice_in_room_cache
.read() .read()
.unwrap() .unwrap()
.get(room_id) .get(room_id)
.and_then(|map| map.get(&appservice.registration.id)) .and_then(|map| map.get(&appservice.0))
.copied(); .copied();
if let Some(b) = maybe { if let Some(b) = maybe {
Ok(b) Ok(b)
} else { } else {
let namespaces = &appservice.1.namespaces;
let users = namespaces
.users
.iter()
.filter_map(|users| Regex::new(users.regex.as_str()).ok())
.collect::<Vec<_>>();
let bridge_user_id = UserId::parse_with_server_name( let bridge_user_id = UserId::parse_with_server_name(
appservice.registration.sender_localpart.as_str(), appservice.1.sender_localpart.as_str(),
services().globals.server_name(), services().globals.server_name(),
) )
.ok(); .ok();
let in_room = bridge_user_id.map_or(false, |id| self.is_joined(&id, room_id).unwrap_or(false)) let in_room = bridge_user_id
|| self .map_or(false, |id| self.is_joined(&id, room_id).unwrap_or(false))
.room_members(room_id) || self.room_members(room_id).any(|userid| {
.any(|userid| userid.map_or(false, |userid| appservice.users.is_match(userid.as_str()))); userid.map_or(false, |userid| {
users.iter().any(|r| r.is_match(userid.as_str()))
})
});
self.appservice_in_room_cache self.appservice_in_room_cache
.write() .write()
.unwrap() .unwrap()
.entry(room_id.to_owned()) .entry(room_id.to_owned())
.or_default() .or_default()
.insert(appservice.registration.id.clone(), in_room); .insert(appservice.0.clone(), in_room);
Ok(in_room) Ok(in_room)
} }
@@ -200,11 +266,11 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn forget(&self, room_id: &RoomId, user_id: &UserId) -> Result<()> { fn forget(&self, room_id: &RoomId, user_id: &UserId) -> Result<()> {
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
let mut roomuser_id = room_id.as_bytes().to_vec(); let mut roomuser_id = room_id.as_bytes().to_vec();
roomuser_id.push(0xFF); roomuser_id.push(0xff);
roomuser_id.extend_from_slice(user_id.as_bytes()); roomuser_id.extend_from_slice(user_id.as_bytes());
self.userroomid_leftstate.remove(&userroom_id)?; self.userroomid_leftstate.remove(&userroom_id)?;
@@ -215,38 +281,53 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
/// Returns an iterator of all servers participating in this room. /// Returns an iterator of all servers participating in this room.
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn room_servers<'a>(&'a self, room_id: &RoomId) -> Box<dyn Iterator<Item = Result<OwnedServerName>> + 'a> { fn room_servers<'a>(
&'a self,
room_id: &RoomId,
) -> Box<dyn Iterator<Item = Result<OwnedServerName>> + 'a> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
Box::new(self.roomserverids.scan_prefix(prefix).map(|(key, _)| { Box::new(self.roomserverids.scan_prefix(prefix).map(|(key, _)| {
ServerName::parse( ServerName::parse(
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element")) utils::string_from_bytes(
.map_err(|_| Error::bad_database("Server name in roomserverids is invalid unicode."))?, key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| {
Error::bad_database("Server name in roomserverids is invalid unicode.")
})?,
) )
.map_err(|_| Error::bad_database("Server name in roomserverids is invalid.")) .map_err(|_| Error::bad_database("Server name in roomserverids is invalid."))
})) }))
} }
#[tracing::instrument(skip(self))] /// Check our room state cache if a server is in the room ID
fn server_in_room(&self, server: &ServerName, room_id: &RoomId) -> Result<bool> { fn server_in_room(&self, server: &ServerName, room_id: &RoomId) -> Result<bool> {
let mut key = server.as_bytes().to_vec(); let mut key = server.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
self.serverroomids.get(&key).map(|o| o.is_some()) self.serverroomids.get(&key).map(|o| o.is_some())
} }
/// Returns an iterator of all rooms a server participates in (as far as we /// Returns an iterator of all rooms a server participates in (as far as we know).
/// know).
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn server_rooms<'a>(&'a self, server: &ServerName) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> { fn server_rooms<'a>(
&'a self,
server: &ServerName,
) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> {
let mut prefix = server.as_bytes().to_vec(); let mut prefix = server.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
Box::new(self.serverroomids.scan_prefix(prefix).map(|(key, _)| { Box::new(self.serverroomids.scan_prefix(prefix).map(|(key, _)| {
RoomId::parse( RoomId::parse(
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element")) utils::string_from_bytes(
key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| Error::bad_database("RoomId in serverroomids is invalid unicode."))?, .map_err(|_| Error::bad_database("RoomId in serverroomids is invalid unicode."))?,
) )
.map_err(|_| Error::bad_database("RoomId in serverroomids is invalid.")) .map_err(|_| Error::bad_database("RoomId in serverroomids is invalid."))
@@ -255,128 +336,204 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
/// Returns an iterator over all joined members of a room. /// Returns an iterator over all joined members of a room.
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn room_members<'a>(&'a self, room_id: &RoomId) -> Box<dyn Iterator<Item = Result<OwnedUserId>> + 'a> { fn room_members<'a>(
&'a self,
room_id: &RoomId,
) -> Box<dyn Iterator<Item = Result<OwnedUserId>> + 'a> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
Box::new(self.roomuserid_joined.scan_prefix(prefix).map(|(key, _)| { Box::new(self.roomuserid_joined.scan_prefix(prefix).map(|(key, _)| {
UserId::parse( UserId::parse(
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element")) utils::string_from_bytes(
.map_err(|_| Error::bad_database("User ID in roomuserid_joined is invalid unicode."))?, key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| {
Error::bad_database("User ID in roomuserid_joined is invalid unicode.")
})?,
) )
.map_err(|_| Error::bad_database("User ID in roomuserid_joined is invalid.")) .map_err(|_| Error::bad_database("User ID in roomuserid_joined is invalid."))
})) }))
} }
/// Returns the number of users which are currently in a room
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn room_joined_count(&self, room_id: &RoomId) -> Result<Option<u64>> { fn room_joined_count(&self, room_id: &RoomId) -> Result<Option<u64>> {
self.roomid_joinedcount self.roomid_joinedcount
.get(room_id.as_bytes())? .get(room_id.as_bytes())?
.map(|b| utils::u64_from_bytes(&b).map_err(|_| Error::bad_database("Invalid joinedcount in db."))) .map(|b| {
utils::u64_from_bytes(&b)
.map_err(|_| Error::bad_database("Invalid joinedcount in db."))
})
.transpose() .transpose()
} }
/// Returns the number of users which are currently invited to a room
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn room_invited_count(&self, room_id: &RoomId) -> Result<Option<u64>> { fn room_invited_count(&self, room_id: &RoomId) -> Result<Option<u64>> {
self.roomid_invitedcount self.roomid_invitedcount
.get(room_id.as_bytes())? .get(room_id.as_bytes())?
.map(|b| utils::u64_from_bytes(&b).map_err(|_| Error::bad_database("Invalid joinedcount in db."))) .map(|b| {
utils::u64_from_bytes(&b)
.map_err(|_| Error::bad_database("Invalid joinedcount in db."))
})
.transpose() .transpose()
} }
/// Returns an iterator over all User IDs who ever joined a room. /// Returns an iterator over all User IDs who ever joined a room.
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn room_useroncejoined<'a>(&'a self, room_id: &RoomId) -> Box<dyn Iterator<Item = Result<OwnedUserId>> + 'a> { fn room_useroncejoined<'a>(
&'a self,
room_id: &RoomId,
) -> Box<dyn Iterator<Item = Result<OwnedUserId>> + 'a> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
Box::new(self.roomuseroncejoinedids.scan_prefix(prefix).map(|(key, _)| { Box::new(
self.roomuseroncejoinedids
.scan_prefix(prefix)
.map(|(key, _)| {
UserId::parse( UserId::parse(
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element")) utils::string_from_bytes(
.map_err(|_| Error::bad_database("User ID in room_useroncejoined is invalid unicode."))?, key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| {
Error::bad_database(
"User ID in room_useroncejoined is invalid unicode.",
)
})?,
) )
.map_err(|_| Error::bad_database("User ID in room_useroncejoined is invalid.")) .map_err(|_| Error::bad_database("User ID in room_useroncejoined is invalid."))
})) }),
)
} }
/// Returns an iterator over all invited members of a room. /// Returns an iterator over all invited members of a room.
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn room_members_invited<'a>(&'a self, room_id: &RoomId) -> Box<dyn Iterator<Item = Result<OwnedUserId>> + 'a> { fn room_members_invited<'a>(
&'a self,
room_id: &RoomId,
) -> Box<dyn Iterator<Item = Result<OwnedUserId>> + 'a> {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
Box::new(self.roomuserid_invitecount.scan_prefix(prefix).map(|(key, _)| { Box::new(
self.roomuserid_invitecount
.scan_prefix(prefix)
.map(|(key, _)| {
UserId::parse( UserId::parse(
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element")) utils::string_from_bytes(
.map_err(|_| Error::bad_database("User ID in roomuserid_invited is invalid unicode."))?, key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| {
Error::bad_database("User ID in roomuserid_invited is invalid unicode.")
})?,
) )
.map_err(|_| Error::bad_database("User ID in roomuserid_invited is invalid.")) .map_err(|_| Error::bad_database("User ID in roomuserid_invited is invalid."))
})) }),
)
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn get_invite_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> { fn get_invite_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
let mut key = room_id.as_bytes().to_vec(); let mut key = room_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(user_id.as_bytes()); key.extend_from_slice(user_id.as_bytes());
self.roomuserid_invitecount.get(&key)?.map_or(Ok(None), |bytes| { self.roomuserid_invitecount
Ok(Some( .get(&key)?
utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid invitecount in db."))?, .map_or(Ok(None), |bytes| {
)) Ok(Some(utils::u64_from_bytes(&bytes).map_err(|_| {
Error::bad_database("Invalid invitecount in db.")
})?))
}) })
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn get_left_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> { fn get_left_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
let mut key = room_id.as_bytes().to_vec(); let mut key = room_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(user_id.as_bytes()); key.extend_from_slice(user_id.as_bytes());
self.roomuserid_leftcount self.roomuserid_leftcount
.get(&key)? .get(&key)?
.map(|bytes| utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid leftcount in db."))) .map(|bytes| {
utils::u64_from_bytes(&bytes)
.map_err(|_| Error::bad_database("Invalid leftcount in db."))
})
.transpose() .transpose()
} }
/// Returns an iterator over all rooms this user joined. /// Returns an iterator over all rooms this user joined.
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn rooms_joined<'a>(&'a self, user_id: &UserId) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> { fn rooms_joined<'a>(
Box::new(self.userroomid_joined.scan_prefix(user_id.as_bytes().to_vec()).map(|(key, _)| { &'a self,
user_id: &UserId,
) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> {
Box::new(
self.userroomid_joined
.scan_prefix(user_id.as_bytes().to_vec())
.map(|(key, _)| {
RoomId::parse( RoomId::parse(
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element")) utils::string_from_bytes(
.map_err(|_| Error::bad_database("Room ID in userroomid_joined is invalid unicode."))?, key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| {
Error::bad_database("Room ID in userroomid_joined is invalid unicode.")
})?,
) )
.map_err(|_| Error::bad_database("Room ID in userroomid_joined is invalid.")) .map_err(|_| Error::bad_database("Room ID in userroomid_joined is invalid."))
})) }),
)
} }
/// Returns an iterator over all rooms a user was invited to. /// Returns an iterator over all rooms a user was invited to.
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn rooms_invited<'a>(&'a self, user_id: &UserId) -> StrippedStateEventIter<'a> { fn rooms_invited<'a>(&'a self, user_id: &UserId) -> StrippedStateEventIter<'a> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
Box::new(self.userroomid_invitestate.scan_prefix(prefix).map(|(key, state)| { Box::new(
self.userroomid_invitestate
.scan_prefix(prefix)
.map(|(key, state)| {
let room_id = RoomId::parse( let room_id = RoomId::parse(
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element")) utils::string_from_bytes(
.map_err(|_| Error::bad_database("Room ID in userroomid_invited is invalid unicode."))?, key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
) )
.map_err(|_| Error::bad_database("Room ID in userroomid_invited is invalid."))?; .map_err(|_| {
Error::bad_database("Room ID in userroomid_invited is invalid unicode.")
})?,
)
.map_err(|_| {
Error::bad_database("Room ID in userroomid_invited is invalid.")
})?;
let state = serde_json::from_slice(&state) let state = serde_json::from_slice(&state).map_err(|_| {
.map_err(|_| Error::bad_database("Invalid state in userroomid_invitestate."))?; Error::bad_database("Invalid state in userroomid_invitestate.")
})?;
Ok((room_id, state)) Ok((room_id, state))
})) }),
)
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn invite_state(&self, user_id: &UserId, room_id: &RoomId) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> { fn invite_state(
&self,
user_id: &UserId,
room_id: &RoomId,
) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
self.userroomid_invitestate self.userroomid_invitestate
@@ -391,9 +548,13 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn left_state(&self, user_id: &UserId, room_id: &RoomId) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> { fn left_state(
&self,
user_id: &UserId,
room_id: &RoomId,
) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(room_id.as_bytes()); key.extend_from_slice(room_id.as_bytes());
self.userroomid_leftstate self.userroomid_leftstate
@@ -411,26 +572,39 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn rooms_left<'a>(&'a self, user_id: &UserId) -> AnySyncStateEventIter<'a> { fn rooms_left<'a>(&'a self, user_id: &UserId) -> AnySyncStateEventIter<'a> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
Box::new(self.userroomid_leftstate.scan_prefix(prefix).map(|(key, state)| { Box::new(
self.userroomid_leftstate
.scan_prefix(prefix)
.map(|(key, state)| {
let room_id = RoomId::parse( let room_id = RoomId::parse(
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element")) utils::string_from_bytes(
.map_err(|_| Error::bad_database("Room ID in userroomid_invited is invalid unicode."))?, key.rsplit(|&b| b == 0xff)
.next()
.expect("rsplit always returns an element"),
) )
.map_err(|_| Error::bad_database("Room ID in userroomid_invited is invalid."))?; .map_err(|_| {
Error::bad_database("Room ID in userroomid_invited is invalid unicode.")
})?,
)
.map_err(|_| {
Error::bad_database("Room ID in userroomid_invited is invalid.")
})?;
let state = serde_json::from_slice(&state) let state = serde_json::from_slice(&state).map_err(|_| {
.map_err(|_| Error::bad_database("Invalid state in userroomid_leftstate."))?; Error::bad_database("Invalid state in userroomid_leftstate.")
})?;
Ok((room_id, state)) Ok((room_id, state))
})) }),
)
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> { fn once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
Ok(self.roomuseroncejoinedids.get(&userroom_id)?.is_some()) Ok(self.roomuseroncejoinedids.get(&userroom_id)?.is_some())
@@ -439,7 +613,7 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn is_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> { fn is_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
Ok(self.userroomid_joined.get(&userroom_id)?.is_some()) Ok(self.userroomid_joined.get(&userroom_id)?.is_some())
@@ -448,7 +622,7 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn is_invited(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> { fn is_invited(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
Ok(self.userroomid_invitestate.get(&userroom_id)?.is_some()) Ok(self.userroomid_invitestate.get(&userroom_id)?.is_some())
@@ -457,7 +631,7 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
fn is_left(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> { fn is_left(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
Ok(self.userroomid_leftstate.get(&userroom_id)?.is_some()) Ok(self.userroomid_leftstate.get(&userroom_id)?.is_some())
@@ -12,12 +12,9 @@ impl service::rooms::state_compressor::Data for KeyValueDatabase {
.shortstatehash_statediff .shortstatehash_statediff
.get(&shortstatehash.to_be_bytes())? .get(&shortstatehash.to_be_bytes())?
.ok_or_else(|| Error::bad_database("State hash does not exist"))?; .ok_or_else(|| Error::bad_database("State hash does not exist"))?;
let parent = utils::u64_from_bytes(&value[0..size_of::<u64>()]).expect("bytes have right length"); let parent =
let parent = if parent != 0 { utils::u64_from_bytes(&value[0..size_of::<u64>()]).expect("bytes have right length");
Some(parent) let parent = if parent != 0 { Some(parent) } else { None };
} else {
None
};
let mut add_mode = true; let mut add_mode = true;
let mut added = HashSet::new(); let mut added = HashSet::new();
@@ -58,6 +55,7 @@ impl service::rooms::state_compressor::Data for KeyValueDatabase {
} }
} }
self.shortstatehash_statediff.insert(&shortstatehash.to_be_bytes(), &value) self.shortstatehash_statediff
.insert(&shortstatehash.to_be_bytes(), &value)
} }
} }
+43 -14
View File
@@ -1,6 +1,7 @@
use std::mem; use std::mem;
use ruma::{api::client::threads::get_threads::v1::IncludeThreads, OwnedUserId, RoomId, UserId}; use ruma::{api::client::threads::get_threads::v1::IncludeThreads, OwnedUserId, RoomId, UserId};
use tracing::debug;
use crate::{database::KeyValueDatabase, service, services, utils, Error, PduEvent, Result}; use crate::{database::KeyValueDatabase, service, services, utils, Error, PduEvent, Result};
@@ -8,34 +9,63 @@ type PduEventIterResult<'a> = Result<Box<dyn Iterator<Item = Result<(u64, PduEve
impl service::rooms::threads::Data for KeyValueDatabase { impl service::rooms::threads::Data for KeyValueDatabase {
fn threads_until<'a>( fn threads_until<'a>(
&'a self, user_id: &'a UserId, room_id: &'a RoomId, until: u64, _include: &'a IncludeThreads, &'a self,
user_id: &'a UserId,
room_id: &'a RoomId,
until: u64,
_include: &'a IncludeThreads,
) -> PduEventIterResult<'a> { ) -> PduEventIterResult<'a> {
let prefix = services().rooms.short.get_shortroomid(room_id)?.expect("room exists").to_be_bytes().to_vec(); let prefix = services()
.rooms
.short
.get_shortroomid(room_id)?
.expect("room exists")
.to_be_bytes()
.to_vec();
let mut current = prefix.clone(); let mut current = prefix.clone();
current.extend_from_slice(&(until - 1).to_be_bytes()); current.extend_from_slice(&(until - 1).to_be_bytes());
Ok(Box::new( Ok(Box::new(
self.threadid_userids.iter_from(&current, true).take_while(move |(k, _)| k.starts_with(&prefix)).map( self.threadid_userids
move |(pduid, _users)| { .iter_from(&current, true)
.take_while(move |(k, _)| k.starts_with(&prefix))
.map(move |(pduid, _users)| {
let count = utils::u64_from_bytes(&pduid[(mem::size_of::<u64>())..]) let count = utils::u64_from_bytes(&pduid[(mem::size_of::<u64>())..])
.map_err(|_| Error::bad_database("Invalid pduid in threadid_userids."))?; .map_err(|_| Error::bad_database("Invalid pduid in threadid_userids."))?;
let mut pdu = services() let mut pdu = services()
.rooms .rooms
.timeline .timeline
.get_pdu_from_id(&pduid)? .get_pdu_from_id(&pduid)?
.ok_or_else(|| Error::bad_database("Invalid pduid reference in threadid_userids"))?; .ok_or_else(|| {
Error::bad_database("Invalid pduid reference in threadid_userids")
})?;
if pdu.sender != user_id { if pdu.sender != user_id {
pdu.remove_transaction_id()?; pdu.remove_transaction_id()?;
} }
Ok((count, pdu)) Ok((count, pdu))
}, }),
),
)) ))
} }
fn delete_all_rooms_threads(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
for (key, _) in self.threadid_userids.scan_prefix(prefix) {
debug!("Removing key: {:?}", key);
self.threadid_userids.remove(&key)?;
}
Ok(())
}
fn update_participants(&self, root_id: &[u8], participants: &[OwnedUserId]) -> Result<()> { fn update_participants(&self, root_id: &[u8], participants: &[OwnedUserId]) -> Result<()> {
let users = participants.iter().map(|user| user.as_bytes()).collect::<Vec<_>>().join(&[0xFF][..]); let users = participants
.iter()
.map(|user| user.as_bytes())
.collect::<Vec<_>>()
.join(&[0xff][..]);
self.threadid_userids.insert(root_id, &users)?; self.threadid_userids.insert(root_id, &users)?;
@@ -46,15 +76,14 @@ impl service::rooms::threads::Data for KeyValueDatabase {
if let Some(users) = self.threadid_userids.get(root_id)? { if let Some(users) = self.threadid_userids.get(root_id)? {
Ok(Some( Ok(Some(
users users
.split(|b| *b == 0xFF) .split(|b| *b == 0xff)
.map(|bytes| { .map(|bytes| {
UserId::parse( UserId::parse(utils::string_from_bytes(bytes).map_err(|_| {
utils::string_from_bytes(bytes) Error::bad_database("Invalid UserId bytes in threadid_userids.")
.map_err(|_| Error::bad_database("Invalid UserId bytes in threadid_userids."))?, })?)
)
.map_err(|_| Error::bad_database("Invalid UserId in threadid_userids.")) .map_err(|_| Error::bad_database("Invalid UserId in threadid_userids."))
}) })
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
.collect(), .collect(),
)) ))
} else { } else {
+141 -52
View File
@@ -1,34 +1,52 @@
use std::{collections::hash_map, mem::size_of, sync::Arc}; use std::{collections::hash_map, mem::size_of, sync::Arc};
use ruma::{api::client::error::ErrorKind, CanonicalJsonObject, EventId, OwnedUserId, RoomId, UserId}; use ruma::{
use service::rooms::timeline::PduCount; api::client::error::ErrorKind, CanonicalJsonObject, EventId, OwnedUserId, RoomId, UserId,
use tracing::error; };
use tracing::{debug, error};
use crate::{database::KeyValueDatabase, service, services, utils, Error, PduEvent, Result}; use crate::{
database::KeyValueDatabase,
service::{self, rooms::timeline::data::PduData},
services, utils, Error, PduEvent, Result,
};
use service::rooms::timeline::PduCount;
impl service::rooms::timeline::Data for KeyValueDatabase { impl service::rooms::timeline::Data for KeyValueDatabase {
fn last_timeline_count(&self, sender_user: &UserId, room_id: &RoomId) -> Result<PduCount> { fn last_timeline_count(&self, sender_user: &UserId, room_id: &RoomId) -> Result<PduCount> {
match self.lasttimelinecount_cache.lock().unwrap().entry(room_id.to_owned()) { match self
.lasttimelinecount_cache
.lock()
.unwrap()
.entry(room_id.to_owned())
{
hash_map::Entry::Vacant(v) => { hash_map::Entry::Vacant(v) => {
if let Some(last_count) = self.pdus_until(sender_user, room_id, PduCount::max())?.find_map(|r| { if let Some(last_count) = self
.pdus_until(sender_user, room_id, PduCount::max())?
.find_map(|r| {
// Filter out buggy events // Filter out buggy events
if r.is_err() { if r.is_err() {
error!("Bad pdu in pdus_since: {:?}", r); error!("Bad pdu in pdus_since: {:?}", r);
} }
r.ok() r.ok()
}) { })
{
Ok(*v.insert(last_count.0)) Ok(*v.insert(last_count.0))
} else { } else {
Ok(PduCount::Normal(0)) Ok(PduCount::Normal(0))
} }
}, }
hash_map::Entry::Occupied(o) => Ok(*o.get()), hash_map::Entry::Occupied(o) => Ok(*o.get()),
} }
} }
/// Returns the `count` of this pdu's id. /// Returns the `count` of this pdu's id.
fn get_pdu_count(&self, event_id: &EventId) -> Result<Option<PduCount>> { fn get_pdu_count(&self, event_id: &EventId) -> Result<Option<PduCount>> {
self.eventid_pduid.get(event_id.as_bytes())?.map(|pdu_id| pdu_count(&pdu_id)).transpose() self.eventid_pduid
.get(event_id.as_bytes())?
.map(|pdu_id| pdu_count(&pdu_id))
.transpose()
} }
/// Returns the json of a pdu. /// Returns the json of a pdu.
@@ -37,7 +55,10 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
|| { || {
self.eventid_outlierpdu self.eventid_outlierpdu
.get(event_id.as_bytes())? .get(event_id.as_bytes())?
.map(|pdu| serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))) .map(|pdu| {
serde_json::from_slice(&pdu)
.map_err(|_| Error::bad_database("Invalid PDU in db."))
})
.transpose() .transpose()
}, },
|x| Ok(Some(x)), |x| Ok(Some(x)),
@@ -49,25 +70,35 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
self.eventid_pduid self.eventid_pduid
.get(event_id.as_bytes())? .get(event_id.as_bytes())?
.map(|pduid| { .map(|pduid| {
self.pduid_pdu.get(&pduid)?.ok_or_else(|| Error::bad_database("Invalid pduid in eventid_pduid.")) self.pduid_pdu
.get(&pduid)?
.ok_or_else(|| Error::bad_database("Invalid pduid in eventid_pduid."))
}) })
.transpose()? .transpose()?
.map(|pdu| serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))) .map(|pdu| {
serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))
})
.transpose() .transpose()
} }
/// Returns the pdu's id. /// Returns the pdu's id.
fn get_pdu_id(&self, event_id: &EventId) -> Result<Option<Vec<u8>>> { self.eventid_pduid.get(event_id.as_bytes()) } fn get_pdu_id(&self, event_id: &EventId) -> Result<Option<Vec<u8>>> {
self.eventid_pduid.get(event_id.as_bytes())
}
/// Returns the pdu. /// Returns the pdu.
fn get_non_outlier_pdu(&self, event_id: &EventId) -> Result<Option<PduEvent>> { fn get_non_outlier_pdu(&self, event_id: &EventId) -> Result<Option<PduEvent>> {
self.eventid_pduid self.eventid_pduid
.get(event_id.as_bytes())? .get(event_id.as_bytes())?
.map(|pduid| { .map(|pduid| {
self.pduid_pdu.get(&pduid)?.ok_or_else(|| Error::bad_database("Invalid pduid in eventid_pduid.")) self.pduid_pdu
.get(&pduid)?
.ok_or_else(|| Error::bad_database("Invalid pduid in eventid_pduid."))
}) })
.transpose()? .transpose()?
.map(|pdu| serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))) .map(|pdu| {
serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))
})
.transpose() .transpose()
} }
@@ -85,14 +116,20 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
|| { || {
self.eventid_outlierpdu self.eventid_outlierpdu
.get(event_id.as_bytes())? .get(event_id.as_bytes())?
.map(|pdu| serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))) .map(|pdu| {
serde_json::from_slice(&pdu)
.map_err(|_| Error::bad_database("Invalid PDU in db."))
})
.transpose() .transpose()
}, },
|x| Ok(Some(x)), |x| Ok(Some(x)),
)? )?
.map(Arc::new) .map(Arc::new)
{ {
self.pdu_cache.lock().unwrap().insert(event_id.to_owned(), Arc::clone(&pdu)); self.pdu_cache
.lock()
.unwrap()
.insert(event_id.to_owned(), Arc::clone(&pdu));
Ok(Some(pdu)) Ok(Some(pdu))
} else { } else {
Ok(None) Ok(None)
@@ -105,7 +142,8 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
fn get_pdu_from_id(&self, pdu_id: &[u8]) -> Result<Option<PduEvent>> { fn get_pdu_from_id(&self, pdu_id: &[u8]) -> Result<Option<PduEvent>> {
self.pduid_pdu.get(pdu_id)?.map_or(Ok(None), |pdu| { self.pduid_pdu.get(pdu_id)?.map_or(Ok(None), |pdu| {
Ok(Some( Ok(Some(
serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))?, serde_json::from_slice(&pdu)
.map_err(|_| Error::bad_database("Invalid PDU in db."))?,
)) ))
}) })
} }
@@ -114,18 +152,28 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
fn get_pdu_json_from_id(&self, pdu_id: &[u8]) -> Result<Option<CanonicalJsonObject>> { fn get_pdu_json_from_id(&self, pdu_id: &[u8]) -> Result<Option<CanonicalJsonObject>> {
self.pduid_pdu.get(pdu_id)?.map_or(Ok(None), |pdu| { self.pduid_pdu.get(pdu_id)?.map_or(Ok(None), |pdu| {
Ok(Some( Ok(Some(
serde_json::from_slice(&pdu).map_err(|_| Error::bad_database("Invalid PDU in db."))?, serde_json::from_slice(&pdu)
.map_err(|_| Error::bad_database("Invalid PDU in db."))?,
)) ))
}) })
} }
fn append_pdu(&self, pdu_id: &[u8], pdu: &PduEvent, json: &CanonicalJsonObject, count: u64) -> Result<()> { fn append_pdu(
&self,
pdu_id: &[u8],
pdu: &PduEvent,
json: &CanonicalJsonObject,
count: u64,
) -> Result<()> {
self.pduid_pdu.insert( self.pduid_pdu.insert(
pdu_id, pdu_id,
&serde_json::to_vec(json).expect("CanonicalJsonObject is always a valid"), &serde_json::to_vec(json).expect("CanonicalJsonObject is always a valid"),
)?; )?;
self.lasttimelinecount_cache.lock().unwrap().insert(pdu.room_id.clone(), PduCount::Normal(count)); self.lasttimelinecount_cache
.lock()
.unwrap()
.insert(pdu.room_id.clone(), PduCount::Normal(count));
self.eventid_pduid.insert(pdu.event_id.as_bytes(), pdu_id)?; self.eventid_pduid.insert(pdu.event_id.as_bytes(), pdu_id)?;
self.eventid_outlierpdu.remove(pdu.event_id.as_bytes())?; self.eventid_outlierpdu.remove(pdu.event_id.as_bytes())?;
@@ -133,7 +181,12 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
fn prepend_backfill_pdu(&self, pdu_id: &[u8], event_id: &EventId, json: &CanonicalJsonObject) -> Result<()> { fn prepend_backfill_pdu(
&self,
pdu_id: &[u8],
event_id: &EventId,
json: &CanonicalJsonObject,
) -> Result<()> {
self.pduid_pdu.insert( self.pduid_pdu.insert(
pdu_id, pdu_id,
&serde_json::to_vec(json).expect("CanonicalJsonObject is always a valid"), &serde_json::to_vec(json).expect("CanonicalJsonObject is always a valid"),
@@ -146,34 +199,49 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
} }
/// Removes a pdu and creates a new one with the same id. /// Removes a pdu and creates a new one with the same id.
fn replace_pdu(&self, pdu_id: &[u8], pdu_json: &CanonicalJsonObject, pdu: &PduEvent) -> Result<()> { fn replace_pdu(
&self,
pdu_id: &[u8],
pdu_json: &CanonicalJsonObject,
pdu: &PduEvent,
) -> Result<()> {
if self.pduid_pdu.get(pdu_id)?.is_some() { if self.pduid_pdu.get(pdu_id)?.is_some() {
self.pduid_pdu.insert( self.pduid_pdu.insert(
pdu_id, pdu_id,
&serde_json::to_vec(pdu_json).expect("CanonicalJsonObject is always a valid"), &serde_json::to_vec(pdu_json).expect("CanonicalJsonObject is always a valid"),
)?; )?;
} else { } else {
return Err(Error::BadRequest(ErrorKind::NotFound, "PDU does not exist.")); return Err(Error::BadRequest(
ErrorKind::NotFound,
"PDU does not exist.",
));
} }
self.pdu_cache.lock().unwrap().remove(&(*pdu.event_id).to_owned()); self.pdu_cache
.lock()
.unwrap()
.remove(&(*pdu.event_id).to_owned());
Ok(()) Ok(())
} }
/// Returns an iterator over all events and their tokens in a room that /// Returns an iterator over all events and their tokens in a room that happened before the
/// happened before the event with id `until` in reverse-chronological /// event with id `until` in reverse-chronological order.
/// order.
fn pdus_until<'a>( fn pdus_until<'a>(
&'a self, user_id: &UserId, room_id: &RoomId, until: PduCount, &'a self,
) -> Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>> { user_id: &UserId,
room_id: &RoomId,
until: PduCount,
) -> PduData<'a> {
let (prefix, current) = count_to_id(room_id, until, 1, true)?; let (prefix, current) = count_to_id(room_id, until, 1, true)?;
let user_id = user_id.to_owned(); let user_id = user_id.to_owned();
Ok(Box::new( Ok(Box::new(
self.pduid_pdu.iter_from(&current, true).take_while(move |(k, _)| k.starts_with(&prefix)).map( self.pduid_pdu
move |(pdu_id, v)| { .iter_from(&current, true)
.take_while(move |(k, _)| k.starts_with(&prefix))
.map(move |(pdu_id, v)| {
let mut pdu = serde_json::from_slice::<PduEvent>(&v) let mut pdu = serde_json::from_slice::<PduEvent>(&v)
.map_err(|_| Error::bad_database("PDU in db is invalid."))?; .map_err(|_| Error::bad_database("PDU in db is invalid."))?;
if pdu.sender != user_id { if pdu.sender != user_id {
@@ -182,21 +250,20 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
pdu.add_age()?; pdu.add_age()?;
let count = pdu_count(&pdu_id)?; let count = pdu_count(&pdu_id)?;
Ok((count, pdu)) Ok((count, pdu))
}, }),
),
)) ))
} }
fn pdus_after<'a>( fn pdus_after<'a>(&'a self, user_id: &UserId, room_id: &RoomId, from: PduCount) -> PduData<'a> {
&'a self, user_id: &UserId, room_id: &RoomId, from: PduCount,
) -> Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>> {
let (prefix, current) = count_to_id(room_id, from, 1, false)?; let (prefix, current) = count_to_id(room_id, from, 1, false)?;
let user_id = user_id.to_owned(); let user_id = user_id.to_owned();
Ok(Box::new( Ok(Box::new(
self.pduid_pdu.iter_from(&current, false).take_while(move |(k, _)| k.starts_with(&prefix)).map( self.pduid_pdu
move |(pdu_id, v)| { .iter_from(&current, false)
.take_while(move |(k, _)| k.starts_with(&prefix))
.map(move |(pdu_id, v)| {
let mut pdu = serde_json::from_slice::<PduEvent>(&v) let mut pdu = serde_json::from_slice::<PduEvent>(&v)
.map_err(|_| Error::bad_database("PDU in db is invalid."))?; .map_err(|_| Error::bad_database("PDU in db is invalid."))?;
if pdu.sender != user_id { if pdu.sender != user_id {
@@ -205,31 +272,47 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
pdu.add_age()?; pdu.add_age()?;
let count = pdu_count(&pdu_id)?; let count = pdu_count(&pdu_id)?;
Ok((count, pdu)) Ok((count, pdu))
}, }),
),
)) ))
} }
fn increment_notification_counts( fn increment_notification_counts(
&self, room_id: &RoomId, notifies: Vec<OwnedUserId>, highlights: Vec<OwnedUserId>, &self,
room_id: &RoomId,
notifies: Vec<OwnedUserId>,
highlights: Vec<OwnedUserId>,
) -> Result<()> { ) -> Result<()> {
let mut notifies_batch = Vec::new(); let mut notifies_batch = Vec::new();
let mut highlights_batch = Vec::new(); let mut highlights_batch = Vec::new();
for user in notifies { for user in notifies {
let mut userroom_id = user.as_bytes().to_vec(); let mut userroom_id = user.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
notifies_batch.push(userroom_id); notifies_batch.push(userroom_id);
} }
for user in highlights { for user in highlights {
let mut userroom_id = user.as_bytes().to_vec(); let mut userroom_id = user.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
highlights_batch.push(userroom_id); highlights_batch.push(userroom_id);
} }
self.userroomid_notificationcount.increment_batch(&mut notifies_batch.into_iter())?; self.userroomid_notificationcount
self.userroomid_highlightcount.increment_batch(&mut highlights_batch.into_iter())?; .increment_batch(&mut notifies_batch.into_iter())?;
self.userroomid_highlightcount
.increment_batch(&mut highlights_batch.into_iter())?;
Ok(())
}
fn delete_all_pdus_for_room(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff);
for (key, _) in self.pduid_pdu.scan_prefix(prefix) {
debug!("Removing key: {:?}", key);
self.pduid_pdu.remove(&key)?;
}
Ok(()) Ok(())
} }
} }
@@ -238,8 +321,9 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
fn pdu_count(pdu_id: &[u8]) -> Result<PduCount> { fn pdu_count(pdu_id: &[u8]) -> Result<PduCount> {
let last_u64 = utils::u64_from_bytes(&pdu_id[pdu_id.len() - size_of::<u64>()..]) let last_u64 = utils::u64_from_bytes(&pdu_id[pdu_id.len() - size_of::<u64>()..])
.map_err(|_| Error::bad_database("PDU has invalid count bytes."))?; .map_err(|_| Error::bad_database("PDU has invalid count bytes."))?;
let second_last_u64 = let second_last_u64 = utils::u64_from_bytes(
utils::u64_from_bytes(&pdu_id[pdu_id.len() - 2 * size_of::<u64>()..pdu_id.len() - size_of::<u64>()]); &pdu_id[pdu_id.len() - 2 * size_of::<u64>()..pdu_id.len() - size_of::<u64>()],
);
if matches!(second_last_u64, Ok(0)) { if matches!(second_last_u64, Ok(0)) {
Ok(PduCount::Backfilled(u64::MAX - last_u64)) Ok(PduCount::Backfilled(u64::MAX - last_u64))
@@ -248,12 +332,17 @@ fn pdu_count(pdu_id: &[u8]) -> Result<PduCount> {
} }
} }
fn count_to_id(room_id: &RoomId, count: PduCount, offset: u64, subtract: bool) -> Result<(Vec<u8>, Vec<u8>)> { fn count_to_id(
room_id: &RoomId,
count: PduCount,
offset: u64,
subtract: bool,
) -> Result<(Vec<u8>, Vec<u8>)> {
let prefix = services() let prefix = services()
.rooms .rooms
.short .short
.get_shortroomid(room_id)? .get_shortroomid(room_id)?
.ok_or_else(|| Error::bad_database("Looked for bad shortroomid in timeline"))? .expect("room exists")
.to_be_bytes() .to_be_bytes()
.to_vec(); .to_vec();
let mut pdu_id = prefix.clone(); let mut pdu_id = prefix.clone();
@@ -265,7 +354,7 @@ fn count_to_id(room_id: &RoomId, count: PduCount, offset: u64, subtract: bool) -
} else { } else {
x + offset x + offset
} }
}, }
PduCount::Backfilled(x) => { PduCount::Backfilled(x) => {
pdu_id.extend_from_slice(&0_u64.to_be_bytes()); pdu_id.extend_from_slice(&0_u64.to_be_bytes());
let num = u64::MAX - x; let num = u64::MAX - x;
@@ -278,7 +367,7 @@ fn count_to_id(room_id: &RoomId, count: PduCount, offset: u64, subtract: bool) -
} else { } else {
num + offset num + offset
} }
}, }
}; };
pdu_id.extend_from_slice(&count_raw.to_be_bytes()); pdu_id.extend_from_slice(&count_raw.to_be_bytes());
+55 -30
View File
@@ -5,73 +5,95 @@ use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}
impl service::rooms::user::Data for KeyValueDatabase { impl service::rooms::user::Data for KeyValueDatabase {
fn reset_notification_counts(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> { fn reset_notification_counts(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
let mut roomuser_id = room_id.as_bytes().to_vec(); let mut roomuser_id = room_id.as_bytes().to_vec();
roomuser_id.push(0xFF); roomuser_id.push(0xff);
roomuser_id.extend_from_slice(user_id.as_bytes()); roomuser_id.extend_from_slice(user_id.as_bytes());
self.userroomid_notificationcount.insert(&userroom_id, &0_u64.to_be_bytes())?; self.userroomid_notificationcount
self.userroomid_highlightcount.insert(&userroom_id, &0_u64.to_be_bytes())?; .insert(&userroom_id, &0_u64.to_be_bytes())?;
self.userroomid_highlightcount
.insert(&userroom_id, &0_u64.to_be_bytes())?;
self.roomuserid_lastnotificationread.insert(&roomuser_id, &services().globals.next_count()?.to_be_bytes())?; self.roomuserid_lastnotificationread.insert(
&roomuser_id,
&services().globals.next_count()?.to_be_bytes(),
)?;
Ok(()) Ok(())
} }
fn notification_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> { fn notification_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
self.userroomid_notificationcount self.userroomid_notificationcount
.get(&userroom_id)? .get(&userroom_id)?
.map(|bytes| { .map(|bytes| {
utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid notification count in db.")) utils::u64_from_bytes(&bytes)
.map_err(|_| Error::bad_database("Invalid notification count in db."))
}) })
.unwrap_or(Ok(0)) .unwrap_or(Ok(0))
} }
fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> { fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
let mut userroom_id = user_id.as_bytes().to_vec(); let mut userroom_id = user_id.as_bytes().to_vec();
userroom_id.push(0xFF); userroom_id.push(0xff);
userroom_id.extend_from_slice(room_id.as_bytes()); userroom_id.extend_from_slice(room_id.as_bytes());
self.userroomid_highlightcount self.userroomid_highlightcount
.get(&userroom_id)? .get(&userroom_id)?
.map(|bytes| { .map(|bytes| {
utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid highlight count in db.")) utils::u64_from_bytes(&bytes)
.map_err(|_| Error::bad_database("Invalid highlight count in db."))
}) })
.unwrap_or(Ok(0)) .unwrap_or(Ok(0))
} }
fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> { fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
let mut key = room_id.as_bytes().to_vec(); let mut key = room_id.as_bytes().to_vec();
key.push(0xFF); key.push(0xff);
key.extend_from_slice(user_id.as_bytes()); key.extend_from_slice(user_id.as_bytes());
Ok(self Ok(self
.roomuserid_lastnotificationread .roomuserid_lastnotificationread
.get(&key)? .get(&key)?
.map(|bytes| { .map(|bytes| {
utils::u64_from_bytes(&bytes) utils::u64_from_bytes(&bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Count in roomuserid_lastprivatereadupdate is invalid.")) Error::bad_database("Count in roomuserid_lastprivatereadupdate is invalid.")
})
}) })
.transpose()? .transpose()?
.unwrap_or(0)) .unwrap_or(0))
} }
fn associate_token_shortstatehash(&self, room_id: &RoomId, token: u64, shortstatehash: u64) -> Result<()> { fn associate_token_shortstatehash(
let shortroomid = services().rooms.short.get_shortroomid(room_id)?.expect("room exists"); &self,
room_id: &RoomId,
token: u64,
shortstatehash: u64,
) -> Result<()> {
let shortroomid = services()
.rooms
.short
.get_shortroomid(room_id)?
.expect("room exists");
let mut key = shortroomid.to_be_bytes().to_vec(); let mut key = shortroomid.to_be_bytes().to_vec();
key.extend_from_slice(&token.to_be_bytes()); key.extend_from_slice(&token.to_be_bytes());
self.roomsynctoken_shortstatehash.insert(&key, &shortstatehash.to_be_bytes()) self.roomsynctoken_shortstatehash
.insert(&key, &shortstatehash.to_be_bytes())
} }
fn get_token_shortstatehash(&self, room_id: &RoomId, token: u64) -> Result<Option<u64>> { fn get_token_shortstatehash(&self, room_id: &RoomId, token: u64) -> Result<Option<u64>> {
let shortroomid = services().rooms.short.get_shortroomid(room_id)?.expect("room exists"); let shortroomid = services()
.rooms
.short
.get_shortroomid(room_id)?
.expect("room exists");
let mut key = shortroomid.to_be_bytes().to_vec(); let mut key = shortroomid.to_be_bytes().to_vec();
key.extend_from_slice(&token.to_be_bytes()); key.extend_from_slice(&token.to_be_bytes());
@@ -79,18 +101,20 @@ impl service::rooms::user::Data for KeyValueDatabase {
self.roomsynctoken_shortstatehash self.roomsynctoken_shortstatehash
.get(&key)? .get(&key)?
.map(|bytes| { .map(|bytes| {
utils::u64_from_bytes(&bytes) utils::u64_from_bytes(&bytes).map_err(|_| {
.map_err(|_| Error::bad_database("Invalid shortstatehash in roomsynctoken_shortstatehash")) Error::bad_database("Invalid shortstatehash in roomsynctoken_shortstatehash")
})
}) })
.transpose() .transpose()
} }
fn get_shared_rooms<'a>( fn get_shared_rooms<'a>(
&'a self, users: Vec<OwnedUserId>, &'a self,
users: Vec<OwnedUserId>,
) -> Result<Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a>> { ) -> Result<Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a>> {
let iterators = users.into_iter().map(move |user_id| { let iterators = users.into_iter().map(move |user_id| {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xFF); prefix.push(0xff);
self.userroomid_joined self.userroomid_joined
.scan_prefix(prefix) .scan_prefix(prefix)
@@ -98,25 +122,26 @@ impl service::rooms::user::Data for KeyValueDatabase {
let roomid_index = key let roomid_index = key
.iter() .iter()
.enumerate() .enumerate()
.find(|(_, &b)| b == 0xFF) .find(|(_, &b)| b == 0xff)
.ok_or_else(|| Error::bad_database("Invalid userroomid_joined in db."))? .ok_or_else(|| Error::bad_database("Invalid userroomid_joined in db."))?
.0 + 1; // +1 because the room id starts AFTER the separator .0
+ 1; // +1 because the room id starts AFTER the separator
let room_id = key[roomid_index..].to_vec(); let room_id = key[roomid_index..].to_vec();
Ok::<_, Error>(room_id) Ok::<_, Error>(room_id)
}) })
.filter_map(std::result::Result::ok) .filter_map(|r| r.ok())
}); });
// We use the default compare function because keys are sorted correctly (not // We use the default compare function because keys are sorted correctly (not reversed)
// reversed)
Ok(Box::new( Ok(Box::new(
utils::common_elements(iterators, Ord::cmp).expect("users is not empty").map(|bytes| { utils::common_elements(iterators, Ord::cmp)
RoomId::parse( .expect("users is not empty")
utils::string_from_bytes(&bytes) .map(|bytes| {
.map_err(|_| Error::bad_database("Invalid RoomId bytes in userroomid_joined"))?, RoomId::parse(utils::string_from_bytes(&bytes).map_err(|_| {
) Error::bad_database("Invalid RoomId bytes in userroomid_joined")
})?)
.map_err(|_| Error::bad_database("Invalid RoomId in userroomid_joined.")) .map_err(|_| Error::bad_database("Invalid RoomId in userroomid_joined."))
}), }),
)) ))
+52 -32
View File
@@ -21,7 +21,8 @@ impl service::sending::Data for KeyValueDatabase {
} }
fn active_requests_for<'a>( fn active_requests_for<'a>(
&'a self, outgoing_kind: &OutgoingKind, &'a self,
outgoing_kind: &OutgoingKind,
) -> Box<dyn Iterator<Item = Result<(Vec<u8>, SendingEventType)>> + 'a> { ) -> Box<dyn Iterator<Item = Result<(Vec<u8>, SendingEventType)>> + 'a> {
let prefix = outgoing_kind.get_prefix(); let prefix = outgoing_kind.get_prefix();
Box::new( Box::new(
@@ -31,7 +32,9 @@ impl service::sending::Data for KeyValueDatabase {
) )
} }
fn delete_active_request(&self, key: Vec<u8>) -> Result<()> { self.servercurrentevent_data.remove(&key) } fn delete_active_request(&self, key: Vec<u8>) -> Result<()> {
self.servercurrentevent_data.remove(&key)
}
fn delete_all_active_requests_for(&self, outgoing_kind: &OutgoingKind) -> Result<()> { fn delete_all_active_requests_for(&self, outgoing_kind: &OutgoingKind) -> Result<()> {
let prefix = outgoing_kind.get_prefix(); let prefix = outgoing_kind.get_prefix();
@@ -55,15 +58,18 @@ impl service::sending::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
fn queue_requests(&self, requests: &[(&OutgoingKind, SendingEventType)]) -> Result<Vec<Vec<u8>>> { fn queue_requests(
&self,
requests: &[(&OutgoingKind, SendingEventType)],
) -> Result<Vec<Vec<u8>>> {
let mut batch = Vec::new(); let mut batch = Vec::new();
let mut keys = Vec::new(); let mut keys = Vec::new();
for (outgoing_kind, event) in requests { for (outgoing_kind, event) in requests {
let mut key = outgoing_kind.get_prefix(); let mut key = outgoing_kind.get_prefix();
if let SendingEventType::Pdu(value) = &event { if let SendingEventType::Pdu(value) = &event {
key.extend_from_slice(value); key.extend_from_slice(value)
} else { } else {
key.extend_from_slice(&services().globals.next_count()?.to_be_bytes()); key.extend_from_slice(&services().globals.next_count()?.to_be_bytes())
} }
let value = if let SendingEventType::Edu(value) = &event { let value = if let SendingEventType::Edu(value) = &event {
&**value &**value
@@ -73,12 +79,14 @@ impl service::sending::Data for KeyValueDatabase {
batch.push((key.clone(), value.to_owned())); batch.push((key.clone(), value.to_owned()));
keys.push(key); keys.push(key);
} }
self.servernameevent_data.insert_batch(&mut batch.into_iter())?; self.servernameevent_data
.insert_batch(&mut batch.into_iter())?;
Ok(keys) Ok(keys)
} }
fn queued_requests<'a>( fn queued_requests<'a>(
&'a self, outgoing_kind: &OutgoingKind, &'a self,
outgoing_kind: &OutgoingKind,
) -> Box<dyn Iterator<Item = Result<(SendingEventType, Vec<u8>)>> + 'a> { ) -> Box<dyn Iterator<Item = Result<(SendingEventType, Vec<u8>)>> + 'a> {
let prefix = outgoing_kind.get_prefix(); let prefix = outgoing_kind.get_prefix();
return Box::new( return Box::new(
@@ -90,10 +98,6 @@ impl service::sending::Data for KeyValueDatabase {
fn mark_as_active(&self, events: &[(SendingEventType, Vec<u8>)]) -> Result<()> { fn mark_as_active(&self, events: &[(SendingEventType, Vec<u8>)]) -> Result<()> {
for (e, key) in events { for (e, key) in events {
if key.is_empty() {
continue;
}
let value = if let SendingEventType::Edu(value) = &e { let value = if let SendingEventType::Edu(value) = &e {
&**value &**value
} else { } else {
@@ -107,27 +111,37 @@ impl service::sending::Data for KeyValueDatabase {
} }
fn set_latest_educount(&self, server_name: &ServerName, last_count: u64) -> Result<()> { fn set_latest_educount(&self, server_name: &ServerName, last_count: u64) -> Result<()> {
self.servername_educount.insert(server_name.as_bytes(), &last_count.to_be_bytes()) self.servername_educount
.insert(server_name.as_bytes(), &last_count.to_be_bytes())
} }
fn get_latest_educount(&self, server_name: &ServerName) -> Result<u64> { fn get_latest_educount(&self, server_name: &ServerName) -> Result<u64> {
self.servername_educount.get(server_name.as_bytes())?.map_or(Ok(0), |bytes| { self.servername_educount
utils::u64_from_bytes(&bytes).map_err(|_| Error::bad_database("Invalid u64 in servername_educount.")) .get(server_name.as_bytes())?
.map_or(Ok(0), |bytes| {
utils::u64_from_bytes(&bytes)
.map_err(|_| Error::bad_database("Invalid u64 in servername_educount."))
}) })
} }
} }
#[tracing::instrument(skip(key))] #[tracing::instrument(skip(key))]
fn parse_servercurrentevent(key: &[u8], value: Vec<u8>) -> Result<(OutgoingKind, SendingEventType)> { fn parse_servercurrentevent(
key: &[u8],
value: Vec<u8>,
) -> Result<(OutgoingKind, SendingEventType)> {
// Appservices start with a plus // Appservices start with a plus
Ok::<_, Error>(if key.starts_with(b"+") { Ok::<_, Error>(if key.starts_with(b"+") {
let mut parts = key[1..].splitn(2, |&b| b == 0xFF); let mut parts = key[1..].splitn(2, |&b| b == 0xff);
let server = parts.next().expect("splitn always returns one element"); let server = parts.next().expect("splitn always returns one element");
let event = parts.next().ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?; let event = parts
.next()
.ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?;
let server = utils::string_from_bytes(server) let server = utils::string_from_bytes(server).map_err(|_| {
.map_err(|_| Error::bad_database("Invalid server bytes in server_currenttransaction"))?; Error::bad_database("Invalid server bytes in server_currenttransaction")
})?;
( (
OutgoingKind::Appservice(server), OutgoingKind::Appservice(server),
@@ -138,19 +152,23 @@ fn parse_servercurrentevent(key: &[u8], value: Vec<u8>) -> Result<(OutgoingKind,
}, },
) )
} else if key.starts_with(b"$") { } else if key.starts_with(b"$") {
let mut parts = key[1..].splitn(3, |&b| b == 0xFF); let mut parts = key[1..].splitn(3, |&b| b == 0xff);
let user = parts.next().expect("splitn always returns one element"); let user = parts.next().expect("splitn always returns one element");
let user_string = utils::string_from_bytes(user) let user_string = utils::string_from_bytes(user)
.map_err(|_| Error::bad_database("Invalid user string in servercurrentevent"))?; .map_err(|_| Error::bad_database("Invalid user string in servercurrentevent"))?;
let user_id = let user_id = UserId::parse(user_string)
UserId::parse(user_string).map_err(|_| Error::bad_database("Invalid user id in servercurrentevent"))?; .map_err(|_| Error::bad_database("Invalid user id in servercurrentevent"))?;
let pushkey = parts.next().ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?; let pushkey = parts
.next()
.ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?;
let pushkey_string = utils::string_from_bytes(pushkey) let pushkey_string = utils::string_from_bytes(pushkey)
.map_err(|_| Error::bad_database("Invalid pushkey in servercurrentevent"))?; .map_err(|_| Error::bad_database("Invalid pushkey in servercurrentevent"))?;
let event = parts.next().ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?; let event = parts
.next()
.ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?;
( (
OutgoingKind::Push(user_id, pushkey_string), OutgoingKind::Push(user_id, pushkey_string),
@@ -162,19 +180,21 @@ fn parse_servercurrentevent(key: &[u8], value: Vec<u8>) -> Result<(OutgoingKind,
}, },
) )
} else { } else {
let mut parts = key.splitn(2, |&b| b == 0xFF); let mut parts = key.splitn(2, |&b| b == 0xff);
let server = parts.next().expect("splitn always returns one element"); let server = parts.next().expect("splitn always returns one element");
let event = parts.next().ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?; let event = parts
.next()
.ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?;
let server = utils::string_from_bytes(server) let server = utils::string_from_bytes(server).map_err(|_| {
.map_err(|_| Error::bad_database("Invalid server bytes in server_currenttransaction"))?; Error::bad_database("Invalid server bytes in server_currenttransaction")
})?;
( (
OutgoingKind::Normal( OutgoingKind::Normal(ServerName::parse(server).map_err(|_| {
ServerName::parse(server) Error::bad_database("Invalid server string in server_currenttransaction")
.map_err(|_| Error::bad_database("Invalid server string in server_currenttransaction"))?, })?),
),
if value.is_empty() { if value.is_empty() {
SendingEventType::Pdu(event.to_vec()) SendingEventType::Pdu(event.to_vec())
} else { } else {

Some files were not shown because too many files have changed in this diff Show More