Compare commits

..
Author SHA1 Message Date
Jonas Zohren 84d54e0eaf Also calculate sum of cache sizes
Signed-off-by: Jonas Zohren <git-pbkyr@jzohren.de>
2021-08-25 00:51:46 +02:00
Jonas Zohren 927a23814b Add test to measure memory usage of caches
Signed-off-by: Jonas Zohren <git-pbkyr@jzohren.de>
2021-08-25 00:43:01 +02:00
57 changed files with 1108 additions and 2478 deletions
+1 -6
View File
@@ -19,7 +19,6 @@ variables:
needs: [] needs: []
rules: rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
- if: '$CI_COMMIT_TAG'
interruptible: true interruptible: true
image: "rust:latest" image: "rust:latest"
tags: ["docker"] tags: ["docker"]
@@ -107,7 +106,6 @@ build:release:cargo:x86_64-unknown-linux-musl:
extends: ".build-cargo-shared-settings" extends: ".build-cargo-shared-settings"
rules: rules:
- if: '$CI_COMMIT_BRANCH' - if: '$CI_COMMIT_BRANCH'
- if: '$CI_COMMIT_TAG'
cache: cache:
key: "build_cache-$TARGET-debug" key: "build_cache-$TARGET-debug"
script: script:
@@ -153,7 +151,6 @@ build:debug:cargo:x86_64-unknown-linux-musl:
needs: [ ] needs: [ ]
rules: rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
- if: '$CI_COMMIT_TAG'
interruptible: true interruptible: true
image: "rust:latest" image: "rust:latest"
tags: ["docker"] tags: ["docker"]
@@ -220,7 +217,7 @@ build:docker:main:
--context $CI_PROJECT_DIR --context $CI_PROJECT_DIR
--build-arg CREATED=$(date -u +'%Y-%m-%dT%H:%M:%SZ') --build-arg CREATED=$(date -u +'%Y-%m-%dT%H:%M:%SZ')
--build-arg VERSION=$(grep -m1 -o '[0-9].[0-9].[0-9]' Cargo.toml) --build-arg VERSION=$(grep -m1 -o '[0-9].[0-9].[0-9]' Cargo.toml)
--build-arg "GIT_REF=$CI_COMMIT_SHORT_SHA" --build-arg "GIT_REF=$CI_COMMIT_REF_NAME"
--dockerfile "$CI_PROJECT_DIR/docker/ci-binaries-packaging.Dockerfile" --dockerfile "$CI_PROJECT_DIR/docker/ci-binaries-packaging.Dockerfile"
--destination "$CI_REGISTRY_IMAGE/conduit:latest" --destination "$CI_REGISTRY_IMAGE/conduit:latest"
--destination "$CI_REGISTRY_IMAGE/conduit:alpine" --destination "$CI_REGISTRY_IMAGE/conduit:alpine"
@@ -230,7 +227,6 @@ build:docker:main:
--destination "$DOCKER_HUB_IMAGE/matrixconduit/matrix-conduit:commit-$CI_COMMIT_SHORT_SHA" --destination "$DOCKER_HUB_IMAGE/matrixconduit/matrix-conduit:commit-$CI_COMMIT_SHORT_SHA"
rules: rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
- if: '$CI_COMMIT_TAG'
@@ -332,7 +328,6 @@ publish:package:
- "build:cargo-deb:x86_64-unknown-linux-gnu" - "build:cargo-deb:x86_64-unknown-linux-gnu"
rules: rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
- if: '$CI_COMMIT_TAG'
image: curlimages/curl:latest image: curlimages/curl:latest
tags: ["docker"] tags: ["docker"]
variables: variables:
Generated
+237 -180
View File
File diff suppressed because it is too large Load Diff
+12 -14
View File
@@ -6,7 +6,7 @@ authors = ["timokoesters <timo@koesters.xyz>"]
homepage = "https://conduit.rs" homepage = "https://conduit.rs"
repository = "https://gitlab.com/famedly/conduit" repository = "https://gitlab.com/famedly/conduit"
readme = "README.md" readme = "README.md"
version = "0.2.0" version = "0.1.0"
edition = "2018" edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -18,29 +18,28 @@ edition = "2018"
rocket = { version = "0.5.0-rc.1", features = ["tls"] } # Used to handle requests rocket = { version = "0.5.0-rc.1", features = ["tls"] } # Used to handle requests
# 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 = { git = "https://github.com/ruma/ruma", rev = "f5ab038e22421ed338396ece977b6b2844772ced", 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 = "f5ab038e22421ed338396ece977b6b2844772ced", 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/timokoesters/ruma", rev = "50c1db7e0a3a21fc794b0cce3b64285a4c750c71", 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/timokoesters/ruma", rev = "2215049b60a1c3358f5a52215adf1e7bb88619a1", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] } #ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
# Used for long polling and federation sender, should be the same as rocket::tokio # Used for long polling and federation sender, should be the same as rocket::tokio
tokio = "1.11.0" tokio = "1.8.2"
# Used for storing data permanently # Used for storing data permanently
sled = { version = "0.34.6", features = ["compression", "no_metrics"], optional = true } sled = { version = "0.34.6", features = ["compression", "no_metrics"], optional = true }
#sled = { git = "https://github.com/spacejam/sled.git", rev = "e4640e0773595229f398438886f19bca6f7326a2", features = ["compression"] } #sled = { git = "https://github.com/spacejam/sled.git", rev = "e4640e0773595229f398438886f19bca6f7326a2", features = ["compression"] }
# Used for the http request / response body type for Ruma endpoints used with reqwest # Used for the http request / response body type for Ruma endpoints used with reqwest
bytes = "1.1.0" bytes = "1.0.1"
# Used for rocket<->ruma conversions # Used for rocket<->ruma conversions
http = "0.2.4" http = "0.2.4"
# Used to find data directory for default db path # Used to find data directory for default db path
directories = "3.0.2" directories = "3.0.2"
# Used for ruma wrapper # Used for ruma wrapper
serde_json = { version = "1.0.67", features = ["raw_value"] } serde_json = { version = "1.0.64", features = ["raw_value"] }
# Used for appservice registration files # Used for appservice registration files
serde_yaml = "0.8.20" serde_yaml = "0.8.17"
# Used for pdu definition # Used for pdu definition
serde = "1.0.130" serde = "1.0.126"
# Used for secure identifiers # Used for secure identifiers
rand = "0.8.4" rand = "0.8.4"
# Used to hash passwords # Used to hash passwords
@@ -50,9 +49,9 @@ reqwest = { version = "0.11.4", default-features = false, features = ["rustls-tl
# Custom TLS verifier # Custom TLS verifier
rustls = { version = "0.19.1", features = ["dangerous_configuration"] } rustls = { version = "0.19.1", features = ["dangerous_configuration"] }
rustls-native-certs = "0.5.0" rustls-native-certs = "0.5.0"
webpki = "0.22.0" webpki = "0.21.0"
# Used for conduit::Error type # Used for conduit::Error type
thiserror = "1.0.28" thiserror = "1.0.26"
# Used to generate thumbnails for images # Used to generate thumbnails for images
image = { version = "0.23.14", default-features = false, features = ["jpeg", "png", "gif"] } image = { version = "0.23.14", default-features = false, features = ["jpeg", "png", "gif"] }
# Used to encode server public key # Used to encode server public key
@@ -67,20 +66,19 @@ regex = "1.5.4"
jsonwebtoken = "7.2.0" jsonwebtoken = "7.2.0"
# Performance measurements # Performance measurements
tracing = { version = "0.1.26", features = ["release_max_level_warn"] } tracing = { version = "0.1.26", features = ["release_max_level_warn"] }
tracing-subscriber = "0.2.20" tracing-subscriber = "0.2.19"
tracing-opentelemetry = "0.15.0" tracing-opentelemetry = "0.14.0"
tracing-flame = "0.1.0" tracing-flame = "0.1.0"
opentelemetry = { version = "0.16.0", features = ["rt-tokio"] } opentelemetry = { version = "0.16.0", features = ["rt-tokio"] }
opentelemetry-jaeger = { version = "0.15.0", features = ["rt-tokio"] } opentelemetry-jaeger = { version = "0.15.0", features = ["rt-tokio"] }
pretty_env_logger = "0.4.0" pretty_env_logger = "0.4.0"
lru-cache = "0.1.2" lru-cache = "0.1.2"
rusqlite = { version = "0.25.3", optional = true, features = ["bundled"] } rusqlite = { version = "0.25.3", optional = true, features = ["bundled"] }
parking_lot = { version = "0.11.2", optional = true } parking_lot = { version = "0.11.1", optional = true }
crossbeam = { version = "0.8.1", optional = true } crossbeam = { version = "0.8.1", optional = true }
num_cpus = "1.13.0" num_cpus = "1.13.0"
threadpool = "1.8.1" threadpool = "1.8.1"
heed = { git = "https://github.com/timokoesters/heed.git", rev = "f6f825da7fb2c758867e05ad973ef800a6fe1d5d", optional = true } heed = { git = "https://github.com/timokoesters/heed.git", rev = "f6f825da7fb2c758867e05ad973ef800a6fe1d5d", optional = true }
thread_local = "1.1.3"
[features] [features]
default = ["conduit_bin", "backend_sqlite"] default = ["conduit_bin", "backend_sqlite"]
+7 -18
View File
@@ -44,7 +44,7 @@ This also allows you to make sure that the file permissions are correctly set up
In Debian you can use this command to create a Conduit user: In Debian you can use this command to create a Conduit user:
```bash ```
sudo adduser --system conduit --no-create-home sudo adduser --system conduit --no-create-home
``` ```
@@ -107,8 +107,8 @@ port = 6167
# Max size for uploads # Max size for uploads
max_request_size = 20_000_000 # in bytes max_request_size = 20_000_000 # in bytes
# Enables registration. If set to false, no users can register on this server. # Disabling registration means no new users will be able to register on this server
allow_registration = true allow_registration = false
# Disable encryption, so no new encrypted rooms can be created # Disable encryption, so no new encrypted rooms can be created
# Note: existing rooms will continue to work # Note: existing rooms will continue to work
@@ -131,13 +131,13 @@ address = "127.0.0.1" # This makes sure Conduit can only be reached using the re
As we are using a Conduit specific user we need to allow it to read the config. As we are using a Conduit specific user we need to allow it to read the config.
To do that you can run this command on Debian: To do that you can run this command on Debian:
```bash ```
sudo chown -R conduit:nogroup /etc/matrix-conduit sudo chown -R conduit:nogroup /etc/matrix-conduit
``` ```
If you use the default database path you also need to run this: If you use the default database path you also need to run this:
```bash ```
sudo mkdir -p /var/lib/matrix-conduit/conduit_db sudo mkdir -p /var/lib/matrix-conduit/conduit_db
sudo chown -R conduit:nogroup /var/lib/matrix-conduit/conduit_db sudo chown -R conduit:nogroup /var/lib/matrix-conduit/conduit_db
``` ```
@@ -151,7 +151,7 @@ This depends on whether you use Apache, Nginx or another web server.
Create `/etc/apache2/sites-enabled/050-conduit.conf` and copy-and-paste this: Create `/etc/apache2/sites-enabled/050-conduit.conf` and copy-and-paste this:
```apache ```
Listen 8448 Listen 8448
<VirtualHost *:443 *:8448> <VirtualHost *:443 *:8448>
@@ -180,7 +180,7 @@ $ sudo systemctl reload apache2
If you use Nginx and not Apache, add the following server section inside the If you use Nginx and not Apache, add the following server section inside the
http section of `/etc/nginx/nginx.conf` http section of `/etc/nginx/nginx.conf`
```nginx ```
server { server {
listen 443 ssl http2; listen 443 ssl http2;
listen [::]:443 ssl http2; listen [::]:443 ssl http2;
@@ -231,15 +231,4 @@ Set it to start automatically when your system boots with:
$ sudo systemctl enable conduit $ sudo systemctl enable conduit
``` ```
## How do I know it works?
You can open <https://app.element.io>, enter your homeserver and try to register.
You can also use these commands as a quick health check.
```bash
$ curl https://your.server.name/_matrix/client/versions
$ curl https://your.server.name:8448/_matrix/client/versions
```
If you want to set up an appservice, take a look at the [Appservice Guide](APPSERVICES.md). If you want to set up an appservice, take a look at the [Appservice Guide](APPSERVICES.md).
+11 -13
View File
@@ -7,29 +7,25 @@
# Alpine build image to build Conduit's statically compiled binary # Alpine build image to build Conduit's statically compiled binary
FROM alpine:3.14 as builder FROM alpine:3.14 as builder
# Install packages needed for building all crates
RUN apk add --no-cache \
cargo \
openssl-dev
# Specifies if the local project is build or if Conduit gets build # Specifies if the local project is build or if Conduit gets build
# from the official git repository. Defaults to the git repo. # from the official git repository. Defaults to the git repo.
ARG LOCAL=false ARG LOCAL=false
# Specifies which revision/commit is build. Defaults to HEAD # Specifies which revision/commit is build. Defaults to HEAD
ARG GIT_REF=origin/master ARG GIT_REF=origin/master
# Install packages needed for building all crates
RUN apk add --no-cache \
cargo \
openssl-dev
# Copy project files from current folder # Copy project files from current folder
COPY . . COPY . .
# Build it from the copied local files or from the official git repository # Build it from the copied local files or from the official git repository
RUN if [[ $LOCAL == "true" ]]; then \ RUN if [[ $LOCAL == "true" ]]; then \
mv ./docker/healthcheck.sh . ; \
echo "Building from local source..." ; \
cargo install --path . ; \ cargo install --path . ; \
else \ else \
echo "Building revision '${GIT_REF}' from online source..." ; \ cargo install --git "https://gitlab.com/famedly/conduit.git" --rev ${GIT_REF}; \
cargo install --git "https://gitlab.com/famedly/conduit.git" --rev ${GIT_REF} ; \
echo "Loadings healthcheck script from online source..." ; \
wget "https://gitlab.com/famedly/conduit/-/raw/${GIT_REF#origin/}/docker/healthcheck.sh" ; \
fi fi
########################## RUNTIME IMAGE ########################## ########################## RUNTIME IMAGE ##########################
@@ -68,7 +64,6 @@ EXPOSE 6167
# /srv/conduit and create data folder for database # /srv/conduit and create data folder for database
RUN mkdir -p /srv/conduit/.local/share/conduit RUN mkdir -p /srv/conduit/.local/share/conduit
COPY --from=builder /root/.cargo/bin/conduit /srv/conduit/ COPY --from=builder /root/.cargo/bin/conduit /srv/conduit/
COPY --from=builder ./healthcheck.sh /srv/conduit/
# Add www-data user and group with UID 82, as used by alpine # Add www-data user and group with UID 82, as used by alpine
# https://git.alpinelinux.org/aports/tree/main/nginx/nginx.pre-install # https://git.alpinelinux.org/aports/tree/main/nginx/nginx.pre-install
@@ -87,7 +82,10 @@ RUN apk add --no-cache \
libgcc libgcc
# Test if Conduit is still alive, uses the same endpoint as Element # Test if Conduit is still alive, uses the same endpoint as Element
HEALTHCHECK --start-period=5s --interval=60s CMD ./healthcheck.sh HEALTHCHECK --start-period=5s \
CMD curl --fail -s "http://localhost:$(grep -m1 -o 'port\s=\s[0-9]*' conduit.toml | grep -m1 -o '[0-9]*')/_matrix/client/versions" || \
curl -k --fail -s "https://localhost:$(grep -m1 -o 'port\s=\s[0-9]*' conduit.toml | grep -m1 -o '[0-9]*')/_matrix/client/versions" || \
exit 1
# Set user to www-data # Set user to www-data
USER www-data USER www-data
+63 -26
View File
@@ -3,42 +3,90 @@
#### What is the goal? #### What is the goal?
An efficient Matrix homeserver that's easy to set up and just works. You can install A fast Matrix homeserver that's easy to set up and just works. You can install
it on a mini-computer like the Raspberry Pi to host Matrix for your family, it on a mini-computer like the Raspberry Pi to host Matrix for your family,
friends or company. friends or company.
#### Can I try it out? #### Can I try it out?
Yes! You can test our Conduit instance by opening a Matrix client (<https://app.element.io> or Element Android for Yes! Just open a Matrix client (<https://app.element.io> or Element Android for
example) and registering on the `conduit.rs` homeserver. example) and register on the `https://conduit.koesters.xyz` homeserver.
It is hosted on a ODROID HC 2 with 2GB RAM and a SAMSUNG Exynos 5422 CPU, which
was used in the Samsung Galaxy S5. It joined many big rooms including Matrix #### What is it built on?
HQ.
- [Ruma](https://www.ruma.io): Useful structures for endpoint requests and
responses that can be (de)serialized
- [Sled](https://github.com/spacejam/sled): A simple (key, value) database with
good performance
- [Rocket](https://rocket.rs): A flexible web framework
#### What is the current status? #### What is the current status?
As of 2021-09-01, Conduit is Beta, meaning you can join and participate in most Conduit can already be used chat with other users on Conduit, chat with users
Matrix rooms, but not all features are supported and you might run into bugs from other Matrix servers and even to chat with users on other platforms using
from time to time. appservices. When chatting with users on the same Conduit server, everything
should work assuming you use a compatible client.
**You should not join Matrix rooms without asking the admins first.** We do not
know whether Conduit is safe for general use yet, so you should assume there is
some chance that it breaks rooms permanently for all participating users. We
are not aware of such a bug today, but we would like to do more testing.
There are still a few important features missing: There are still a few important features missing:
- E2EE verification over federation - Database stability (currently you might have to do manual upgrades or even wipe the db for new versions)
- Outgoing read receipts, typing, presence over federation - Edge cases for end-to-end encryption over federation
- Typing and presence over federation
- Lots of testing
Check out the [Conduit 1.0 Release Milestone](https://gitlab.com/famedly/conduit/-/milestones/3). Check out the [Conduit 1.0 Release Milestone](https://gitlab.com/famedly/conduit/-/milestones/3).
#### How can I deploy my own? #### How can I deploy my own?
Simple install (this was tested the most): [DEPLOY.md](DEPLOY.md)\ ##### Deploy
Debian package: [debian/README.Debian](debian/README.Debian)\
Docker: [docker/README.md](docker/README.md)
If you want to connect an Appservice to Conduit, take a look at [APPSERVICES.md](APPSERVICES.md). Download or compile a Conduit binary, set up the config and call it from somewhere like a systemd script. [Read
more](DEPLOY.md)
If you want to connect an Appservice to Conduit, take a look at the [Appservice Guide](APPSERVICES.md).
##### Deploy using a Debian package
You need to have the `deb` helper command installed that creates Debian packages from Cargo projects (see [cargo-deb](https://github.com/mmstick/cargo-deb/) for more info):
```shell
$ cargo install cargo-deb
```
Then, you can create and install a Debian package at a whim:
```shell
$ cargo deb
$ dpkg -i target/debian/matrix-conduit_0.1.0_amd64.deb
```
This will build, package, install, configure and start Conduit. [Read more](debian/README.Debian).
Note that `cargo deb` supports [cross-compilation](https://github.com/mmstick/cargo-deb/#cross-compilation) too!
Official Debian packages will follow once Conduit starts to have stable releases.
##### Deploy using Docker
Pull and run the docker image with
``` bash
docker pull matrixconduit/matrix-conduit:latest
docker run -d -p 8448:8000 -v ~/conduit.toml:/srv/conduit/conduit.toml -v db:/srv/conduit/.local/share/conduit matrixconduit/matrix-conduit:latest
```
> <b>Note:</b> You also need to supply a `conduit.toml` config file, you can find an example [here](./conduit-example.toml).
> Or you can pass in `-e CONDUIT_CONFIG=""` and configure Conduit purely with env vars.
Or build and run it with docker or docker-compose. [Read more](docker/README.md)
#### How can I contribute? #### How can I contribute?
@@ -50,17 +98,6 @@ If you want to connect an Appservice to Conduit, take a look at [APPSERVICES.md]
3. Fork the repo and work on the issue. #conduit:nordgedanken.dev is happy to help :) 3. Fork the repo and work on the issue. #conduit:nordgedanken.dev is happy to help :)
4. Submit a MR 4. Submit a MR
#### Thanks to
Thanks to Famedly, Prototype Fund (DLR and German BMBF) and all other individuals for financially supporting this project.
Thanks to the contributors to Conduit and all libraries we use, for example:
- Ruma: A clean library for the Matrix Spec in Rust
- Rocket: A flexible web framework
#### Donate #### Donate
Liberapay: <https://liberapay.com/timokoesters/>\ Liberapay: <https://liberapay.com/timokoesters/>\
+2 -2
View File
@@ -22,8 +22,8 @@ port = 6167
# Max size for uploads # Max size for uploads
max_request_size = 20_000_000 # in bytes max_request_size = 20_000_000 # in bytes
# Enables registration. If set to false, no users can register on this server. # Disable registration. No new users will be able to register on this server
allow_registration = true #allow_registration = false
# Disable encryption, so no new encrypted rooms can be created # Disable encryption, so no new encrypted rooms can be created
# Note: existing rooms will continue to work # Note: existing rooms will continue to work
+2 -2
View File
@@ -62,8 +62,8 @@ port = ${CONDUIT_PORT}
# Max size for uploads # Max size for uploads
max_request_size = 20_000_000 # in bytes max_request_size = 20_000_000 # in bytes
# Enables registration. If set to false, no users can register on this server. # Disable registration. No new users will be able to register on this server.
allow_registration = true #allow_registration = false
# Disable encryption, so no new encrypted rooms can be created. # Disable encryption, so no new encrypted rooms can be created.
# Note: Existing rooms will continue to work. # Note: Existing rooms will continue to work.
+1 -1
View File
@@ -27,7 +27,6 @@ services:
environment: environment:
CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]' CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
CONDUIT_ALLOW_REGISTRATION: 'true'
### 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
@@ -35,6 +34,7 @@ services:
# 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: "info,rocket=off,_=off,sled=off" # CONDUIT_LOG: info # default is: "info,rocket=off,_=off,sled=off"
# CONDUIT_ALLOW_JAEGER: 'false' # CONDUIT_ALLOW_JAEGER: 'false'
# CONDUIT_ALLOW_REGISTRATION : 'false'
# CONDUIT_ALLOW_ENCRYPTION: 'false' # CONDUIT_ALLOW_ENCRYPTION: 'false'
# CONDUIT_ALLOW_FEDERATION: 'false' # CONDUIT_ALLOW_FEDERATION: 'false'
# CONDUIT_DATABASE_PATH: /srv/conduit/.local/share/conduit # CONDUIT_DATABASE_PATH: /srv/conduit/.local/share/conduit
+5 -63
View File
@@ -40,27 +40,18 @@ which also will tag the resulting image as `matrixconduit/matrix-conduit:latest`
After building the image you can simply run it with After building the image you can simply run it with
``` bash ``` bash
docker run -d -p 8448:6167 -v ~/conduit.toml:/srv/conduit/conduit.toml -v db:/srv/conduit/.local/share/conduit matrixconduit/matrix-conduit:latest docker run -d -p 8448:8000 -v ~/conduit.toml:/srv/conduit/conduit.toml -v db:/srv/conduit/.local/share/conduit matrixconduit/matrix-conduit:latest
``` ```
or you can skip the build step and pull the image from one of the following registries: For detached mode, you also need to use the `-d` flag. You also need to supply a `conduit.toml` config file, you can find an example [here](../conduit-example.toml).
| Registry | Image | Size |
| --------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Docker Hub | [matrixconduit/matrix-conduit:latest](https://hub.docker.com/r/matrixconduit/matrix-conduit) | ![Image Size](https://img.shields.io/docker/image-size/matrixconduit/matrix-conduit/latest) |
| GitLab Registry | [registry.gitlab.com/famedly/conduit/conduit:latest](https://gitlab.com/famedly/conduit/container_registry/2134341) | ![Image Size](https://img.shields.io/docker/image-size/matrixconduit/matrix-conduit/latest) |
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. too pass `-e CONDUIT_CONFIG=""` into your container. For an overview of possible values, please take a look at the `docker-compose.yml` file.
If you just want to test Conduit for a short time, you can use the `--rm` flag, which will clean up everything related to your container after you stop it. If you just want to test Conduit for a short time, you can use the `--rm` flag, which will clean up everything related to your container after you stop it.
## Docker-compose ## Docker-compose
If the docker command is not for you or your setup, you can also use one of the provided `docker-compose` files. Depending on your proxy setup, use the [`docker-compose.traefik.yml`](docker-compose.traefik.yml) and [`docker-compose.override.traefik.yml`](docker-compose.override.traefik.yml) for Traefik (don't forget to remove `.traefik` from the filenames) or the normal [`docker-compose.yml`](../docker-compose.yml) for every other reverse proxy. Additional info about deploying If the docker command is not for you or your setup, you can also use one of the provided `docker-compose` files. Depending on your proxy setup, use the [`docker-compose.traefik.yml`](docker-compose.traefik.yml) including [`docker-compose.override.traefik.yml`](docker-compose.override.traefik.yml) or the normal [`docker-compose.yml`](../docker-compose.yml) for every other reverse proxy.
Conduit can be found [here](../DEPLOY.md).
### Build ### Build
@@ -76,57 +67,8 @@ This will also start the container right afterwards, so if want it to run in det
### Run ### Run
If you already have built the image or want to use one from the registries, you can just start the container and everything else in the compose file in detached mode with: If you already have built the image, you can just start the container and everything else in the compose file in detached mode with:
``` bash ``` bash
docker-compose up -d docker-compose up -d
``` ```
> **Note:** Don't forget to modify and adjust the compose file to your needs.
### Use Traefik as Proxy
As a container user, you probably know about Traefik. It is a easy to use reverse proxy for making containerized app and services available through the web. With the
two provided files, [`docker-compose.traefik.yml`](docker-compose.traefik.yml) and [`docker-compose.override.traefik.yml`](docker-compose.override.traefik.yml), it is
equally easy to deploy and use Conduit, with a little caveat. If you already took a look at the files, then you should have seen the `well-known` service, and that is
the little caveat. Traefik is simply a proxy and loadbalancer and is not able to serve any kind of content, but for Conduit to federate, we need to either expose ports
`443` and `8448` or serve two endpoints `.well-known/matrix/client` and `.well-known/matrix/server`.
With the service `well-known` we use a single `nginx` container that will serve those two files.
So...step by step:
1. Copy [`docker-compose.traefik.yml`](docker-compose.traefik.yml) and [`docker-compose.override.traefik.yml`](docker-compose.override.traefik.yml) from the repository and remove `.traefik` from the filenames.
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](../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`.
5. Create the files needed by the `well-known` service.
- `./nginx/matrix.conf` (relative to the compose file, you can change this, but then also need to change the volume mapping)
```nginx
server {
server_name <SUBDOMAIN>.<DOMAIN>;
listen 80 default_server;
location /.well-known/matrix/ {
root /var/www;
default_type application/json;
add_header Access-Control-Allow-Origin *;
}
}
```
- `./nginx/www/.well-known/matrix/client` (relative to the compose file, you can change this, but then also need to change the volume mapping)
```json
{
"m.homeserver": {
"base_url": "https://<SUBDOMAIN>.<DOMAIN>"
}
}
```
- `./nginx/www/.well-known/matrix/server` (relative to the compose file, you can change this, but then also need to change the volume mapping)
```json
{
"m.server": "<SUBDOMAIN>.<DOMAIN>:443"
}
```
6. Run `docker-compose up -d`
7. Connect to your homeserver with your preferred client and create a user. You should do this immediatly after starting Conduit, because the first created user is the admin.
+13 -12
View File
@@ -9,12 +9,6 @@
FROM alpine:3.14 FROM alpine:3.14
# Install packages needed to run Conduit
RUN apk add --no-cache \
ca-certificates \
curl \
libgcc
ARG CREATED ARG CREATED
ARG VERSION ARG VERSION
ARG GIT_REF ARG GIT_REF
@@ -42,10 +36,6 @@ EXPOSE 6167
# create data folder for database # create data folder for database
RUN mkdir -p /srv/conduit/.local/share/conduit RUN mkdir -p /srv/conduit/.local/share/conduit
# Copy the Conduit binary into the image at the latest possible moment to maximise caching:
COPY ./conduit-x86_64-unknown-linux-musl /srv/conduit/conduit
COPY ./docker/healthcheck.sh /srv/conduit/
# Add www-data user and group with UID 82, as used by alpine # Add www-data user and group with UID 82, as used by alpine
# https://git.alpinelinux.org/aports/tree/main/nginx/nginx.pre-install # https://git.alpinelinux.org/aports/tree/main/nginx/nginx.pre-install
RUN set -x ; \ RUN set -x ; \
@@ -55,11 +45,18 @@ RUN set -x ; \
# Change ownership of Conduit files to www-data user and group # Change ownership of Conduit files to www-data user and group
RUN chown -cR www-data:www-data /srv/conduit RUN chown -cR www-data:www-data /srv/conduit
RUN chmod +x /srv/conduit/healthcheck.sh
# Install packages needed to run Conduit
RUN apk add --no-cache \
ca-certificates \
curl \
libgcc
# Test if Conduit is still alive, uses the same endpoint as Element # Test if Conduit is still alive, uses the same endpoint as Element
HEALTHCHECK --start-period=5s --interval=60s CMD ./healthcheck.sh HEALTHCHECK --start-period=5s \
CMD curl --fail -s "http://localhost:$(grep -m1 -o 'port\s=\s[0-9]*' conduit.toml | grep -m1 -o '[0-9]*')/_matrix/client/versions" || \
curl -k --fail -s "https://localhost:$(grep -m1 -o 'port\s=\s[0-9]*' conduit.toml | grep -m1 -o '[0-9]*')/_matrix/client/versions" || \
exit 1
# Set user to www-data # Set user to www-data
USER www-data USER www-data
@@ -67,3 +64,7 @@ USER www-data
WORKDIR /srv/conduit WORKDIR /srv/conduit
# Run Conduit # Run Conduit
ENTRYPOINT [ "/srv/conduit/conduit" ] ENTRYPOINT [ "/srv/conduit/conduit" ]
# Copy the Conduit binary into the image at the latest possible moment to maximise caching:
COPY ./conduit-x86_64-unknown-linux-musl /srv/conduit/conduit
@@ -10,29 +10,6 @@ services:
- "traefik.http.routers.to-conduit.rule=Host(`<SUBDOMAIN>.<DOMAIN>`)" # Change to the address on which Conduit is hosted - "traefik.http.routers.to-conduit.rule=Host(`<SUBDOMAIN>.<DOMAIN>`)" # Change to the address on which Conduit is hosted
- "traefik.http.routers.to-conduit.tls=true" - "traefik.http.routers.to-conduit.tls=true"
- "traefik.http.routers.to-conduit.tls.certresolver=letsencrypt" - "traefik.http.routers.to-conduit.tls.certresolver=letsencrypt"
- "traefik.http.routers.to-conduit.middlewares=cors-headers@docker"
- "traefik.http.middlewares.cors-headers.headers.accessControlAllowOrigin=*"
- "traefik.http.middlewares.cors-headers.headers.accessControlAllowHeaders=Origin, X-Requested-With, Content-Type, Accept, Authorization"
- "traefik.http.middlewares.cors-headers.headers.accessControlAllowMethods=GET, POST, PUT, DELETE, OPTIONS"
# 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
# and in the docker-compose file.
well-known:
labels:
- "traefik.enable=true"
- "traefik.docker.network=proxy"
- "traefik.http.routers.to-matrix-wellknown.rule=Host(`<SUBDOMAIN>.<DOMAIN>`) && PathPrefix(`/.well-known/matrix`)"
- "traefik.http.routers.to-matrix-wellknown.tls=true"
- "traefik.http.routers.to-matrix-wellknown.tls.certresolver=letsencrypt"
- "traefik.http.routers.to-matrix-wellknown.middlewares=cors-headers@docker"
- "traefik.http.middlewares.cors-headers.headers.accessControlAllowOrigin=*"
- "traefik.http.middlewares.cors-headers.headers.accessControlAllowHeaders=Origin, X-Requested-With, Content-Type, Accept, Authorization"
- "traefik.http.middlewares.cors-headers.headers.accessControlAllowMethods=GET, POST, PUT, DELETE, OPTIONS"
### Uncomment this if you uncommented Element-Web App in the docker-compose.yml ### Uncomment this if you uncommented Element-Web App in the docker-compose.yml
# element-web: # element-web:
+1 -11
View File
@@ -27,7 +27,6 @@ services:
environment: environment:
CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]' CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
CONDUIT_ALLOW_REGISTRATION : 'true'
### 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
@@ -35,22 +34,13 @@ services:
# 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: "info,rocket=off,_=off,sled=off" # CONDUIT_LOG: info # default is: "info,rocket=off,_=off,sled=off"
# CONDUIT_ALLOW_JAEGER: 'false' # CONDUIT_ALLOW_JAEGER: 'false'
# CONDUIT_ALLOW_REGISTRATION : 'false'
# CONDUIT_ALLOW_ENCRYPTION: 'false' # CONDUIT_ALLOW_ENCRYPTION: 'false'
# CONDUIT_ALLOW_FEDERATION: 'false' # CONDUIT_ALLOW_FEDERATION: 'false'
# 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
# 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
# and in the docker-compose override file.
well-known:
image: nginx:latest
restart: unless-stopped
volumes:
- ./nginx/matrix.conf:/etc/nginx/conf.d/matrix.conf # the config to serve the .well-known/matrix files
- ./nginx/www:/var/www/ # location of the client and server .well-known-files
### 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
### Domain or Subdomain for the communication between Element and Conduit ### Domain or Subdomain for the communication between Element and Conduit
-13
View File
@@ -1,13 +0,0 @@
#!/bin/sh
# If the port is not specified as env var, take it from the config file
if [ -z ${CONDUIT_PORT} ]; then
CONDUIT_PORT=$(grep -m1 -o 'port\s=\s[0-9]*' conduit.toml | grep -m1 -o '[0-9]*')
fi
# The actual health check.
# We try to first get a response on HTTP and when that fails on HTTPS and when that fails, we exit with code 1.
# TODO: Change this to a single curl call. Do we have a config value that we can check for that?
curl --fail -s "http://localhost:${CONDUIT_PORT}/_matrix/client/versions" || \
curl -k --fail -s "https://localhost:${CONDUIT_PORT}/_matrix/client/versions" || \
exit 1
+2 -6
View File
@@ -9,7 +9,7 @@ use std::{
}; };
use tracing::warn; use tracing::warn;
pub(crate) async fn send_request<T: OutgoingRequest>( pub async fn send_request<T: OutgoingRequest>(
globals: &crate::database::globals::Globals, globals: &crate::database::globals::Globals,
registration: serde_yaml::Value, registration: serde_yaml::Value,
request: T, request: T,
@@ -46,11 +46,7 @@ where
*reqwest_request.timeout_mut() = Some(Duration::from_secs(30)); *reqwest_request.timeout_mut() = Some(Duration::from_secs(30));
let url = reqwest_request.url().clone(); let url = reqwest_request.url().clone();
let mut response = globals let mut response = globals.reqwest_client().execute(reqwest_request).await?;
.reqwest_client()?
.build()?
.execute(reqwest_request)
.await?;
// reqwest::Response -> http::Response conversion // reqwest::Response -> http::Response conversion
let status = response.status(); let status = response.status();
+21 -42
View File
@@ -40,12 +40,8 @@ const GUEST_NAME_LENGTH: usize = 10;
/// ///
/// Checks if a username is valid and available on this server. /// Checks if a username is valid and available on this server.
/// ///
/// Conditions for returning true: /// - Returns true if no user or appservice on this server claimed this username
/// - The user id is not historical /// - This will not reserve the username, so the username might become invalid when trying to register
/// - The server name of the user id matches this server
/// - No user or appservice on this server already claimed this username
///
/// Note: This will not reserve the username, so the username might become invalid when trying to register
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/register/available", data = "<body>") get("/_matrix/client/r0/register/available", data = "<body>")
@@ -84,15 +80,11 @@ pub async fn get_register_available_route(
/// ///
/// Register an account on this homeserver. /// Register an account on this homeserver.
/// ///
/// You can use [`GET /_matrix/client/r0/register/available`](fn.get_register_available_route.html) /// - Returns the device id and access_token unless `inhibit_login` is true
/// to check if the user id is valid and available. /// - When registering a guest account, all parameters except initial_device_display_name will be
/// /// ignored
/// - Only works if registration is enabled /// - Creates a new account and a device for it
/// - If type is guest: ignores all parameters except initial_device_display_name /// - The account will be populated with default account data
/// - 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 check
/// - Creates a new account and populates it with default account data
/// - If `inhibit_login` is false: Creates a device and returns device id and access_token
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/register", data = "<body>") post("/_matrix/client/r0/register", data = "<body>")
@@ -137,7 +129,7 @@ pub async fn register_route(
))?; ))?;
// Check if username is creative enough // Check if username is creative enough
if db.users.exists(&user_id)? { if !missing_username && db.users.exists(&user_id)? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::UserInUse, ErrorKind::UserInUse,
"Desired user ID is already taken.", "Desired user ID is already taken.",
@@ -201,12 +193,12 @@ pub async fn register_route(
// Create user // Create user
db.users.create(&user_id, password)?; db.users.create(&user_id, password)?;
// Default to pretty displayname
let displayname = format!("{} ⚡️", user_id.localpart()); let displayname = format!("{} ⚡️", user_id.localpart());
db.users db.users
.set_displayname(&user_id, Some(displayname.clone()))?; .set_displayname(&user_id, Some(displayname.clone()))?;
// Initial account data // Initial data
db.account_data.update( db.account_data.update(
None, None,
&user_id, &user_id,
@@ -219,7 +211,6 @@ pub async fn register_route(
&db.globals, &db.globals,
)?; )?;
// Inhibit login does not work for guests
if !is_guest && body.inhibit_login { if !is_guest && body.inhibit_login {
return Ok(register::Response { return Ok(register::Response {
access_token: None, access_token: None,
@@ -240,7 +231,7 @@ pub async fn register_route(
// Generate new token for the device // Generate new token for the device
let token = utils::random_string(TOKEN_LENGTH); let token = utils::random_string(TOKEN_LENGTH);
// Create device for this account // Add device
db.users.create_device( db.users.create_device(
&user_id, &user_id,
&device_id, &device_id,
@@ -248,7 +239,7 @@ pub async fn register_route(
body.initial_device_display_name.clone(), body.initial_device_display_name.clone(),
)?; )?;
// If this is the first user on this server, create the admin room // If this is the first user on this server, create the admins room
if db.users.count()? == 1 { if db.users.count()? == 1 {
// Create a user for the server // Create a user for the server
let conduit_user = UserId::parse_with_server_name("conduit", db.globals.server_name()) let conduit_user = UserId::parse_with_server_name("conduit", db.globals.server_name())
@@ -507,8 +498,8 @@ pub async fn register_route(
PduBuilder { PduBuilder {
event_type: EventType::RoomMessage, event_type: EventType::RoomMessage,
content: serde_json::to_value(message::MessageEventContent::text_html( content: serde_json::to_value(message::MessageEventContent::text_html(
"## Thank you for trying out Conduit!\n\nConduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.\n\nHelpful links:\n> Website: https://conduit.rs\n> Git and Documentation: https://gitlab.com/famedly/conduit\n> Report issues: https://gitlab.com/famedly/conduit/-/issues\n\nHere are some rooms you can join (by typing the command):\n\nConduit room (Ask questions and get notified on updates):\n`/join #conduit:fachschaften.org`\n\nConduit lounge (Off-topic, only Conduit users are allowed to join)\n`/join #conduit-lounge:conduit.rs`".to_owned(), "Thanks for trying out Conduit! This software is still in development, so expect many bugs and missing features. If you have federation enabled, you can join the Conduit chat room by typing `/join #conduit:matrix.org`. **Important: Please don't join any other Matrix rooms over federation without permission from the room's admins.** Some actions might trigger bugs in other server implementations, breaking the chat for everyone else.".to_owned(),
"<h2>Thank you for trying out Conduit!</h2>\n<p>Conduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.</p>\n<p>Helpful links:</p>\n<blockquote>\n<p>Website: https://conduit.rs<br>Git and Documentation: https://gitlab.com/famedly/conduit<br>Report issues: https://gitlab.com/famedly/conduit/-/issues</p>\n</blockquote>\n<p>Here are some rooms you can join (by typing the command):</p>\n<p>Conduit room (Ask questions and get notified on updates):<br><code>/join #conduit:fachschaften.org</code></p>\n<p>Conduit lounge (Off-topic, only Conduit users are allowed to join)<br><code>/join #conduit-lounge:conduit.rs</code></p>\n".to_owned(), "Thanks for trying out Conduit! This software is still in development, so expect many bugs and missing features. If you have federation enabled, you can join the Conduit chat room by typing <code>/join #conduit:matrix.org</code>. <strong>Important: Please don't join any other Matrix rooms over federation without permission from the room's admins.</strong> Some actions might trigger bugs in other server implementations, breaking the chat for everyone else.".to_owned(),
)) ))
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
@@ -538,16 +529,9 @@ pub async fn register_route(
/// ///
/// Changes the password of this account. /// Changes the password of this account.
/// ///
/// - Requires UIAA to verify user password /// - Invalidates all other access tokens if logout_devices is true
/// - Changes the password of the sender user /// - Deletes all other devices and most of their data (to-device events, last seen, etc.) if
/// - The password hash is calculated using argon2 with 32 character salt, the plain password is /// logout_devices is true
/// not saved
///
/// If logout_devices is true it does the following for each device except the sender device:
/// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// - Forgets to-device events
/// - Triggers device list updates
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/account/password", data = "<body>") post("/_matrix/client/r0/account/password", data = "<body>")
@@ -614,9 +598,9 @@ pub async fn change_password_route(
/// # `GET _matrix/client/r0/account/whoami` /// # `GET _matrix/client/r0/account/whoami`
/// ///
/// Get user_id of the sender user. /// Get user_id of this account.
/// ///
/// Note: Also works for Application Services /// - Also works for Application Services
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/account/whoami", data = "<body>") get("/_matrix/client/r0/account/whoami", data = "<body>")
@@ -632,13 +616,11 @@ pub async fn whoami_route(body: Ruma<whoami::Request>) -> ConduitResult<whoami::
/// # `POST /_matrix/client/r0/account/deactivate` /// # `POST /_matrix/client/r0/account/deactivate`
/// ///
/// Deactivate sender user account. /// Deactivate this user's account
/// ///
/// - 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, last seen ts) /// - Deletes all devices
/// - Forgets all to-device events
/// - Triggers device list updates
/// - Removes ability to log in again /// - Removes ability to log in again
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
@@ -685,7 +667,6 @@ pub async fn deactivate_route(
} }
// Leave all joined rooms and reject all invitations // Leave all joined rooms and reject all invitations
// TODO: work over federation invites
let all_rooms = db let all_rooms = db
.rooms .rooms
.rooms_joined(&sender_user) .rooms_joined(&sender_user)
@@ -749,8 +730,6 @@ pub async fn deactivate_route(
/// # `GET _matrix/client/r0/account/3pid` /// # `GET _matrix/client/r0/account/3pid`
/// ///
/// 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
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/account/3pid", data = "<body>") get("/_matrix/client/r0/account/3pid", data = "<body>")
+1 -31
View File
@@ -15,9 +15,6 @@ use ruma::{
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{delete, get, put}; use rocket::{delete, get, put};
/// # `PUT /_matrix/client/r0/directory/room/{roomAlias}`
///
/// Creates a new room alias on this server.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/directory/room/<_>", data = "<body>") put("/_matrix/client/r0/directory/room/<_>", data = "<body>")
@@ -27,13 +24,6 @@ pub async fn create_alias_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<create_alias::Request<'_>>, body: Ruma<create_alias::Request<'_>>,
) -> ConduitResult<create_alias::Response> { ) -> ConduitResult<create_alias::Response> {
if body.room_alias.server_name() != db.globals.server_name() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Alias is from another server.",
));
}
if db.rooms.id_from_alias(&body.room_alias)?.is_some() { if db.rooms.id_from_alias(&body.room_alias)?.is_some() {
return Err(Error::Conflict("Alias already exists.")); return Err(Error::Conflict("Alias already exists."));
} }
@@ -46,12 +36,6 @@ pub async fn create_alias_route(
Ok(create_alias::Response::new().into()) Ok(create_alias::Response::new().into())
} }
/// # `DELETE /_matrix/client/r0/directory/room/{roomAlias}`
///
/// Deletes a room alias from this server.
///
/// - TODO: additional access control checks
/// - TODO: Update canonical alias event
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
delete("/_matrix/client/r0/directory/room/<_>", data = "<body>") delete("/_matrix/client/r0/directory/room/<_>", data = "<body>")
@@ -61,27 +45,13 @@ pub async fn delete_alias_route(
db: DatabaseGuard, db: DatabaseGuard,
body: Ruma<delete_alias::Request<'_>>, body: Ruma<delete_alias::Request<'_>>,
) -> ConduitResult<delete_alias::Response> { ) -> ConduitResult<delete_alias::Response> {
if body.room_alias.server_name() != db.globals.server_name() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Alias is from another server.",
));
}
db.rooms.set_alias(&body.room_alias, None, &db.globals)?; db.rooms.set_alias(&body.room_alias, None, &db.globals)?;
// TODO: update alt_aliases?
db.flush()?; db.flush()?;
Ok(delete_alias::Response::new().into()) Ok(delete_alias::Response::new().into())
} }
/// # `GET /_matrix/client/r0/directory/room/{roomAlias}`
///
/// Resolve an alias locally or over federation.
///
/// - TODO: Suggest more servers to join via
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/directory/room/<_>", data = "<body>") get("/_matrix/client/r0/directory/room/<_>", data = "<body>")
@@ -94,7 +64,7 @@ pub async fn get_alias_route(
get_alias_helper(&db, &body.room_alias).await get_alias_helper(&db, &body.room_alias).await
} }
pub(crate) async fn get_alias_helper( pub async fn get_alias_helper(
db: &Database, db: &Database,
room_alias: &RoomAliasId, room_alias: &RoomAliasId,
) -> ConduitResult<get_alias::Response> { ) -> ConduitResult<get_alias::Response> {
-89
View File
@@ -12,9 +12,6 @@ use ruma::api::client::{
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{delete, get, post, put}; use rocket::{delete, get, post, put};
/// # `POST /_matrix/client/r0/room_keys/version`
///
/// Creates a new backup.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/unstable/room_keys/version", data = "<body>") post("/_matrix/client/unstable/room_keys/version", data = "<body>")
@@ -34,9 +31,6 @@ pub async fn create_backup_route(
Ok(create_backup::Response { version }.into()) Ok(create_backup::Response { version }.into())
} }
/// # `PUT /_matrix/client/r0/room_keys/version/{version}`
///
/// Update information about an existing backup. Only `auth_data` can be modified.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/unstable/room_keys/version/<_>", data = "<body>") put("/_matrix/client/unstable/room_keys/version/<_>", data = "<body>")
@@ -55,9 +49,6 @@ pub async fn update_backup_route(
Ok(update_backup::Response {}.into()) Ok(update_backup::Response {}.into())
} }
/// # `GET /_matrix/client/r0/room_keys/version`
///
/// Get information about the latest backup version.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/version", data = "<body>") get("/_matrix/client/unstable/room_keys/version", data = "<body>")
@@ -86,9 +77,6 @@ pub async fn get_latest_backup_route(
.into()) .into())
} }
/// # `GET /_matrix/client/r0/room_keys/version`
///
/// Get information about an existing backup.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/version/<_>", data = "<body>") get("/_matrix/client/unstable/room_keys/version/<_>", data = "<body>")
@@ -116,11 +104,6 @@ pub async fn get_backup_route(
.into()) .into())
} }
/// # `DELETE /_matrix/client/r0/room_keys/version/{version}`
///
/// Delete an existing key backup.
///
/// - Deletes both information about the backup, as well as all key data related to the backup
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
delete("/_matrix/client/unstable/room_keys/version/<_>", data = "<body>") delete("/_matrix/client/unstable/room_keys/version/<_>", data = "<body>")
@@ -139,13 +122,7 @@ pub async fn delete_backup_route(
Ok(delete_backup::Response {}.into()) Ok(delete_backup::Response {}.into())
} }
/// # `PUT /_matrix/client/r0/room_keys/keys`
///
/// 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 allowed
/// - Adds the keys to the backup
/// - Returns the new number of keys in this backup and the etag
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/unstable/room_keys/keys", data = "<body>") put("/_matrix/client/unstable/room_keys/keys", data = "<body>")
@@ -157,18 +134,6 @@ pub async fn add_backup_keys_route(
) -> ConduitResult<add_backup_keys::Response> { ) -> ConduitResult<add_backup_keys::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)
!= db
.key_backups
.get_latest_backup_version(sender_user)?
.as_ref()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.",
));
}
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 {
db.key_backups.add_key( db.key_backups.add_key(
@@ -191,13 +156,7 @@ pub async fn add_backup_keys_route(
.into()) .into())
} }
/// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}`
///
/// 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 allowed
/// - Adds the keys to the backup
/// - Returns the new number of keys in this backup and the etag
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/unstable/room_keys/keys/<_>", data = "<body>") put("/_matrix/client/unstable/room_keys/keys/<_>", data = "<body>")
@@ -209,18 +168,6 @@ pub async fn add_backup_key_sessions_route(
) -> ConduitResult<add_backup_key_sessions::Response> { ) -> ConduitResult<add_backup_key_sessions::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)
!= db
.key_backups
.get_latest_backup_version(sender_user)?
.as_ref()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.",
));
}
for (session_id, key_data) in &body.sessions { for (session_id, key_data) in &body.sessions {
db.key_backups.add_key( db.key_backups.add_key(
&sender_user, &sender_user,
@@ -241,13 +188,7 @@ pub async fn add_backup_key_sessions_route(
.into()) .into())
} }
/// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
///
/// 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 allowed
/// - Adds the keys to the backup
/// - Returns the new number of keys in this backup and the etag
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/unstable/room_keys/keys/<_>/<_>", data = "<body>") put("/_matrix/client/unstable/room_keys/keys/<_>/<_>", data = "<body>")
@@ -259,18 +200,6 @@ pub async fn add_backup_key_session_route(
) -> ConduitResult<add_backup_key_session::Response> { ) -> ConduitResult<add_backup_key_session::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)
!= db
.key_backups
.get_latest_backup_version(sender_user)?
.as_ref()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.",
));
}
db.key_backups.add_key( db.key_backups.add_key(
&sender_user, &sender_user,
&body.version, &body.version,
@@ -289,9 +218,6 @@ pub async fn add_backup_key_session_route(
.into()) .into())
} }
/// # `GET /_matrix/client/r0/room_keys/keys`
///
/// Retrieves all keys from the backup.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/keys", data = "<body>") get("/_matrix/client/unstable/room_keys/keys", data = "<body>")
@@ -308,9 +234,6 @@ pub async fn get_backup_keys_route(
Ok(get_backup_keys::Response { rooms }.into()) Ok(get_backup_keys::Response { rooms }.into())
} }
/// # `GET /_matrix/client/r0/room_keys/keys/{roomId}`
///
/// Retrieves all keys from the backup for a given room.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/keys/<_>", data = "<body>") get("/_matrix/client/unstable/room_keys/keys/<_>", data = "<body>")
@@ -329,9 +252,6 @@ pub async fn get_backup_key_sessions_route(
Ok(get_backup_key_sessions::Response { sessions }.into()) Ok(get_backup_key_sessions::Response { sessions }.into())
} }
/// # `GET /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
///
/// Retrieves a key from the backup.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/keys/<_>/<_>", data = "<body>") get("/_matrix/client/unstable/room_keys/keys/<_>/<_>", data = "<body>")
@@ -354,9 +274,6 @@ pub async fn get_backup_key_session_route(
Ok(get_backup_key_session::Response { key_data }.into()) Ok(get_backup_key_session::Response { key_data }.into())
} }
/// # `DELETE /_matrix/client/r0/room_keys/keys`
///
/// Delete the keys from the backup.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
delete("/_matrix/client/unstable/room_keys/keys", data = "<body>") delete("/_matrix/client/unstable/room_keys/keys", data = "<body>")
@@ -380,9 +297,6 @@ pub async fn delete_backup_keys_route(
.into()) .into())
} }
/// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}`
///
/// Delete the keys from the backup for a given room.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
delete("/_matrix/client/unstable/room_keys/keys/<_>", data = "<body>") delete("/_matrix/client/unstable/room_keys/keys/<_>", data = "<body>")
@@ -406,9 +320,6 @@ pub async fn delete_backup_key_sessions_route(
.into()) .into())
} }
/// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
///
/// Delete a key from the backup.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
delete("/_matrix/client/unstable/room_keys/keys/<_>/<_>", data = "<body>") delete("/_matrix/client/unstable/room_keys/keys/<_>/<_>", data = "<body>")
+1 -1
View File
@@ -13,7 +13,7 @@ use rocket::get;
/// # `GET /_matrix/client/r0/capabilities` /// # `GET /_matrix/client/r0/capabilities`
/// ///
/// Get information on the supported feature set and other relevent capabilities of this server. /// Get information on this server's supported feature set and other relevent capabilities.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/capabilities", data = "<_body>") get("/_matrix/client/r0/capabilities", data = "<_body>")
+2 -12
View File
@@ -16,9 +16,6 @@ use serde_json::{json, value::RawValue as RawJsonValue};
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, put}; use rocket::{get, put};
/// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`
///
/// Sets some account data for the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/user/<_>/account_data/<_>", data = "<body>") put("/_matrix/client/r0/user/<_>/account_data/<_>", data = "<body>")
@@ -51,9 +48,6 @@ pub async fn set_global_account_data_route(
Ok(set_global_account_data::Response {}.into()) Ok(set_global_account_data::Response {}.into())
} }
/// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`
///
/// Sets some room account data for the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put( put(
@@ -89,9 +83,6 @@ pub async fn set_room_account_data_route(
Ok(set_room_account_data::Response {}.into()) Ok(set_room_account_data::Response {}.into())
} }
/// # `GET /_matrix/client/r0/user/{userId}/account_data/{type}`
///
/// Gets some account data for the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/user/<_>/account_data/<_>", data = "<body>") get("/_matrix/client/r0/user/<_>/account_data/<_>", data = "<body>")
@@ -107,6 +98,7 @@ pub async fn get_global_account_data_route(
.account_data .account_data
.get::<Box<RawJsonValue>>(None, sender_user, body.event_type.clone().into())? .get::<Box<RawJsonValue>>(None, sender_user, body.event_type.clone().into())?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
db.flush()?;
let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get()) let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
@@ -115,9 +107,6 @@ pub async fn get_global_account_data_route(
Ok(get_global_account_data::Response { account_data }.into()) Ok(get_global_account_data::Response { account_data }.into())
} }
/// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}`
///
/// Gets some room account data for the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get( get(
@@ -140,6 +129,7 @@ pub async fn get_room_account_data_route(
body.event_type.clone().into(), body.event_type.clone().into(),
)? )?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?; .ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
db.flush()?;
let account_data = serde_json::from_str::<ExtractRoomEventContent>(event.get()) let account_data = serde_json::from_str::<ExtractRoomEventContent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))? .map_err(|_| Error::bad_database("Invalid account data event in db."))?
-6
View File
@@ -5,12 +5,6 @@ use std::convert::TryFrom;
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::get; use rocket::get;
/// # `GET /_matrix/client/r0/rooms/{roomId}/context`
///
/// Allows loading room history around an event.
///
/// - Only works if the user is joined (TODO: always allow, but only show events if the user was
/// joined, depending on history_visibility)
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/context/<_>", data = "<body>") get("/_matrix/client/r0/rooms/<_>/context/<_>", data = "<body>")
-29
View File
@@ -11,9 +11,6 @@ use super::SESSION_ID_LENGTH;
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{delete, get, post, put}; use rocket::{delete, get, post, put};
/// # `GET /_matrix/client/r0/devices`
///
/// Get metadata on all devices of the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/devices", data = "<body>") get("/_matrix/client/r0/devices", data = "<body>")
@@ -34,9 +31,6 @@ pub async fn get_devices_route(
Ok(get_devices::Response { devices }.into()) Ok(get_devices::Response { devices }.into())
} }
/// # `GET /_matrix/client/r0/devices/{deviceId}`
///
/// Get metadata on a single device of the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/devices/<_>", data = "<body>") get("/_matrix/client/r0/devices/<_>", data = "<body>")
@@ -56,9 +50,6 @@ pub async fn get_device_route(
Ok(get_device::Response { device }.into()) Ok(get_device::Response { device }.into())
} }
/// # `PUT /_matrix/client/r0/devices/{deviceId}`
///
/// Updates the metadata on a given device of the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/devices/<_>", data = "<body>") put("/_matrix/client/r0/devices/<_>", data = "<body>")
@@ -85,15 +76,6 @@ pub async fn update_device_route(
Ok(update_device::Response {}.into()) Ok(update_device::Response {}.into())
} }
/// # `PUT /_matrix/client/r0/devices/{deviceId}`
///
/// Deletes the given device.
///
/// - Requires UIAA to verify user password
/// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// - Forgets to-device events
/// - Triggers device list updates
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
delete("/_matrix/client/r0/devices/<_>", data = "<body>") delete("/_matrix/client/r0/devices/<_>", data = "<body>")
@@ -146,17 +128,6 @@ pub async fn delete_device_route(
Ok(delete_device::Response {}.into()) Ok(delete_device::Response {}.into())
} }
/// # `PUT /_matrix/client/r0/devices/{deviceId}`
///
/// Deletes the given device.
///
/// - Requires UIAA to verify user password
///
/// For each device:
/// - Invalidates access token
/// - Deletes device metadata (device id, device display name, last seen ip, last seen ts)
/// - Forgets to-device events
/// - Triggers device list updates
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/delete_devices", data = "<body>") post("/_matrix/client/r0/delete_devices", data = "<body>")
+3 -20
View File
@@ -28,11 +28,6 @@ use tracing::{info, warn};
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, post, put}; use rocket::{get, post, put};
/// # `POST /_matrix/client/r0/publicRooms`
///
/// Lists the public rooms on this server.
///
/// - Rooms are ordered by the number of joined members
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/publicRooms", data = "<body>") post("/_matrix/client/r0/publicRooms", data = "<body>")
@@ -53,11 +48,6 @@ pub async fn get_public_rooms_filtered_route(
.await .await
} }
/// # `GET /_matrix/client/r0/publicRooms`
///
/// Lists the public rooms on this server.
///
/// - Rooms are ordered by the number of joined members
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/publicRooms", data = "<body>") get("/_matrix/client/r0/publicRooms", data = "<body>")
@@ -87,11 +77,6 @@ pub async fn get_public_rooms_route(
.into()) .into())
} }
/// # `PUT /_matrix/client/r0/directory/list/room/{roomId}`
///
/// Sets the visibility of a given room in the room directory.
///
/// - TODO: Access control checks
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/directory/list/room/<_>", data = "<body>") put("/_matrix/client/r0/directory/list/room/<_>", data = "<body>")
@@ -122,9 +107,6 @@ pub async fn set_room_visibility_route(
Ok(set_room_visibility::Response {}.into()) Ok(set_room_visibility::Response {}.into())
} }
/// # `GET /_matrix/client/r0/directory/list/room/{roomId}`
///
/// Gets the visibility of a given room in the room directory.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/directory/list/room/<_>", data = "<body>") get("/_matrix/client/r0/directory/list/room/<_>", data = "<body>")
@@ -144,7 +126,7 @@ pub async fn get_room_visibility_route(
.into()) .into())
} }
pub(crate) async fn get_public_rooms_filtered_helper( pub async fn get_public_rooms_filtered_helper(
db: &Database, db: &Database,
server: Option<&ServerName>, server: Option<&ServerName>,
limit: Option<UInt>, limit: Option<UInt>,
@@ -251,7 +233,8 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.map_err(|_| { .map_err(|_| {
Error::bad_database("Invalid room name event in database.") Error::bad_database("Invalid room name event in database.")
})? })?
.name) .name
.map(|n| n.to_owned().into()))
})?, })?,
num_joined_members: db num_joined_members: db
.rooms .rooms
-6
View File
@@ -4,9 +4,6 @@ use ruma::api::client::r0::filter::{self, create_filter, get_filter};
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, post}; use rocket::{get, post};
/// # `GET /_matrix/client/r0/user/{userId}/filter/{filterId}`
///
/// TODO: Loads a filter that was previously created.
#[cfg_attr(feature = "conduit_bin", get("/_matrix/client/r0/user/<_>/filter/<_>"))] #[cfg_attr(feature = "conduit_bin", get("/_matrix/client/r0/user/<_>/filter/<_>"))]
#[tracing::instrument] #[tracing::instrument]
pub async fn get_filter_route() -> ConduitResult<get_filter::Response> { pub async fn get_filter_route() -> ConduitResult<get_filter::Response> {
@@ -21,9 +18,6 @@ pub async fn get_filter_route() -> ConduitResult<get_filter::Response> {
.into()) .into())
} }
/// # `PUT /_matrix/client/r0/user/{userId}/filter`
///
/// TODO: Creates a new filter to be used by other endpoints.
#[cfg_attr(feature = "conduit_bin", post("/_matrix/client/r0/user/<_>/filter"))] #[cfg_attr(feature = "conduit_bin", post("/_matrix/client/r0/user/<_>/filter"))]
#[tracing::instrument] #[tracing::instrument]
pub async fn create_filter_route() -> ConduitResult<create_filter::Response> { pub async fn create_filter_route() -> ConduitResult<create_filter::Response> {
+23 -67
View File
@@ -1,6 +1,5 @@
use super::SESSION_ID_LENGTH; use super::SESSION_ID_LENGTH;
use crate::{database::DatabaseGuard, utils, ConduitResult, Database, Error, Result, Ruma}; use crate::{database::DatabaseGuard, utils, ConduitResult, Database, Error, Result, Ruma};
use rocket::futures::{prelude::*, stream::FuturesUnordered};
use ruma::{ use ruma::{
api::{ api::{
client::{ client::{
@@ -19,17 +18,11 @@ use ruma::{
DeviceId, DeviceKeyAlgorithm, UserId, DeviceId, DeviceKeyAlgorithm, UserId,
}; };
use serde_json::json; use serde_json::json;
use std::collections::{BTreeMap, HashMap, HashSet}; use std::collections::{BTreeMap, HashSet};
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, post}; use rocket::{get, post};
/// # `POST /_matrix/client/r0/keys/upload`
///
/// Publish end-to-end encryption keys for the sender device.
///
/// - Adds one time keys
/// - If there are no device keys yet: Adds device keys (TODO: merge with existing keys?)
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/keys/upload", data = "<body>") post("/_matrix/client/r0/keys/upload", data = "<body>")
@@ -55,7 +48,6 @@ pub async fn upload_keys_route(
} }
if let Some(device_keys) = &body.device_keys { if let Some(device_keys) = &body.device_keys {
// 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 db if db
.users .users
@@ -80,13 +72,6 @@ pub async fn upload_keys_route(
.into()) .into())
} }
/// # `POST /_matrix/client/r0/keys/query`
///
/// Get end-to-end encryption keys for the given users.
///
/// - Always fetches users from other servers over federation
/// - Gets master keys, self-signing keys, user signing keys and device keys.
/// - The master and self-signing keys contain signatures that the user is allowed to see
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/keys/query", data = "<body>") post("/_matrix/client/r0/keys/query", data = "<body>")
@@ -109,9 +94,6 @@ pub async fn get_keys_route(
Ok(response.into()) Ok(response.into())
} }
/// # `POST /_matrix/client/r0/keys/claim`
///
/// Claims one-time keys
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/keys/claim", data = "<body>") post("/_matrix/client/r0/keys/claim", data = "<body>")
@@ -128,11 +110,6 @@ pub async fn claim_keys_route(
Ok(response.into()) Ok(response.into())
} }
/// # `POST /_matrix/client/r0/keys/device_signing/upload`
///
/// Uploads end-to-end key information for the sender user.
///
/// - Requires UIAA to verify password
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/unstable/keys/device_signing/upload", data = "<body>") post("/_matrix/client/unstable/keys/device_signing/upload", data = "<body>")
@@ -194,9 +171,6 @@ pub async fn upload_signing_keys_route(
Ok(upload_signing_keys::Response {}.into()) Ok(upload_signing_keys::Response {}.into())
} }
/// # `POST /_matrix/client/r0/keys/signatures/upload`
///
/// Uploads end-to-end key signatures from the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/unstable/keys/signatures/upload", data = "<body>") post("/_matrix/client/unstable/keys/signatures/upload", data = "<body>")
@@ -258,11 +232,6 @@ pub async fn upload_signatures_route(
Ok(upload_signatures::Response {}.into()) Ok(upload_signatures::Response {}.into())
} }
/// # `POST /_matrix/client/r0/keys/changes`
///
/// Gets a list of users who have updated their device identity keys since the previous sync token.
///
/// - TODO: left users
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/keys/changes", data = "<body>") get("/_matrix/client/r0/keys/changes", data = "<body>")
@@ -314,7 +283,7 @@ pub async fn get_key_changes_route(
.into()) .into())
} }
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>( pub async fn get_keys_helper<F: Fn(&UserId) -> bool>(
sender_user: Option<&UserId>, sender_user: Option<&UserId>,
device_keys_input: &BTreeMap<UserId, Vec<Box<DeviceId>>>, device_keys_input: &BTreeMap<UserId, Vec<Box<DeviceId>>>,
allowed_signatures: F, allowed_signatures: F,
@@ -325,7 +294,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
let mut user_signing_keys = BTreeMap::new(); let mut user_signing_keys = BTreeMap::new();
let mut device_keys = BTreeMap::new(); let mut device_keys = BTreeMap::new();
let mut get_over_federation = HashMap::new(); let mut get_over_federation = BTreeMap::new();
for (user_id, device_ids) in device_keys_input { for (user_id, device_ids) in device_keys_input {
if user_id.server_name() != db.globals.server_name() { if user_id.server_name() != db.globals.server_name() {
@@ -395,30 +364,22 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
let mut failures = BTreeMap::new(); let mut failures = BTreeMap::new();
let mut futures = get_over_federation for (server, vec) in get_over_federation {
.into_iter() let mut device_keys_input_fed = BTreeMap::new();
.map(|(server, vec)| async move { for (user_id, keys) in vec {
let mut device_keys_input_fed = BTreeMap::new(); device_keys_input_fed.insert(user_id.clone(), keys.clone());
for (user_id, keys) in vec { }
device_keys_input_fed.insert(user_id.clone(), keys.clone()); match db
} .sending
( .send_federation_request(
&db.globals,
server, server,
db.sending federation::keys::get_keys::v1::Request {
.send_federation_request( device_keys: device_keys_input_fed,
&db.globals, },
server,
federation::keys::get_keys::v1::Request {
device_keys: device_keys_input_fed,
},
)
.await,
) )
}) .await
.collect::<FuturesUnordered<_>>(); {
while let Some((server, response)) = futures.next().await {
match response {
Ok(response) => { Ok(response) => {
master_keys.extend(response.master_keys); master_keys.extend(response.master_keys);
self_signing_keys.extend(response.self_signing_keys); self_signing_keys.extend(response.self_signing_keys);
@@ -439,7 +400,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
}) })
} }
pub(crate) async fn claim_keys_helper( pub async fn claim_keys_helper(
one_time_keys_input: &BTreeMap<UserId, BTreeMap<Box<DeviceId>, DeviceKeyAlgorithm>>, one_time_keys_input: &BTreeMap<UserId, BTreeMap<Box<DeviceId>, DeviceKeyAlgorithm>>,
db: &Database, db: &Database,
) -> Result<claim_keys::Response> { ) -> Result<claim_keys::Response> {
@@ -469,15 +430,13 @@ pub(crate) async fn claim_keys_helper(
one_time_keys.insert(user_id.clone(), container); one_time_keys.insert(user_id.clone(), container);
} }
let mut failures = BTreeMap::new();
for (server, vec) in get_over_federation { for (server, vec) in get_over_federation {
let mut one_time_keys_input_fed = BTreeMap::new(); let mut one_time_keys_input_fed = BTreeMap::new();
for (user_id, keys) in vec { for (user_id, keys) in vec {
one_time_keys_input_fed.insert(user_id.clone(), keys.clone()); one_time_keys_input_fed.insert(user_id.clone(), keys.clone());
} }
// Ignore failures // Ignore failures
if let Ok(keys) = db let keys = db
.sending .sending
.send_federation_request( .send_federation_request(
&db.globals, &db.globals,
@@ -486,16 +445,13 @@ pub(crate) async fn claim_keys_helper(
one_time_keys: one_time_keys_input_fed, one_time_keys: one_time_keys_input_fed,
}, },
) )
.await .await?;
{
one_time_keys.extend(keys.one_time_keys); one_time_keys.extend(keys.one_time_keys);
} else {
failures.insert(server.to_string(), json!({}));
}
} }
Ok(claim_keys::Response { Ok(claim_keys::Response {
failures, failures: BTreeMap::new(),
one_time_keys, one_time_keys,
}) })
} }
-19
View File
@@ -12,9 +12,6 @@ use rocket::{get, post};
const MXC_LENGTH: usize = 32; const MXC_LENGTH: usize = 32;
/// # `GET /_matrix/media/r0/config`
///
/// Returns max upload size.
#[cfg_attr(feature = "conduit_bin", get("/_matrix/media/r0/config"))] #[cfg_attr(feature = "conduit_bin", get("/_matrix/media/r0/config"))]
#[tracing::instrument(skip(db))] #[tracing::instrument(skip(db))]
pub async fn get_media_config_route( pub async fn get_media_config_route(
@@ -26,12 +23,6 @@ pub async fn get_media_config_route(
.into()) .into())
} }
/// # `POST /_matrix/media/r0/upload`
///
/// Permanently save media in the server.
///
/// - Some metadata will be saved in the database
/// - Media will be saved in the media/ directory
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/media/r0/upload", data = "<body>") post("/_matrix/media/r0/upload", data = "<body>")
@@ -70,11 +61,6 @@ pub async fn create_content_route(
.into()) .into())
} }
/// # `POST /_matrix/media/r0/download/{serverName}/{mediaId}`
///
/// Load media from our server or over federation.
///
/// - Only allows federation if `allow_remote` is true
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/media/r0/download/<_>/<_>", data = "<body>") get("/_matrix/media/r0/download/<_>/<_>", data = "<body>")
@@ -128,11 +114,6 @@ pub async fn get_content_route(
} }
} }
/// # `POST /_matrix/media/r0/thumbnail/{serverName}/{mediaId}`
///
/// Load media thumbnail from our server or over federation.
///
/// - Only allows federation if `allow_remote` is true
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/media/r0/thumbnail/<_>/<_>", data = "<body>") get("/_matrix/media/r0/thumbnail/<_>/<_>", data = "<body>")
+26 -86
View File
@@ -5,6 +5,7 @@ use crate::{
server_server, utils, ConduitResult, Database, Error, Result, Ruma, server_server, utils, ConduitResult, Database, Error, Result, Ruma,
}; };
use member::{MemberEventContent, MembershipState}; use member::{MemberEventContent, MembershipState};
use rocket::futures;
use ruma::{ use ruma::{
api::{ api::{
client::{ client::{
@@ -37,12 +38,6 @@ use tracing::{debug, error, warn};
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, post}; use rocket::{get, post};
/// # `POST /_matrix/client/r0/rooms/{roomId}/join`
///
/// Tries to join the sender user into a room.
///
/// - If the server knowns about this room: creates the join event and does auth rules locally
/// - If the server does not know about the room: asks other servers over federation
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/join", data = "<body>") post("/_matrix/client/r0/rooms/<_>/join", data = "<body>")
@@ -84,12 +79,6 @@ pub async fn join_room_by_id_route(
ret ret
} }
/// # `POST /_matrix/client/r0/join/{roomIdOrAlias}`
///
/// Tries to join the sender user into a room.
///
/// - If the server knowns about this room: creates the join event and does auth rules locally
/// - If the server does not know about the room: asks other servers over federation
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/join/<_>", data = "<body>") post("/_matrix/client/r0/join/<_>", data = "<body>")
@@ -144,11 +133,6 @@ pub async fn join_room_by_id_or_alias_route(
.into()) .into())
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/leave`
///
/// Tries to leave the sender user from a room.
///
/// - This should always work if the user is currently joined.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/leave", data = "<body>") post("/_matrix/client/r0/rooms/<_>/leave", data = "<body>")
@@ -167,9 +151,6 @@ pub async fn leave_room_route(
Ok(leave_room::Response::new().into()) Ok(leave_room::Response::new().into())
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/invite`
///
/// Tries to send an invite event into the room.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/invite", data = "<body>") post("/_matrix/client/r0/rooms/<_>/invite", data = "<body>")
@@ -190,9 +171,6 @@ pub async fn invite_user_route(
} }
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/kick`
///
/// Tries to send a kick event into the room.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/kick", data = "<body>") post("/_matrix/client/r0/rooms/<_>/kick", data = "<body>")
@@ -256,9 +234,6 @@ pub async fn kick_user_route(
Ok(kick_user::Response::new().into()) Ok(kick_user::Response::new().into())
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/ban`
///
/// Tries to send a ban event into the room.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/ban", data = "<body>") post("/_matrix/client/r0/rooms/<_>/ban", data = "<body>")
@@ -332,9 +307,6 @@ pub async fn ban_user_route(
Ok(ban_user::Response::new().into()) Ok(ban_user::Response::new().into())
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/unban`
///
/// Tries to send an unban event into the room.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/unban", data = "<body>") post("/_matrix/client/r0/rooms/<_>/unban", data = "<body>")
@@ -397,14 +369,6 @@ pub async fn unban_user_route(
Ok(unban_user::Response::new().into()) Ok(unban_user::Response::new().into())
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/forget`
///
/// Forgets about a room.
///
/// - If the sender user currently left the room: Stops sender user from receiving information about the room
///
/// Note: Other devices of the user have no way of knowing the room was forgotten, so this has to
/// be called from every device
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/forget", data = "<body>") post("/_matrix/client/r0/rooms/<_>/forget", data = "<body>")
@@ -423,9 +387,6 @@ pub async fn forget_room_route(
Ok(forget_room::Response::new().into()) Ok(forget_room::Response::new().into())
} }
/// # `POST /_matrix/client/r0/joined_rooms`
///
/// Lists all rooms the user has joined.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/joined_rooms", data = "<body>") get("/_matrix/client/r0/joined_rooms", data = "<body>")
@@ -447,11 +408,6 @@ pub async fn joined_rooms_route(
.into()) .into())
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/members`
///
/// Lists all joined users in a room (TODO: at a specific point in time, with a specific membership).
///
/// - Only works if the user is currently joined
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/members", data = "<body>") get("/_matrix/client/r0/rooms/<_>/members", data = "<body>")
@@ -463,7 +419,6 @@ pub async fn get_member_events_route(
) -> ConduitResult<get_member_events::Response> { ) -> ConduitResult<get_member_events::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");
// TODO: check history visibility?
if !db.rooms.is_joined(sender_user, &body.room_id)? { if !db.rooms.is_joined(sender_user, &body.room_id)? {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
@@ -483,12 +438,6 @@ pub async fn get_member_events_route(
.into()) .into())
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/joined_members`
///
/// Lists all members of a room.
///
/// - The sender user must be in the room
/// - TODO: An appservice just needs a puppet joined
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/joined_members", data = "<body>") get("/_matrix/client/r0/rooms/<_>/joined_members", data = "<body>")
@@ -500,7 +449,11 @@ pub async fn joined_members_route(
) -> ConduitResult<joined_members::Response> { ) -> ConduitResult<joined_members::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 !db.rooms.is_joined(&sender_user, &body.room_id)? { if !db
.rooms
.is_joined(&sender_user, &body.room_id)
.unwrap_or(false)
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"You aren't a member of the room.", "You aren't a member of the room.",
@@ -666,19 +619,14 @@ async fn join_room_by_id_helper(
let mut state = HashMap::new(); let mut state = HashMap::new();
let pub_key_map = RwLock::new(BTreeMap::new()); let pub_key_map = RwLock::new(BTreeMap::new());
server_server::fetch_join_signing_keys( for result in futures::future::join_all(
&send_join_response, send_join_response
&room_version, .room_state
&pub_key_map, .state
&db, .iter()
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map, &db)),
) )
.await?; .await
for result in send_join_response
.room_state
.state
.iter()
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map, &db))
{ {
let (event_id, value) = match result { let (event_id, value) = match result {
Ok(t) => t, Ok(t) => t,
@@ -727,11 +675,14 @@ async fn join_room_by_id_helper(
&db, &db,
)?; )?;
for result in send_join_response for result in futures::future::join_all(
.room_state send_join_response
.auth_chain .room_state
.iter() .auth_chain
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map, &db)) .iter()
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map, &db)),
)
.await
{ {
let (event_id, value) = match result { let (event_id, value) = match result {
Ok(t) => t, Ok(t) => t,
@@ -788,7 +739,7 @@ async fn join_room_by_id_helper(
Ok(join_room_by_id::Response::new(room_id.clone()).into()) Ok(join_room_by_id::Response::new(room_id.clone()).into())
} }
fn validate_and_add_event_id( async fn validate_and_add_event_id(
pdu: &Raw<Pdu>, pdu: &Raw<Pdu>,
room_version: &RoomVersionId, room_version: &RoomVersionId,
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, String>>>, pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, String>>>,
@@ -831,6 +782,7 @@ fn validate_and_add_event_id(
} }
} }
server_server::fetch_required_signing_keys(&value, pub_key_map, db).await?;
if let Err(e) = ruma::signatures::verify_event( if let Err(e) = ruma::signatures::verify_event(
&*pub_key_map &*pub_key_map
.read() .read()
@@ -851,7 +803,7 @@ fn validate_and_add_event_id(
Ok((event_id, value)) Ok((event_id, value))
} }
pub(crate) async fn invite_helper<'a>( pub async fn invite_helper<'a>(
sender_user: &UserId, sender_user: &UserId,
user_id: &UserId, user_id: &UserId,
room_id: &RoomId, room_id: &RoomId,
@@ -1021,14 +973,6 @@ pub(crate) async fn invite_helper<'a>(
(room_version_id, pdu_json, invite_room_state) (room_version_id, pdu_json, invite_room_state)
}; };
// Generate event id
let expected_event_id = EventId::try_from(&*format!(
"${}",
ruma::signatures::reference_hash(&pdu_json, &room_version_id)
.expect("ruma can calculate reference hashes")
))
.expect("ruma's reference hashes are valid event ids");
let response = db let response = db
.sending .sending
.send_federation_request( .send_federation_request(
@@ -1036,9 +980,9 @@ pub(crate) async fn invite_helper<'a>(
user_id.server_name(), user_id.server_name(),
create_invite::v2::Request { create_invite::v2::Request {
room_id: room_id.clone(), room_id: room_id.clone(),
event_id: expected_event_id.clone(), event_id: ruma::event_id!("$receivingservershouldsetthis"),
room_version: room_version_id, room_version: room_version_id,
event: PduEvent::convert_to_outgoing_federation_event(pdu_json.clone()), event: PduEvent::convert_to_outgoing_federation_event(pdu_json),
invite_room_state, invite_room_state,
}, },
) )
@@ -1058,10 +1002,6 @@ pub(crate) async fn invite_helper<'a>(
} }
}; };
if expected_event_id != event_id {
warn!("Server {} changed invite event, that's not allowed in the spec: ours: {:?}, theirs: {:?}", user_id.server_name(), pdu_json, value);
}
let origin = serde_json::from_value::<Box<ServerName>>( let origin = serde_json::from_value::<Box<ServerName>>(
serde_json::to_value(value.get("origin").ok_or(Error::BadRequest( serde_json::to_value(value.get("origin").ok_or(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
-13
View File
@@ -16,13 +16,6 @@ use std::{
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, put}; use rocket::{get, put};
/// # `PUT /_matrix/client/r0/rooms/{roomId}/send/{eventType}/{txnId}`
///
/// Send a message event into the room.
///
/// - Is a NOOP if the txn id was already used before and returns the same event id again
/// - 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 allowed
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/rooms/<_>/send/<_>/<_>", data = "<body>") put("/_matrix/client/r0/rooms/<_>/send/<_>/<_>", data = "<body>")
@@ -99,12 +92,6 @@ pub async fn send_message_event_route(
Ok(send_message_event::Response::new(event_id).into()) Ok(send_message_event::Response::new(event_id).into())
} }
/// # `GET /_matrix/client/r0/rooms/{roomId}/messages`
///
/// Allows paginating through room history.
///
/// - Only works if the user is joined (TODO: always allow, but only show events where the user was
/// joined, depending on history_visibility)
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/messages", data = "<body>") get("/_matrix/client/r0/rooms/<_>/messages", data = "<body>")
-3
View File
@@ -71,9 +71,6 @@ pub const DEVICE_ID_LENGTH: usize = 10;
pub const TOKEN_LENGTH: usize = 256; pub const TOKEN_LENGTH: usize = 256;
pub const SESSION_ID_LENGTH: usize = 256; pub const SESSION_ID_LENGTH: usize = 256;
/// # `OPTIONS`
///
/// Web clients use this to get CORS headers.
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
#[options("/<_..>")] #[options("/<_..>")]
#[tracing::instrument] #[tracing::instrument]
-9
View File
@@ -5,9 +5,6 @@ use std::{convert::TryInto, time::Duration};
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, put}; use rocket::{get, put};
/// # `PUT /_matrix/client/r0/presence/{userId}/status`
///
/// Sets the presence state of the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/presence/<_>/status", data = "<body>") put("/_matrix/client/r0/presence/<_>/status", data = "<body>")
@@ -49,11 +46,6 @@ pub async fn set_presence_route(
Ok(set_presence::Response {}.into()) Ok(set_presence::Response {}.into())
} }
/// # `GET /_matrix/client/r0/presence/{userId}/status`
///
/// Gets the presence state of the given user.
///
/// - Only works if you share a room with the user
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/presence/<_>/status", data = "<body>") get("/_matrix/client/r0/presence/<_>/status", data = "<body>")
@@ -79,7 +71,6 @@ pub async fn get_presence_route(
.get_last_presence_event(&sender_user, &room_id)? .get_last_presence_event(&sender_user, &room_id)?
{ {
presence_event = Some(presence); presence_event = Some(presence);
break;
} }
} }
+12 -39
View File
@@ -17,11 +17,6 @@ use std::{convert::TryInto, sync::Arc};
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, put}; use rocket::{get, put};
/// # `PUT /_matrix/client/r0/profile/{userId}/displayname`
///
/// Updates the displayname.
///
/// - Also makes sure other users receive the update using presence EDUs
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/profile/<_>/displayname", data = "<body>") put("/_matrix/client/r0/profile/<_>/displayname", data = "<body>")
@@ -37,9 +32,10 @@ pub async fn set_displayname_route(
.set_displayname(&sender_user, body.displayname.clone())?; .set_displayname(&sender_user, body.displayname.clone())?;
// 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<_> = db let all_rooms_joined = db.rooms.rooms_joined(&sender_user).collect::<Vec<_>>();
.rooms
.rooms_joined(&sender_user) for (pdu_builder, room_id) in all_rooms_joined
.into_iter()
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
@@ -57,7 +53,7 @@ pub async fn set_displayname_route(
.ok_or_else(|| { .ok_or_else(|| {
Error::bad_database( Error::bad_database(
"Tried to send displayname update for user not in the \ "Tried to send displayname update for user not in the \
room.", room.",
) )
})? })?
.content .content
@@ -76,9 +72,7 @@ pub async fn set_displayname_route(
)) ))
}) })
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.collect(); {
for (pdu_builder, room_id) in all_rooms_joined {
let mutex_state = Arc::clone( let mutex_state = Arc::clone(
db.globals db.globals
.roomid_mutex_state .roomid_mutex_state
@@ -121,11 +115,6 @@ pub async fn set_displayname_route(
Ok(set_display_name::Response {}.into()) Ok(set_display_name::Response {}.into())
} }
/// # `GET /_matrix/client/r0/profile/{userId}/displayname`
///
/// Returns the displayname of the user.
///
/// - If user is on another server: Fetches displayname over federation
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/profile/<_>/displayname", data = "<body>") get("/_matrix/client/r0/profile/<_>/displayname", data = "<body>")
@@ -160,11 +149,6 @@ pub async fn get_displayname_route(
.into()) .into())
} }
/// # `PUT /_matrix/client/r0/profile/{userId}/avatar_url`
///
/// Updates the avatar_url and blurhash.
///
/// - Also makes sure other users receive the update using presence EDUs
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/profile/<_>/avatar_url", data = "<body>") put("/_matrix/client/r0/profile/<_>/avatar_url", data = "<body>")
@@ -182,9 +166,10 @@ pub async fn set_avatar_url_route(
db.users.set_blurhash(&sender_user, body.blurhash.clone())?; db.users.set_blurhash(&sender_user, body.blurhash.clone())?;
// 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<_> = db let all_joined_rooms = db.rooms.rooms_joined(&sender_user).collect::<Vec<_>>();
.rooms
.rooms_joined(&sender_user) for (pdu_builder, room_id) in all_joined_rooms
.into_iter()
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
@@ -202,7 +187,7 @@ pub async fn set_avatar_url_route(
.ok_or_else(|| { .ok_or_else(|| {
Error::bad_database( Error::bad_database(
"Tried to send displayname update for user not in the \ "Tried to send displayname update for user not in the \
room.", room.",
) )
})? })?
.content .content
@@ -221,9 +206,7 @@ pub async fn set_avatar_url_route(
)) ))
}) })
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.collect(); {
for (pdu_builder, room_id) in all_joined_rooms {
let mutex_state = Arc::clone( let mutex_state = Arc::clone(
db.globals db.globals
.roomid_mutex_state .roomid_mutex_state
@@ -266,11 +249,6 @@ pub async fn set_avatar_url_route(
Ok(set_avatar_url::Response {}.into()) Ok(set_avatar_url::Response {}.into())
} }
/// # `GET /_matrix/client/r0/profile/{userId}/avatar_url`
///
/// Returns the avatar_url and blurhash of the user.
///
/// - If user is on another server: Fetches avatar_url and blurhash over federation
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/profile/<_>/avatar_url", data = "<body>") get("/_matrix/client/r0/profile/<_>/avatar_url", data = "<body>")
@@ -307,11 +285,6 @@ pub async fn get_avatar_url_route(
.into()) .into())
} }
/// # `GET /_matrix/client/r0/profile/{userId}`
///
/// Returns the displayname, avatar_url and blurhash of the user.
///
/// - If user is on another server: Fetches profile over federation
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/profile/<_>", data = "<body>") get("/_matrix/client/r0/profile/<_>", data = "<body>")
-32
View File
@@ -15,9 +15,6 @@ use ruma::{
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{delete, get, post, put}; use rocket::{delete, get, post, put};
/// # `GET /_matrix/client/r0/pushrules`
///
/// Retrieves the push rules event for this user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/pushrules", data = "<body>") get("/_matrix/client/r0/pushrules", data = "<body>")
@@ -43,9 +40,6 @@ pub async fn get_pushrules_all_route(
.into()) .into())
} }
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
///
/// Retrieves a single specified push rule for this user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/pushrules/<_>/<_>/<_>", data = "<body>") get("/_matrix/client/r0/pushrules/<_>/<_>/<_>", data = "<body>")
@@ -100,9 +94,6 @@ pub async fn get_pushrule_route(
} }
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
///
/// Creates a single specified push rule for this user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/pushrules/<_>/<_>/<_>", data = "<req>") put("/_matrix/client/r0/pushrules/<_>/<_>/<_>", data = "<req>")
@@ -206,9 +197,6 @@ pub async fn set_pushrule_route(
Ok(set_pushrule::Response {}.into()) Ok(set_pushrule::Response {}.into())
} }
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions`
///
/// Gets the actions of a single specified push rule for this user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/pushrules/<_>/<_>/<_>/actions", data = "<body>") get("/_matrix/client/r0/pushrules/<_>/<_>/<_>/actions", data = "<body>")
@@ -268,9 +256,6 @@ pub async fn get_pushrule_actions_route(
.into()) .into())
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions`
///
/// Sets the actions of a single specified push rule for this user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/pushrules/<_>/<_>/<_>/actions", data = "<body>") put("/_matrix/client/r0/pushrules/<_>/<_>/<_>/actions", data = "<body>")
@@ -345,9 +330,6 @@ pub async fn set_pushrule_actions_route(
Ok(set_pushrule_actions::Response {}.into()) Ok(set_pushrule_actions::Response {}.into())
} }
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled`
///
/// Gets the enabled status of a single specified push rule for this user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/pushrules/<_>/<_>/<_>/enabled", data = "<body>") get("/_matrix/client/r0/pushrules/<_>/<_>/<_>/enabled", data = "<body>")
@@ -409,9 +391,6 @@ pub async fn get_pushrule_enabled_route(
Ok(get_pushrule_enabled::Response { enabled }.into()) Ok(get_pushrule_enabled::Response { enabled }.into())
} }
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled`
///
/// Sets the enabled status of a single specified push rule for this user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/pushrules/<_>/<_>/<_>/enabled", data = "<body>") put("/_matrix/client/r0/pushrules/<_>/<_>/<_>/enabled", data = "<body>")
@@ -491,9 +470,6 @@ pub async fn set_pushrule_enabled_route(
Ok(set_pushrule_enabled::Response {}.into()) Ok(set_pushrule_enabled::Response {}.into())
} }
/// # `DELETE /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
///
/// Deletes a single specified push rule for this user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
delete("/_matrix/client/r0/pushrules/<_>/<_>/<_>", data = "<body>") delete("/_matrix/client/r0/pushrules/<_>/<_>/<_>", data = "<body>")
@@ -563,9 +539,6 @@ pub async fn delete_pushrule_route(
Ok(delete_pushrule::Response {}.into()) Ok(delete_pushrule::Response {}.into())
} }
/// # `GET /_matrix/client/r0/pushers`
///
/// Gets all currently active pushers for the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/pushers", data = "<body>") get("/_matrix/client/r0/pushers", data = "<body>")
@@ -583,11 +556,6 @@ pub async fn get_pushers_route(
.into()) .into())
} }
/// # `POST /_matrix/client/r0/pushers/set`
///
/// Adds a pusher for the sender user.
///
/// - TODO: Handle `append`
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/pushers/set", data = "<body>") post("/_matrix/client/r0/pushers/set", data = "<body>")
-9
View File
@@ -13,12 +13,6 @@ use std::collections::BTreeMap;
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::post; use rocket::post;
/// # `POST /_matrix/client/r0/rooms/{roomId}/read_markers`
///
/// Sets different types of read markers.
///
/// - Updates fully-read account data event to `fully_read`
/// - If `read_receipt` is set: Update private marker and public read receipt EDU
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/read_markers", data = "<body>") post("/_matrix/client/r0/rooms/<_>/read_markers", data = "<body>")
@@ -86,9 +80,6 @@ pub async fn set_read_marker_route(
Ok(set_read_marker::Response {}.into()) Ok(set_read_marker::Response {}.into())
} }
/// # `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}`
///
/// Sets private read marker and public read receipt EDU.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/receipt/<_>/<_>", data = "<body>") post("/_matrix/client/r0/rooms/<_>/receipt/<_>/<_>", data = "<body>")
-5
View File
@@ -9,11 +9,6 @@ use ruma::{
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::put; use rocket::put;
/// # `PUT /_matrix/client/r0/rooms/{roomId}/redact/{eventId}/{txnId}`
///
/// Tries to send a redaction event into the room.
///
/// - TODO: Handle txn id
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/rooms/<_>/redact/<_>/<_>", data = "<body>") put("/_matrix/client/r0/rooms/<_>/redact/<_>/<_>", data = "<body>")
-36
View File
@@ -20,22 +20,6 @@ use tracing::{info, warn};
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, post}; use rocket::{get, post};
/// # `POST /_matrix/client/r0/createRoom`
///
/// Creates a new room.
///
/// - Room ID is randomly generated
/// - Create alias if room_alias_name is set
/// - Send create event
/// - Join sender user
/// - Send power levels event
/// - Send canonical room alias
/// - Send join rules
/// - Send history visibility
/// - Send guest access
/// - Send events listed in initial state
/// - Send events implied by `name` and `topic`
/// - Send invite events
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/createRoom", data = "<body>") post("/_matrix/client/r0/createRoom", data = "<body>")
@@ -360,11 +344,6 @@ pub async fn create_room_route(
Ok(create_room::Response::new(room_id).into()) Ok(create_room::Response::new(room_id).into())
} }
/// # `GET /_matrix/client/r0/rooms/{roomId}/event/{eventId}`
///
/// Gets a single event.
///
/// - You have to currently be joined to the room (TODO: Respect history visibility)
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/event/<_>", data = "<body>") get("/_matrix/client/r0/rooms/<_>/event/<_>", data = "<body>")
@@ -393,11 +372,6 @@ pub async fn get_room_event_route(
.into()) .into())
} }
/// # `GET /_matrix/client/r0/rooms/{roomId}/aliases`
///
/// Lists all aliases of the room.
///
/// - Only users joined to the room are allowed to call this TODO: Allow any user to call it if history_visibility is world readable
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/aliases", data = "<body>") get("/_matrix/client/r0/rooms/<_>/aliases", data = "<body>")
@@ -426,16 +400,6 @@ pub async fn get_room_aliases_route(
.into()) .into())
} }
/// # `GET /_matrix/client/r0/rooms/{roomId}/upgrade`
///
/// Upgrades the room.
///
/// - Creates a replacement room
/// - Sends a tombstone event into the current room
/// - Sender user joins the room
/// - Transfers some state events
/// - Moves local aliases
/// - Modifies old room power levels to prevent users from speaking
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/upgrade", data = "<body>") post("/_matrix/client/r0/rooms/<_>/upgrade", data = "<body>")
-5
View File
@@ -6,11 +6,6 @@ use rocket::post;
use search_events::{EventContextResult, ResultCategories, ResultRoomEvents, SearchResult}; use search_events::{EventContextResult, ResultCategories, ResultRoomEvents, SearchResult};
use std::collections::BTreeMap; use std::collections::BTreeMap;
/// # `POST /_matrix/client/r0/search`
///
/// Searches rooms for messages.
///
/// - Only works if the user is currently joined to the room (TODO: Respect history visibility)
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/search", data = "<body>") post("/_matrix/client/r0/search", data = "<body>")
+7 -12
View File
@@ -24,7 +24,7 @@ use rocket::{get, post};
/// # `GET /_matrix/client/r0/login` /// # `GET /_matrix/client/r0/login`
/// ///
/// Get the supported login types of this server. One of these should be used as the `type` field /// Get the homeserver's supported login types. One of these should be used as the `type` field
/// when logging in. /// when logging in.
#[cfg_attr(feature = "conduit_bin", get("/_matrix/client/r0/login"))] #[cfg_attr(feature = "conduit_bin", get("/_matrix/client/r0/login"))]
#[tracing::instrument] #[tracing::instrument]
@@ -41,10 +41,9 @@ pub async fn get_login_types_route() -> ConduitResult<get_login_types::Response>
/// ///
/// Authenticates the user and returns an access token it can use in subsequent requests. /// Authenticates the user and returns an access token it can use in subsequent requests.
/// ///
/// - The user needs to authenticate using their password (or if enabled using a json web token) /// - The returned access token is associated with the user and device
/// - If `device_id` is known: invalidates old access token of that device /// - Old access tokens of that device should be invalidated
/// - If `device_id` is unknown: creates a new device /// - If `device_id` is unknown, a new device will be created
/// - Returns access token that is associated with the user and device
/// ///
/// Note: You can use [`GET /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see /// Note: You can use [`GET /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see
/// supported login types. /// supported login types.
@@ -163,10 +162,8 @@ pub async fn login_route(
/// ///
/// Log out the current device. /// Log out the current device.
/// ///
/// - Invalidates access token /// - Invalidates the access token
/// - Deletes device metadata (device id, device display name, last seen ip, last seen ts) /// - Deletes the device and most of it's data (to-device events, last seen, etc.)
/// - Forgets to-device events
/// - Triggers device list updates
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/logout", data = "<body>") post("/_matrix/client/r0/logout", data = "<body>")
@@ -191,9 +188,7 @@ pub async fn logout_route(
/// 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, last seen ts) /// - Deletes devices and most of their data (to-device events, last seen, etc.)
/// - Forgets all to-device events
/// - Triggers device list updates
/// ///
/// Note: This is equivalent to calling [`GET /_matrix/client/r0/logout`](fn.logout_route.html) /// Note: This is equivalent to calling [`GET /_matrix/client/r0/logout`](fn.logout_route.html)
/// from each device of this user. /// from each device of this user.
+1 -32
View File
@@ -22,13 +22,6 @@ use ruma::{
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, put}; use rocket::{get, put};
/// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}`
///
/// Sends a state event into the room.
///
/// - 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 allowed
/// - If event is new canonical_alias: Rejects if alias is incorrect
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/rooms/<_>/state/<_>/<_>", data = "<body>") put("/_matrix/client/r0/rooms/<_>/state/<_>/<_>", data = "<body>")
@@ -55,13 +48,6 @@ pub async fn send_state_event_for_key_route(
Ok(send_state_event::Response { event_id }.into()) Ok(send_state_event::Response { event_id }.into())
} }
/// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}`
///
/// Sends a state event into the room.
///
/// - 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 allowed
/// - If event is new canonical_alias: Rejects if alias is incorrect
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/rooms/<_>/state/<_>", data = "<body>") put("/_matrix/client/r0/rooms/<_>/state/<_>", data = "<body>")
@@ -88,11 +74,6 @@ pub async fn send_state_event_for_empty_key_route(
Ok(send_state_event::Response { event_id }.into()) Ok(send_state_event::Response { event_id }.into())
} }
/// # `GET /_matrix/client/r0/rooms/{roomid}/state`
///
/// Get all state events for a room.
///
/// - If not joined: Only works if current room history visibility is world readable
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/state", data = "<body>") get("/_matrix/client/r0/rooms/<_>/state", data = "<body>")
@@ -140,11 +121,6 @@ pub async fn get_state_events_route(
.into()) .into())
} }
/// # `GET /_matrix/client/r0/rooms/{roomid}/state/{eventType}/{stateKey}`
///
/// Get single state event of a room.
///
/// - If not joined: Only works if current room history visibility is world readable
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/state/<_>/<_>", data = "<body>") get("/_matrix/client/r0/rooms/<_>/state/<_>/<_>", data = "<body>")
@@ -196,11 +172,6 @@ pub async fn get_state_events_for_key_route(
.into()) .into())
} }
/// # `GET /_matrix/client/r0/rooms/{roomid}/state/{eventType}`
///
/// Get single state event of a room.
///
/// - If not joined: Only works if current room history visibility is world readable
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/state/<_>", data = "<body>") get("/_matrix/client/r0/rooms/<_>/state/<_>", data = "<body>")
@@ -252,7 +223,7 @@ pub async fn get_state_events_for_empty_key_route(
.into()) .into())
} }
async fn send_state_event_for_key_helper( pub async fn send_state_event_for_key_helper(
db: &Database, db: &Database,
sender: &UserId, sender: &UserId,
room_id: &RoomId, room_id: &RoomId,
@@ -262,8 +233,6 @@ async fn send_state_event_for_key_helper(
) -> Result<EventId> { ) -> Result<EventId> {
let sender_user = sender; let sender_user = sender;
// TODO: Review this check, error if event is unparsable, use event type, allow alias if it
// previously existed
if let Ok(canonical_alias) = if let Ok(canonical_alias) =
serde_json::from_str::<CanonicalAliasEventContent>(json.json().get()) serde_json::from_str::<CanonicalAliasEventContent>(json.json().get())
{ {
+98 -67
View File
@@ -12,7 +12,7 @@ use std::{
time::Duration, time::Duration,
}; };
use tokio::sync::watch::Sender; use tokio::sync::watch::Sender;
use tracing::error; use tracing::{error, warn};
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{get, tokio}; use rocket::{get, tokio};
@@ -22,33 +22,12 @@ use rocket::{get, tokio};
/// Synchronize the client's state with the latest state on the server. /// Synchronize the client's state with the latest state on the server.
/// ///
/// - This endpoint takes a `since` parameter which should be the `next_batch` value from a /// - This endpoint takes a `since` parameter which should be the `next_batch` value from a
/// previous request for incremental syncs. /// previous request.
/// /// - Calling this endpoint without a `since` parameter will return all recent events, the state
/// Calling this endpoint without a `since` parameter returns: /// of all rooms and more data. This should only be called on the initial login of the device.
/// - Some of the most recent events of each timeline /// - To get incremental updates, you can call this endpoint with a `since` parameter. This will
/// - Notification counts for each room /// return all recent events, state updates and more data that happened since the last /sync
/// - Joined and invited member counts, heroes /// request.
/// - All state events
///
/// Calling this endpoint with a `since` parameter from a previous `next_batch` returns:
/// For joined rooms:
/// - Some of the most recent events of each timeline that happened after since
/// - If user joined the room after since: All state events and device list updates in that room
/// - If the user was already in the room: A list of all events that are in the state now, but were
/// not in the state at `since`
/// - If the state we send contains a member event: Joined and invited member counts, heroes
/// - Device list updates that happened after `since`
/// - If there are events in the timeline we send or the user send updated his read mark: Notification counts
/// - EDUs that are active now (read receipts, typing updates, presence)
///
/// For invited rooms:
/// - If the user was invited after `since`: A subset of the state of the room at the point of the invite
///
/// For left rooms:
/// - If the user left after `since`: prev_batch token, empty state (TODO: subset of the state at the point of the leave)
///
/// - Sync is handled in an async task, multiple requests from the same device with the same
/// `since` will be cached
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/sync", data = "<body>") get("/_matrix/client/r0/sync", data = "<body>")
@@ -127,7 +106,7 @@ pub async fn sync_events_route(
result result
} }
async fn sync_helper_wrapper( pub async fn sync_helper_wrapper(
db: Arc<DatabaseGuard>, db: Arc<DatabaseGuard>,
sender_user: UserId, sender_user: UserId,
sender_device: Box<DeviceId>, sender_device: Box<DeviceId>,
@@ -267,12 +246,36 @@ async fn sync_helper(
.current_shortstatehash(&room_id)? .current_shortstatehash(&room_id)?
.expect("All rooms have state"); .expect("All rooms have state");
let since_shortstatehash = db.rooms.get_token_shortstatehash(&room_id, since)?; let first_pdu_before_since = db
.rooms
.pdus_until(&sender_user, &room_id, since)?
.next()
.transpose()?;
let pdus_after_since = db
.rooms
.pdus_after(&sender_user, &room_id, since)?
.next()
.is_some();
let since_shortstatehash = first_pdu_before_since
.as_ref()
.map(|pdu| {
db.rooms
.pdu_shortstatehash(&pdu.1.event_id)
.transpose()
.ok_or_else(|| {
warn!("PDU without state: {}", pdu.1.event_id);
Error::bad_database("Found PDU without state")
})
})
.transpose()?
.transpose()?;
// Calculates joined_member_count, invited_member_count and heroes // Calculates joined_member_count, invited_member_count and heroes
let calculate_counts = || { let calculate_counts = || {
let joined_member_count = db.rooms.room_joined_count(&room_id)?.unwrap_or(0); let joined_member_count = db.rooms.room_members(&room_id).count();
let invited_member_count = db.rooms.room_invited_count(&room_id)?.unwrap_or(0); let invited_member_count = db.rooms.room_members_invited(&room_id).count();
// Recalculate heroes (first 5 members) // Recalculate heroes (first 5 members)
let mut heroes = Vec::new(); let mut heroes = Vec::new();
@@ -356,7 +359,7 @@ async fn sync_helper(
true, true,
state_events, state_events,
) )
} else if timeline_pdus.is_empty() && since_shortstatehash == Some(current_shortstatehash) { } else if !pdus_after_since || since_shortstatehash == Some(current_shortstatehash) {
// No state changes // No state changes
(Vec::new(), None, None, false, Vec::new()) (Vec::new(), None, None, false, Vec::new())
} else { } else {
@@ -397,6 +400,11 @@ async fn sync_helper(
current_state_ids current_state_ids
.iter() .iter()
.filter(|(key, id)| since_state_ids.get(key) != Some(id)) .filter(|(key, id)| since_state_ids.get(key) != Some(id))
.filter(|(_, id)| {
!timeline_pdus
.iter()
.any(|(_, timeline_pdu)| timeline_pdu.event_id == **id)
})
.map(|(_, id)| db.rooms.get_pdu(id)) .map(|(_, id)| db.rooms.get_pdu(id))
.filter_map(|r| r.ok().flatten()) .filter_map(|r| r.ok().flatten())
.collect() .collect()
@@ -416,43 +424,70 @@ async fn sync_helper(
let send_member_count = state_events let send_member_count = state_events
.iter() .iter()
.any(|event| event.kind == EventType::RoomMember); .any(|event| event.kind == EventType::RoomMember)
|| timeline_pdus.iter().any(|(_, event)| {
event.state_key.is_some() && event.kind == EventType::RoomMember
});
if encrypted_room { if encrypted_room {
for state_event in &state_events { for (user_id, current_member) in db
if state_event.kind != EventType::RoomMember { .rooms
continue; .room_members(&room_id)
} .filter_map(|r| r.ok())
.filter_map(|user_id| {
db.rooms
.state_get(
current_shortstatehash,
&EventType::RoomMember,
user_id.as_str(),
)
.ok()
.flatten()
.map(|current_member| (user_id, current_member))
})
{
let current_membership = serde_json::from_value::<
Raw<ruma::events::room::member::MemberEventContent>,
>(current_member.content.clone())
.expect("Raw::from_value always works")
.deserialize()
.map_err(|_| Error::bad_database("Invalid PDU in database."))?
.membership;
if let Some(state_key) = &state_event.state_key { let since_membership = db
let user_id = UserId::try_from(state_key.clone()) .rooms
.map_err(|_| Error::bad_database("Invalid UserId in member PDU."))?; .state_get(
since_shortstatehash,
&EventType::RoomMember,
user_id.as_str(),
)?
.and_then(|since_member| {
serde_json::from_value::<
Raw<ruma::events::room::member::MemberEventContent>,
>(since_member.content.clone())
.expect("Raw::from_value always works")
.deserialize()
.map_err(|_| Error::bad_database("Invalid PDU in database."))
.ok()
})
.map_or(MembershipState::Leave, |member| member.membership);
if user_id == sender_user { let user_id = UserId::try_from(user_id.clone())
continue; .map_err(|_| Error::bad_database("Invalid UserId in member PDU."))?;
}
let new_membership = serde_json::from_value::< match (since_membership, current_membership) {
Raw<ruma::events::room::member::MemberEventContent>, (MembershipState::Leave, MembershipState::Join) => {
>(state_event.content.clone()) // A new user joined an encrypted room
.expect("Raw::from_value always works") if !share_encrypted_room(&db, &sender_user, &user_id, &room_id)? {
.deserialize() device_list_updates.insert(user_id);
.map_err(|_| Error::bad_database("Invalid PDU in database."))?
.membership;
match new_membership {
MembershipState::Join => {
// A new user joined an encrypted room
if !share_encrypted_room(&db, &sender_user, &user_id, &room_id)? {
device_list_updates.insert(user_id);
}
} }
MembershipState::Leave => {
// Write down users that have left encrypted rooms we are in
left_encrypted_users.insert(user_id);
}
_ => {}
} }
// TODO: Remove, this should never happen here, right?
(MembershipState::Join, MembershipState::Leave) => {
// Write down users that have left encrypted rooms we are in
left_encrypted_users.insert(user_id);
}
_ => {}
} }
} }
} }
@@ -550,10 +585,6 @@ async fn sync_helper(
); );
} }
// Save the state after this sync so we can send the correct state diff next sync
db.rooms
.associate_token_shortstatehash(&room_id, next_batch, current_shortstatehash)?;
let joined_room = sync_events::JoinedRoom { let joined_room = sync_events::JoinedRoom {
account_data: sync_events::RoomAccountData { account_data: sync_events::RoomAccountData {
events: db events: db
-15
View File
@@ -8,11 +8,6 @@ use std::collections::BTreeMap;
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::{delete, get, put}; use rocket::{delete, get, put};
/// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}`
///
/// Adds a tag to the room.
///
/// - Inserts the tag into the tag event of the room account data.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/user/<_>/rooms/<_>/tags/<_>", data = "<body>") put("/_matrix/client/r0/user/<_>/rooms/<_>/tags/<_>", data = "<body>")
@@ -50,11 +45,6 @@ pub async fn update_tag_route(
Ok(create_tag::Response {}.into()) Ok(create_tag::Response {}.into())
} }
/// # `DELETE /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags/{tag}`
///
/// Deletes a tag from the room.
///
/// - Removes the tag from the tag event of the room account data.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
delete("/_matrix/client/r0/user/<_>/rooms/<_>/tags/<_>", data = "<body>") delete("/_matrix/client/r0/user/<_>/rooms/<_>/tags/<_>", data = "<body>")
@@ -89,11 +79,6 @@ pub async fn delete_tag_route(
Ok(delete_tag::Response {}.into()) Ok(delete_tag::Response {}.into())
} }
/// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/tags`
///
/// Returns tags on the room.
///
/// - Gets the tag event of the room account data.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/user/<_>/rooms/<_>/tags", data = "<body>") get("/_matrix/client/r0/user/<_>/rooms/<_>/tags", data = "<body>")
-3
View File
@@ -5,9 +5,6 @@ use ruma::api::client::r0::thirdparty::get_protocols;
use rocket::get; use rocket::get;
use std::collections::BTreeMap; use std::collections::BTreeMap;
/// # `GET /_matrix/client/r0/thirdparty/protocols`
///
/// TODO: Fetches all metadata about protocols supported by the homeserver.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
get("/_matrix/client/r0/thirdparty/protocols") get("/_matrix/client/r0/thirdparty/protocols")
-4
View File
@@ -13,9 +13,6 @@ use ruma::{
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::put; use rocket::put;
/// # `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}`
///
/// Send a to-device event to a set of client devices.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/sendToDevice/<_>/<_>", data = "<body>") put("/_matrix/client/r0/sendToDevice/<_>/<_>", data = "<body>")
@@ -59,7 +56,6 @@ pub async fn send_event_to_device_route(
}, },
)) ))
.expect("DirectToDevice EDU can be serialized"), .expect("DirectToDevice EDU can be serialized"),
db.globals.next_count()?,
)?; )?;
continue; continue;
-3
View File
@@ -5,9 +5,6 @@ use ruma::api::client::r0::typing::create_typing_event;
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::put; use rocket::put;
/// # `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}`
///
/// Sets the typing state of the sender user.
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
put("/_matrix/client/r0/rooms/<_>/typing/<_>", data = "<body>") put("/_matrix/client/r0/rooms/<_>/typing/<_>", data = "<body>")
+1 -1
View File
@@ -10,7 +10,7 @@ use rocket::get;
/// ///
/// - 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 their name /// - Unstable features should be namespaced and may include version information in their name
/// ///
/// Note: Unstable features are used while developing new features. Clients should avoid using /// Note: Unstable features are used while developing new features. Clients should avoid using
/// unstable features in their stable releases /// unstable features in their stable releases
-5
View File
@@ -4,11 +4,6 @@ use ruma::api::client::r0::user_directory::search_users;
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::post; use rocket::post;
/// # `POST /_matrix/client/r0/user_directory/search`
///
/// Searches all known users for a match.
///
/// - TODO: Hide users that are not in any public rooms?
#[cfg_attr( #[cfg_attr(
feature = "conduit_bin", feature = "conduit_bin",
post("/_matrix/client/r0/user_directory/search", data = "<body>") post("/_matrix/client/r0/user_directory/search", data = "<body>")
-3
View File
@@ -5,9 +5,6 @@ use std::time::Duration;
#[cfg(feature = "conduit_bin")] #[cfg(feature = "conduit_bin")]
use rocket::get; use rocket::get;
/// # `GET /_matrix/client/r0/voip/turnServer`
///
/// TODO: Returns information about the recommended turn server.
#[cfg_attr(feature = "conduit_bin", get("/_matrix/client/r0/voip/turnServer"))] #[cfg_attr(feature = "conduit_bin", get("/_matrix/client/r0/voip/turnServer"))]
#[tracing::instrument] #[tracing::instrument]
pub async fn turn_server_route() -> ConduitResult<get_turn_server_info::Response> { pub async fn turn_server_route() -> ConduitResult<get_turn_server_info::Response> {
+8 -31
View File
@@ -47,15 +47,13 @@ pub struct Config {
database_path: String, database_path: String,
#[serde(default = "default_db_cache_capacity_mb")] #[serde(default = "default_db_cache_capacity_mb")]
db_cache_capacity_mb: f64, db_cache_capacity_mb: f64,
#[serde(default = "default_pdu_cache_capacity")]
pdu_cache_capacity: u32,
#[serde(default = "default_sqlite_wal_clean_second_interval")] #[serde(default = "default_sqlite_wal_clean_second_interval")]
sqlite_wal_clean_second_interval: u32, sqlite_wal_clean_second_interval: u32,
#[serde(default = "default_max_request_size")] #[serde(default = "default_max_request_size")]
max_request_size: u32, max_request_size: u32,
#[serde(default = "default_max_concurrent_requests")] #[serde(default = "default_max_concurrent_requests")]
max_concurrent_requests: u16, max_concurrent_requests: u16,
#[serde(default = "false_fn")] #[serde(default = "true_fn")]
allow_registration: bool, allow_registration: bool,
#[serde(default = "true_fn")] #[serde(default = "true_fn")]
allow_encryption: bool, allow_encryption: bool,
@@ -109,10 +107,6 @@ fn default_db_cache_capacity_mb() -> f64 {
200.0 200.0
} }
fn default_pdu_cache_capacity() -> u32 {
100_000
}
fn default_sqlite_wal_clean_second_interval() -> u32 { fn default_sqlite_wal_clean_second_interval() -> u32 {
1 * 60 // every minute 1 * 60 // every minute
} }
@@ -258,7 +252,6 @@ impl Database {
userroomid_joined: builder.open_tree("userroomid_joined")?, userroomid_joined: builder.open_tree("userroomid_joined")?,
roomuserid_joined: builder.open_tree("roomuserid_joined")?, roomuserid_joined: builder.open_tree("roomuserid_joined")?,
roomid_joinedcount: builder.open_tree("roomid_joinedcount")?, roomid_joinedcount: builder.open_tree("roomid_joinedcount")?,
roomid_invitedcount: builder.open_tree("roomid_invitedcount")?,
roomuseroncejoinedids: builder.open_tree("roomuseroncejoinedids")?, roomuseroncejoinedids: builder.open_tree("roomuseroncejoinedids")?,
userroomid_invitestate: builder.open_tree("userroomid_invitestate")?, userroomid_invitestate: builder.open_tree("userroomid_invitestate")?,
roomuserid_invitecount: builder.open_tree("roomuserid_invitecount")?, roomuserid_invitecount: builder.open_tree("roomuserid_invitecount")?,
@@ -271,8 +264,6 @@ impl Database {
statekey_shortstatekey: builder.open_tree("statekey_shortstatekey")?, statekey_shortstatekey: builder.open_tree("statekey_shortstatekey")?,
shortstatekey_statekey: builder.open_tree("shortstatekey_statekey")?, shortstatekey_statekey: builder.open_tree("shortstatekey_statekey")?,
shorteventid_authchain: builder.open_tree("shorteventid_authchain")?,
roomid_shortroomid: builder.open_tree("roomid_shortroomid")?, roomid_shortroomid: builder.open_tree("roomid_shortroomid")?,
shortstatehash_statediff: builder.open_tree("shortstatehash_statediff")?, shortstatehash_statediff: builder.open_tree("shortstatehash_statediff")?,
@@ -280,26 +271,16 @@ impl Database {
shorteventid_eventid: builder.open_tree("shorteventid_eventid")?, shorteventid_eventid: builder.open_tree("shorteventid_eventid")?,
shorteventid_shortstatehash: builder.open_tree("shorteventid_shortstatehash")?, shorteventid_shortstatehash: builder.open_tree("shorteventid_shortstatehash")?,
roomid_shortstatehash: builder.open_tree("roomid_shortstatehash")?, roomid_shortstatehash: builder.open_tree("roomid_shortstatehash")?,
roomsynctoken_shortstatehash: builder.open_tree("roomsynctoken_shortstatehash")?,
statehash_shortstatehash: builder.open_tree("statehash_shortstatehash")?, statehash_shortstatehash: builder.open_tree("statehash_shortstatehash")?,
eventid_outlierpdu: builder.open_tree("eventid_outlierpdu")?, eventid_outlierpdu: builder.open_tree("eventid_outlierpdu")?,
softfailedeventids: builder.open_tree("softfailedeventids")?,
referencedevents: builder.open_tree("referencedevents")?, referencedevents: builder.open_tree("referencedevents")?,
pdu_cache: Mutex::new(LruCache::new( pdu_cache: Mutex::new(LruCache::new(100_000)),
config auth_chain_cache: Mutex::new(LruCache::new(100_000)),
.pdu_cache_capacity
.try_into()
.expect("pdu cache capacity fits into usize"),
)),
auth_chain_cache: Mutex::new(LruCache::new(1_000_000)),
shorteventid_cache: Mutex::new(LruCache::new(1_000_000)), shorteventid_cache: Mutex::new(LruCache::new(1_000_000)),
eventidshort_cache: Mutex::new(LruCache::new(1_000_000)), eventidshort_cache: Mutex::new(LruCache::new(1_000_000)),
shortstatekey_cache: Mutex::new(LruCache::new(1_000_000)), shortstatekey_cache: Mutex::new(LruCache::new(1_000_000)),
statekeyshort_cache: Mutex::new(LruCache::new(1_000_000)), statekeyshort_cache: Mutex::new(LruCache::new(1_000_000)),
our_real_users_cache: RwLock::new(HashMap::new()),
appservice_in_room_cache: RwLock::new(HashMap::new()),
stateinfo_cache: Mutex::new(LruCache::new(1000)), stateinfo_cache: Mutex::new(LruCache::new(1000)),
}, },
account_data: account_data::AccountData { account_data: account_data::AccountData {
@@ -458,7 +439,7 @@ impl Database {
let room_id = let room_id =
RoomId::try_from(utils::string_from_bytes(&roomid).unwrap()).unwrap(); RoomId::try_from(utils::string_from_bytes(&roomid).unwrap()).unwrap();
db.rooms.update_joined_count(&room_id, &db)?; db.rooms.update_joined_count(&room_id)?;
} }
db.globals.bump_database_version(6)?; db.globals.bump_database_version(6)?;
@@ -655,7 +636,7 @@ impl Database {
if db.globals.database_version()? < 9 { if db.globals.database_version()? < 9 {
// Update tokenids db layout // Update tokenids db layout
let mut iter = db let batch = db
.rooms .rooms
.tokenids .tokenids
.iter() .iter()
@@ -683,7 +664,9 @@ impl Database {
println!("new {:?}", new_key); println!("new {:?}", new_key);
Some((new_key, Vec::new())) Some((new_key, Vec::new()))
}) })
.peekable(); .collect::<Vec<_>>();
let mut iter = batch.into_iter().peekable();
while iter.peek().is_some() { while iter.peek().is_some() {
db.rooms db.rooms
@@ -726,12 +709,6 @@ impl Database {
.insert(&shortstatekey, &statekey)?; .insert(&shortstatekey, &statekey)?;
} }
// Force E2EE device list updates so we can send them over federation
for user_id in db.users.iter().filter_map(|r| r.ok()) {
db.users
.mark_device_key_update(&user_id, &db.rooms, &db.globals)?;
}
db.globals.bump_database_version(10)?; db.globals.bump_database_version(10)?;
println!("Migration: 9 -> 10 finished"); println!("Migration: 9 -> 10 finished");
+35 -35
View File
@@ -10,7 +10,6 @@ use std::{
pin::Pin, pin::Pin,
sync::Arc, sync::Arc,
}; };
use thread_local::ThreadLocal;
use tokio::sync::oneshot::Sender; use tokio::sync::oneshot::Sender;
use tracing::debug; use tracing::debug;
@@ -41,8 +40,6 @@ impl<T> Drop for NonAliasingBox<T> {
pub struct Engine { pub struct Engine {
writer: Mutex<Connection>, writer: Mutex<Connection>,
read_conn_tls: ThreadLocal<Connection>,
read_iterator_conn_tls: ThreadLocal<Connection>,
path: PathBuf, path: PathBuf,
cache_size_per_thread: u32, cache_size_per_thread: u32,
@@ -65,19 +62,40 @@ impl Engine {
self.writer.lock() self.writer.lock()
} }
fn read_lock(&self) -> &Connection { fn read_lock(&self) -> &'static Connection {
self.read_conn_tls READ_CONNECTION.with(|cell| {
.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap()) let connection = &mut cell.borrow_mut();
if (*connection).is_none() {
let c = Box::leak(Box::new(
Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap(),
));
**connection = Some(c);
}
connection.unwrap()
})
} }
fn read_lock_iterator(&self) -> &Connection { fn read_lock_iterator(&self) -> &'static Connection {
self.read_iterator_conn_tls READ_CONNECTION_ITERATOR.with(|cell| {
.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap()) let connection = &mut cell.borrow_mut();
if (*connection).is_none() {
let c = Box::leak(Box::new(
Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap(),
));
**connection = Some(c);
}
connection.unwrap()
})
} }
pub fn flush_wal(self: &Arc<Self>) -> Result<()> { pub fn flush_wal(self: &Arc<Self>) -> Result<()> {
self.write_lock() // We use autocheckpoints
.pragma_update(Some(Main), "wal_checkpoint", &"TRUNCATE")?; //self.write_lock()
//.pragma_update(Some(Main), "wal_checkpoint", &"TRUNCATE")?;
Ok(()) Ok(())
} }
} }
@@ -88,18 +106,15 @@ impl DatabaseEngine for 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 connection // 2. divide by permanent connections
// 3. round down to nearest integer // 3. round down to nearest integer
let cache_size_per_thread: u32 = ((config.db_cache_capacity_mb * 1024.0) let cache_size_per_thread: u32 =
/ ((num_cpus::get().max(1) * 2) + 1) as f64) ((config.db_cache_capacity_mb * 1024.0) / (num_cpus::get().max(1) + 1) as f64) as u32;
as u32;
let writer = Mutex::new(Self::prepare_conn(&path, cache_size_per_thread)?); let writer = Mutex::new(Self::prepare_conn(&path, cache_size_per_thread)?);
let arc = Arc::new(Engine { let arc = Arc::new(Engine {
writer, writer,
read_conn_tls: ThreadLocal::new(),
read_iterator_conn_tls: ThreadLocal::new(),
path, path,
cache_size_per_thread, cache_size_per_thread,
}); });
@@ -134,7 +149,6 @@ type TupleOfBytes = (Vec<u8>, Vec<u8>);
impl SqliteTable { impl SqliteTable {
#[tracing::instrument(skip(self, guard, key))] #[tracing::instrument(skip(self, guard, key))]
fn get_with_guard(&self, guard: &Connection, key: &[u8]) -> Result<Option<Vec<u8>>> { fn get_with_guard(&self, guard: &Connection, key: &[u8]) -> Result<Option<Vec<u8>>> {
//dbg!(&self.name);
Ok(guard Ok(guard
.prepare(format!("SELECT value FROM {} WHERE key = ?", self.name).as_str())? .prepare(format!("SELECT value FROM {} WHERE key = ?", self.name).as_str())?
.query_row([key], |row| row.get(0)) .query_row([key], |row| row.get(0))
@@ -143,7 +157,6 @@ impl SqliteTable {
#[tracing::instrument(skip(self, guard, key, value))] #[tracing::instrument(skip(self, guard, key, value))]
fn insert_with_guard(&self, guard: &Connection, key: &[u8], value: &[u8]) -> Result<()> { fn insert_with_guard(&self, guard: &Connection, key: &[u8], value: &[u8]) -> Result<()> {
//dbg!(&self.name);
guard.execute( guard.execute(
format!( format!(
"INSERT OR REPLACE INTO {} (key, value) VALUES (?, ?)", "INSERT OR REPLACE INTO {} (key, value) VALUES (?, ?)",
@@ -170,16 +183,11 @@ impl SqliteTable {
let statement_ref = NonAliasingBox(statement); let statement_ref = NonAliasingBox(statement);
//let name = self.name.clone();
let iterator = Box::new( let iterator = Box::new(
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(move |r| { .map(|r| r.unwrap()),
//dbg!(&name);
r.unwrap()
}),
); );
Box::new(PreparedStatementIterator { Box::new(PreparedStatementIterator {
@@ -287,8 +295,6 @@ impl Tree for SqliteTable {
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?
//let name = self.name.clone();
if backwards { if backwards {
let statement = Box::leak(Box::new( let statement = Box::leak(Box::new(
guard guard
@@ -305,10 +311,7 @@ impl Tree 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(move |r| { .map(|r| r.unwrap()),
//dbg!(&name);
r.unwrap()
}),
); );
Box::new(PreparedStatementIterator { Box::new(PreparedStatementIterator {
iterator, iterator,
@@ -330,10 +333,7 @@ impl Tree 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(move |r| { .map(|r| r.unwrap()),
//dbg!(&name);
r.unwrap()
}),
); );
Box::new(PreparedStatementIterator { Box::new(PreparedStatementIterator {
+1 -1
View File
@@ -40,7 +40,7 @@ impl AccountData {
roomuserdataid.push(0xff); roomuserdataid.push(0xff);
roomuserdataid.extend_from_slice(&event_type.as_bytes()); roomuserdataid.extend_from_slice(&event_type.as_bytes());
let mut key = prefix; let mut key = prefix.clone();
key.extend_from_slice(event_type.as_bytes()); key.extend_from_slice(event_type.as_bytes());
let json = serde_json::to_value(data).expect("all types here can be serialized"); // TODO: maybe add error handling let json = serde_json::to_value(data).expect("all types here can be serialized"); // TODO: maybe add error handling
+63 -28
View File
@@ -1,4 +1,4 @@
use crate::{database::Config, server_server::FedDest, utils, ConduitResult, Error, Result}; use crate::{database::Config, utils, ConduitResult, Error, Result};
use ruma::{ use ruma::{
api::{ api::{
client::r0::sync::sync_events, client::r0::sync::sync_events,
@@ -6,25 +6,25 @@ use ruma::{
}, },
DeviceId, EventId, MilliSecondsSinceUnixEpoch, RoomId, ServerName, ServerSigningKeyId, UserId, DeviceId, EventId, MilliSecondsSinceUnixEpoch, RoomId, ServerName, ServerSigningKeyId, UserId,
}; };
use rustls::{ServerCertVerifier, WebPKIVerifier};
use std::{ use std::{
collections::{BTreeMap, HashMap}, collections::{BTreeMap, HashMap},
fs, fs,
future::Future, future::Future,
net::IpAddr,
path::PathBuf, path::PathBuf,
sync::{Arc, Mutex, RwLock}, sync::{Arc, Mutex, RwLock},
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use tokio::sync::{broadcast, watch::Receiver, Mutex as TokioMutex, Semaphore}; use tokio::sync::{broadcast, watch::Receiver, Mutex as TokioMutex, Semaphore};
use tracing::error; use tracing::{error, info};
use trust_dns_resolver::TokioAsyncResolver; use trust_dns_resolver::TokioAsyncResolver;
use super::abstraction::Tree; use super::abstraction::Tree;
pub const COUNTER: &[u8] = b"c"; pub const COUNTER: &[u8] = b"c";
type WellKnownMap = HashMap<Box<ServerName>, (FedDest, String)>; type WellKnownMap = HashMap<Box<ServerName>, (String, String)>;
type TlsNameMap = HashMap<String, (Vec<IpAddr>, u16)>; type TlsNameMap = HashMap<String, webpki::DNSName>;
type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries
type SyncHandle = ( type SyncHandle = (
Option<String>, // since Option<String>, // since
@@ -37,6 +37,7 @@ pub struct Globals {
pub(super) globals: Arc<dyn Tree>, pub(super) globals: Arc<dyn Tree>,
config: Config, config: Config,
keypair: Arc<ruma::signatures::Ed25519KeyPair>, keypair: Arc<ruma::signatures::Ed25519KeyPair>,
reqwest_client: reqwest::Client,
dns_resolver: TokioAsyncResolver, dns_resolver: TokioAsyncResolver,
jwt_decoding_key: Option<jsonwebtoken::DecodingKey<'static>>, jwt_decoding_key: Option<jsonwebtoken::DecodingKey<'static>>,
pub(super) server_signingkeys: Arc<dyn Tree>, pub(super) server_signingkeys: Arc<dyn Tree>,
@@ -50,6 +51,40 @@ pub struct Globals {
pub rotate: RotationHandler, pub rotate: RotationHandler,
} }
struct MatrixServerVerifier {
inner: WebPKIVerifier,
tls_name_override: Arc<RwLock<TlsNameMap>>,
}
impl ServerCertVerifier for MatrixServerVerifier {
#[tracing::instrument(skip(self, roots, presented_certs, dns_name, ocsp_response))]
fn verify_server_cert(
&self,
roots: &rustls::RootCertStore,
presented_certs: &[rustls::Certificate],
dns_name: webpki::DNSNameRef<'_>,
ocsp_response: &[u8],
) -> std::result::Result<rustls::ServerCertVerified, rustls::TLSError> {
if let Some(override_name) = self.tls_name_override.read().unwrap().get(dns_name.into()) {
let result = self.inner.verify_server_cert(
roots,
presented_certs,
override_name.as_ref(),
ocsp_response,
);
if result.is_ok() {
return result;
}
info!(
"Server {:?} is non-compliant, retrying TLS verification with original name",
dns_name
);
}
self.inner
.verify_server_cert(roots, presented_certs, dns_name, ocsp_response)
}
}
/// Handles "rotation" of long-polling requests. "Rotation" in this context is similar to "rotation" of log files and the like. /// Handles "rotation" of long-polling requests. "Rotation" in this context is similar to "rotation" of log files and the like.
/// ///
/// This is utilized to have sync workers return early and release read locks on the database. /// This is utilized to have sync workers return early and release read locks on the database.
@@ -127,6 +162,24 @@ impl Globals {
}; };
let tls_name_override = Arc::new(RwLock::new(TlsNameMap::new())); let tls_name_override = Arc::new(RwLock::new(TlsNameMap::new()));
let verifier = Arc::new(MatrixServerVerifier {
inner: WebPKIVerifier::new(),
tls_name_override: tls_name_override.clone(),
});
let mut tlsconfig = rustls::ClientConfig::new();
tlsconfig.dangerous().set_certificate_verifier(verifier);
tlsconfig.root_store =
rustls_native_certs::load_native_certs().expect("Error loading system certificates");
let mut reqwest_client_builder = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(30))
.timeout(Duration::from_secs(60 * 3))
.pool_max_idle_per_host(1)
.use_preconfigured_tls(tlsconfig);
if let Some(proxy) = config.proxy.to_proxy()? {
reqwest_client_builder = reqwest_client_builder.proxy(proxy);
}
let reqwest_client = reqwest_client_builder.build().unwrap();
let jwt_decoding_key = config let jwt_decoding_key = config
.jwt_secret .jwt_secret
@@ -137,6 +190,7 @@ impl Globals {
globals, globals,
config, config,
keypair: Arc::new(keypair), keypair: Arc::new(keypair),
reqwest_client,
dns_resolver: TokioAsyncResolver::tokio_from_system_conf().map_err(|_| { dns_resolver: TokioAsyncResolver::tokio_from_system_conf().map_err(|_| {
Error::bad_config("Failed to set up trust dns resolver with system config.") Error::bad_config("Failed to set up trust dns resolver with system config.")
})?, })?,
@@ -165,16 +219,8 @@ impl Globals {
} }
/// Returns a reqwest client which can be used to send requests. /// Returns a reqwest client which can be used to send requests.
pub fn reqwest_client(&self) -> Result<reqwest::ClientBuilder> { pub fn reqwest_client(&self) -> &reqwest::Client {
let mut reqwest_client_builder = reqwest::Client::builder() &self.reqwest_client
.connect_timeout(Duration::from_secs(30))
.timeout(Duration::from_secs(60 * 3))
.pool_max_idle_per_host(1);
if let Some(proxy) = self.config.proxy.to_proxy()? {
reqwest_client_builder = reqwest_client_builder.proxy(proxy);
}
Ok(reqwest_client_builder)
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
@@ -227,11 +273,7 @@ impl Globals {
/// Remove the outdated keys and insert the new ones. /// Remove the outdated keys and insert the new ones.
/// ///
/// This doesn't actually check that the keys provided are newer than the old set. /// This doesn't actually check that the keys provided are newer than the old set.
pub fn add_signing_key( pub fn add_signing_key(&self, origin: &ServerName, new_keys: ServerSigningKeys) -> Result<()> {
&self,
origin: &ServerName,
new_keys: ServerSigningKeys,
) -> Result<BTreeMap<ServerSigningKeyId, 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())?;
@@ -256,14 +298,7 @@ impl Globals {
&serde_json::to_vec(&keys).expect("serversigningkeys can be serialized"), &serde_json::to_vec(&keys).expect("serversigningkeys can be serialized"),
)?; )?;
let mut tree = keys.verify_keys; Ok(())
tree.extend(
keys.old_verify_keys
.into_iter()
.map(|old| (old.0, VerifyKey::new(old.1.key))),
);
Ok(tree)
} }
/// This returns an empty `Ok(BTreeMap<..>)` when there are no keys found for the server. /// This returns an empty `Ok(BTreeMap<..>)` when there are no keys found for the server.
-21
View File
@@ -84,27 +84,6 @@ impl KeyBackups {
Ok(version.to_string()) Ok(version.to_string())
} }
pub fn get_latest_backup_version(&self, user_id: &UserId) -> Result<Option<String>> {
let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
let mut last_possible_key = prefix.clone();
last_possible_key.extend_from_slice(&u64::MAX.to_be_bytes());
self.backupid_algorithm
.iter_from(&last_possible_key, true)
.take_while(move |(k, _)| k.starts_with(&prefix))
.next()
.map_or(Ok(None), |(key, _)| {
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(Some)
})
}
pub fn get_latest_backup(&self, user_id: &UserId) -> Result<Option<(String, BackupAlgorithm)>> { pub fn get_latest_backup(&self, user_id: &UserId) -> Result<Option<(String, 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);
+1 -5
View File
@@ -113,11 +113,7 @@ where
//*reqwest_request.timeout_mut() = Some(Duration::from_secs(5)); //*reqwest_request.timeout_mut() = Some(Duration::from_secs(5));
let url = reqwest_request.url().clone(); let url = reqwest_request.url().clone();
let response = globals let response = globals.reqwest_client().execute(reqwest_request).await;
.reqwest_client()?
.build()?
.execute(reqwest_request)
.await;
match response { match response {
Ok(mut response) => { Ok(mut response) => {
+215 -383
View File
@@ -1,39 +1,40 @@
mod edus; use std::{
collections::{BTreeMap, HashMap, HashSet},
convert::{TryFrom, TryInto},
mem::size_of,
sync::{Arc, Mutex},
};
pub use edus::RoomEdus;
use member::MembershipState;
use crate::{pdu::PduBuilder, server_server, utils, Database, Error, PduEvent, Result};
use lru_cache::LruCache; use lru_cache::LruCache;
use member::MembershipState;
use regex::Regex; use regex::Regex;
use ring::digest; use ring::digest;
use rocket::http::RawStr; use rocket::http::RawStr;
use ruma::{ use ruma::{
api::{client::error::ErrorKind, federation}, api::{client::error::ErrorKind, federation},
EventId,
events::{ events::{
ignored_user_list, push_rules, AnyStrippedStateEvent, AnySyncStateEvent,
room::{ EventType,
ignored_user_list, push_rules, room::{
create::CreateEventContent, member, message, power_levels::PowerLevelsEventContent, create::CreateEventContent, member, message, power_levels::PowerLevelsEventContent,
}, },
AnyStrippedStateEvent, AnySyncStateEvent, EventType,
}, },
push::{self, Action, Tweak}, push::{self, Action, Tweak},
serde::{CanonicalJsonObject, CanonicalJsonValue, Raw}, RoomAliasId,
state_res::{self, RoomVersion, StateMap}, RoomId, RoomVersionId, serde::{CanonicalJsonObject, CanonicalJsonValue, Raw}, ServerName, state_res::{self, RoomVersion, StateMap}, uint, UserId,
uint, EventId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
};
use std::{
collections::{BTreeMap, HashMap, HashSet},
convert::{TryFrom, TryInto},
mem::size_of,
sync::{Arc, Mutex, RwLock},
time::Instant,
}; };
use tokio::sync::MutexGuard; use tokio::sync::MutexGuard;
use tracing::{error, warn}; use tracing::{error, warn};
pub use edus::RoomEdus;
use crate::{Database, Error, pdu::PduBuilder, PduEvent, Result, utils};
use super::{abstraction::Tree, admin::AdminCommand, pusher}; use super::{abstraction::Tree, admin::AdminCommand, pusher};
mod edus;
/// The unique identifier of each state group. /// The unique identifier of each state group.
/// ///
/// This is created when a state group is added to the database by /// This is created when a state group is added to the database by
@@ -59,7 +60,6 @@ pub struct Rooms {
pub(super) userroomid_joined: Arc<dyn Tree>, pub(super) userroomid_joined: Arc<dyn Tree>,
pub(super) roomuserid_joined: Arc<dyn Tree>, pub(super) roomuserid_joined: Arc<dyn Tree>,
pub(super) roomid_joinedcount: Arc<dyn Tree>, pub(super) roomid_joinedcount: Arc<dyn Tree>,
pub(super) roomid_invitedcount: Arc<dyn Tree>,
pub(super) roomuseroncejoinedids: Arc<dyn Tree>, pub(super) roomuseroncejoinedids: Arc<dyn Tree>,
pub(super) userroomid_invitestate: Arc<dyn Tree>, // InviteState = Vec<Raw<Pdu>> pub(super) userroomid_invitestate: Arc<dyn Tree>, // InviteState = Vec<Raw<Pdu>>
pub(super) roomuserid_invitecount: Arc<dyn Tree>, // InviteCount = Count pub(super) roomuserid_invitecount: Arc<dyn Tree>, // InviteCount = Count
@@ -71,7 +71,6 @@ pub struct Rooms {
/// Remember the current state hash of a room. /// Remember the current state hash of a room.
pub(super) roomid_shortstatehash: Arc<dyn Tree>, pub(super) roomid_shortstatehash: Arc<dyn Tree>,
pub(super) roomsynctoken_shortstatehash: Arc<dyn Tree>,
/// Remember the state hash at events in the past. /// Remember the state hash at events in the past.
pub(super) shorteventid_shortstatehash: Arc<dyn Tree>, pub(super) shorteventid_shortstatehash: Arc<dyn Tree>,
/// StateKey = EventType + StateKey, ShortStateKey = Count /// StateKey = EventType + StateKey, ShortStateKey = Count
@@ -86,24 +85,19 @@ pub struct Rooms {
pub(super) statehash_shortstatehash: Arc<dyn Tree>, pub(super) statehash_shortstatehash: Arc<dyn Tree>,
pub(super) shortstatehash_statediff: Arc<dyn Tree>, // StateDiff = parent (or 0) + (shortstatekey+shorteventid++) + 0_u64 + (shortstatekey+shorteventid--) pub(super) shortstatehash_statediff: Arc<dyn Tree>, // StateDiff = parent (or 0) + (shortstatekey+shorteventid++) + 0_u64 + (shortstatekey+shorteventid--)
pub(super) shorteventid_authchain: Arc<dyn Tree>,
/// RoomId + EventId -> outlier PDU. /// RoomId + EventId -> outlier PDU.
/// Any pdu that has passed the steps 1-8 in the incoming event /federation/send/txn. /// Any pdu that has passed the steps 1-8 in the incoming event /federation/send/txn.
pub(super) eventid_outlierpdu: Arc<dyn Tree>, pub(super) eventid_outlierpdu: Arc<dyn Tree>,
pub(super) softfailedeventids: Arc<dyn Tree>,
/// RoomId + EventId -> Parent PDU EventId. /// RoomId + EventId -> Parent PDU EventId.
pub(super) referencedevents: Arc<dyn Tree>, pub(super) referencedevents: Arc<dyn Tree>,
pub(super) pdu_cache: Mutex<LruCache<EventId, Arc<PduEvent>>>, pub(super) pdu_cache: Mutex<LruCache<EventId, Arc<PduEvent>>>,
pub(super) shorteventid_cache: Mutex<LruCache<u64, Arc<EventId>>>, pub(super) auth_chain_cache: Mutex<LruCache<Vec<u64>, HashSet<u64>>>,
pub(super) auth_chain_cache: Mutex<LruCache<Vec<u64>, Arc<HashSet<u64>>>>, pub(super) shorteventid_cache: Mutex<LruCache<u64, EventId>>,
pub(super) eventidshort_cache: Mutex<LruCache<EventId, u64>>, pub(super) eventidshort_cache: Mutex<LruCache<EventId, u64>>,
pub(super) statekeyshort_cache: Mutex<LruCache<(EventType, String), u64>>, pub(super) statekeyshort_cache: Mutex<LruCache<(EventType, String), u64>>,
pub(super) shortstatekey_cache: Mutex<LruCache<u64, (EventType, String)>>, pub(super) shortstatekey_cache: Mutex<LruCache<u64, (EventType, String)>>,
pub(super) our_real_users_cache: RwLock<HashMap<RoomId, Arc<HashSet<UserId>>>>,
pub(super) appservice_in_room_cache: RwLock<HashMap<RoomId, HashMap<String, bool>>>,
pub(super) stateinfo_cache: Mutex< pub(super) stateinfo_cache: Mutex<
LruCache< LruCache<
u64, u64,
@@ -121,7 +115,7 @@ impl Rooms {
/// Builds a StateMap by iterating over all keys that start /// Builds a StateMap by iterating over all keys that start
/// with state_hash, this gives the full state for the given state_hash. /// with state_hash, this gives the full state for the given state_hash.
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn state_full_ids(&self, shortstatehash: u64) -> Result<BTreeMap<u64, Arc<EventId>>> { pub fn state_full_ids(&self, shortstatehash: u64) -> Result<BTreeMap<u64, EventId>> {
let full_state = self let full_state = self
.load_shortstatehash_info(shortstatehash)? .load_shortstatehash_info(shortstatehash)?
.pop() .pop()
@@ -172,7 +166,7 @@ impl Rooms {
shortstatehash: u64, shortstatehash: u64,
event_type: &EventType, event_type: &EventType,
state_key: &str, state_key: &str,
) -> Result<Option<Arc<EventId>>> { ) -> Result<Option<EventId>> {
let shortstatekey = match self.get_shortstatekey(event_type, state_key)? { let shortstatekey = match self.get_shortstatekey(event_type, state_key)? {
Some(s) => s, Some(s) => s,
None => return Ok(None), None => return Ok(None),
@@ -385,7 +379,7 @@ impl Rooms {
self.save_state_from_diff( self.save_state_from_diff(
new_shortstatehash, new_shortstatehash,
statediffnew.clone(), statediffnew.clone(),
statediffremoved, statediffremoved.clone(),
2, // every state change is 2 event changes on average 2, // every state change is 2 event changes on average
states_parents, states_parents,
)?; )?;
@@ -429,7 +423,7 @@ impl Rooms {
} }
} }
self.update_joined_count(room_id, &db)?; self.update_joined_count(room_id)?;
self.roomid_shortstatehash self.roomid_shortstatehash
.insert(room_id.as_bytes(), &new_shortstatehash.to_be_bytes())?; .insert(room_id.as_bytes(), &new_shortstatehash.to_be_bytes())?;
@@ -497,7 +491,8 @@ impl Rooms {
Ok(response) Ok(response)
} else { } else {
let response = vec![(shortstatehash, added.clone(), added, removed)]; let mut response = Vec::new();
response.push((shortstatehash, added.clone(), added, removed));
self.stateinfo_cache self.stateinfo_cache
.lock() .lock()
.unwrap() .unwrap()
@@ -527,7 +522,7 @@ impl Rooms {
pub fn parse_compressed_state_event( pub fn parse_compressed_state_event(
&self, &self,
compressed_event: CompressedStateEvent, compressed_event: CompressedStateEvent,
) -> Result<(u64, Arc<EventId>)> { ) -> Result<(u64, EventId)> {
Ok(( Ok((
utils::u64_from_bytes(&compressed_event[0..size_of::<u64>()]) utils::u64_from_bytes(&compressed_event[0..size_of::<u64>()])
.expect("bytes have right length"), .expect("bytes have right length"),
@@ -608,7 +603,7 @@ impl Rooms {
return Ok(()); return Ok(());
} }
if parent_states.is_empty() { if parent_states.len() == 0 {
// There is no parent layer, create a new state // There is no parent layer, create a new state
let mut value = 0_u64.to_be_bytes().to_vec(); // 0 means no parent let mut value = 0_u64.to_be_bytes().to_vec(); // 0 means no parent
for new in &statediffnew { for new in &statediffnew {
@@ -688,7 +683,7 @@ impl Rooms {
state_hash: &StateHashId, state_hash: &StateHashId,
globals: &super::globals::Globals, globals: &super::globals::Globals,
) -> Result<(u64, bool)> { ) -> Result<(u64, bool)> {
Ok(match self.statehash_shortstatehash.get(state_hash)? { Ok(match self.statehash_shortstatehash.get(&state_hash)? {
Some(shortstatehash) => ( Some(shortstatehash) => (
utils::u64_from_bytes(&shortstatehash) utils::u64_from_bytes(&shortstatehash)
.map_err(|_| Error::bad_database("Invalid shortstatehash in db."))?, .map_err(|_| Error::bad_database("Invalid shortstatehash in db."))?,
@@ -697,7 +692,7 @@ impl Rooms {
None => { None => {
let shortstatehash = globals.next_count()?; let shortstatehash = globals.next_count()?;
self.statehash_shortstatehash self.statehash_shortstatehash
.insert(state_hash, &shortstatehash.to_be_bytes())?; .insert(&state_hash, &shortstatehash.to_be_bytes())?;
(shortstatehash, false) (shortstatehash, false)
} }
}) })
@@ -843,14 +838,14 @@ impl Rooms {
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn get_eventid_from_short(&self, shorteventid: u64) -> Result<Arc<EventId>> { pub fn get_eventid_from_short(&self, shorteventid: u64) -> Result<EventId> {
if let Some(id) = self if let Some(id) = self
.shorteventid_cache .shorteventid_cache
.lock() .lock()
.unwrap() .unwrap()
.get_mut(&shorteventid) .get_mut(&shorteventid)
{ {
return Ok(Arc::clone(id)); return Ok(id.clone());
} }
let bytes = self let bytes = self
@@ -858,17 +853,15 @@ impl Rooms {
.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 = Arc::new( let event_id = EventId::try_from(utils::string_from_bytes(&bytes).map_err(|_| {
EventId::try_from(utils::string_from_bytes(&bytes).map_err(|_| { Error::bad_database("EventID in shorteventid_eventid is invalid unicode.")
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 self.shorteventid_cache
.lock() .lock()
.unwrap() .unwrap()
.insert(shorteventid, Arc::clone(&event_id)); .insert(shorteventid, event_id.clone());
Ok(event_id) Ok(event_id)
} }
@@ -935,7 +928,7 @@ impl Rooms {
room_id: &RoomId, room_id: &RoomId,
event_type: &EventType, event_type: &EventType,
state_key: &str, state_key: &str,
) -> Result<Option<Arc<EventId>>> { ) -> Result<Option<EventId>> {
if let Some(current_shortstatehash) = self.current_shortstatehash(room_id)? { if let Some(current_shortstatehash) = self.current_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 {
@@ -1232,19 +1225,9 @@ impl Rooms {
self.eventid_outlierpdu.insert( self.eventid_outlierpdu.insert(
&event_id.as_bytes(), &event_id.as_bytes(),
&serde_json::to_vec(&pdu).expect("CanonicalJsonObject is valid"), &serde_json::to_vec(&pdu).expect("CanonicalJsonObject is valid"),
) )?;
}
#[tracing::instrument(skip(self))] Ok(())
pub fn mark_event_soft_failed(&self, event_id: &EventId) -> Result<()> {
self.softfailedeventids.insert(&event_id.as_bytes(), &[])
}
#[tracing::instrument(skip(self))]
pub fn is_event_soft_failed(&self, event_id: &EventId) -> Result<bool> {
self.softfailedeventids
.get(&event_id.as_bytes())
.map(|o| o.is_some())
} }
/// Creates a new persisted data unit and adds it to a room. /// Creates a new persisted data unit and adds it to a room.
@@ -1347,9 +1330,15 @@ impl Rooms {
let mut notifies = Vec::new(); let mut notifies = Vec::new();
let mut highlights = Vec::new(); let mut highlights = Vec::new();
for user in self.get_our_real_users(&pdu.room_id, db)?.iter() { for user in db
.rooms
.room_members(&pdu.room_id)
.filter_map(|r| r.ok())
.filter(|user_id| user_id.server_name() == db.globals.server_name())
.filter(|user_id| !db.users.is_deactivated(user_id).unwrap_or(true))
{
// Don't notify the user of their own events // Don't notify the user of their own events
if user == &pdu.sender { if user == pdu.sender {
continue; continue;
} }
@@ -1525,101 +1514,6 @@ impl Rooms {
"list_appservices" => { "list_appservices" => {
db.admin.send(AdminCommand::ListAppservices); db.admin.send(AdminCommand::ListAppservices);
} }
"get_auth_chain" => {
if args.len() == 1 {
if let Ok(event_id) = EventId::try_from(args[0]) {
if let Some(event) = db.rooms.get_pdu_json(&event_id)? {
let room_id_str = event
.get("room_id")
.and_then(|val| val.as_str())
.ok_or_else(|| {
Error::bad_database(
"Invalid event in database",
)
})?;
let room_id = RoomId::try_from(room_id_str)
.map_err(|_| Error::bad_database("Invalid room id field in event in database"))?;
let start = Instant::now();
let count = server_server::get_auth_chain(
&room_id,
vec![Arc::new(event_id)],
db,
)?
.count();
let elapsed = start.elapsed();
db.admin.send(AdminCommand::SendMessage(
message::MessageEventContent::text_plain(
format!(
"Loaded auth chain with length {} in {:?}",
count, elapsed
),
),
));
}
}
}
}
"parse_pdu" => {
if body.len() > 2
&& body[0].trim() == "```"
&& body.last().unwrap().trim() == "```"
{
let string = body[1..body.len() - 1].join("\n");
match serde_json::from_str(&string) {
Ok(value) => {
let event_id = EventId::try_from(&*format!(
"${}",
// Anything higher than version3 behaves the same
ruma::signatures::reference_hash(
&value,
&RoomVersionId::Version6
)
.expect("ruma can calculate reference hashes")
))
.expect(
"ruma's reference hashes are valid event ids",
);
match serde_json::from_value::<PduEvent>(
serde_json::to_value(value)
.expect("value is json"),
) {
Ok(pdu) => {
db.admin.send(AdminCommand::SendMessage(
message::MessageEventContent::text_plain(
format!("EventId: {:?}\n{:#?}", event_id, pdu),
),
));
}
Err(e) => {
db.admin.send(AdminCommand::SendMessage(
message::MessageEventContent::text_plain(
format!("EventId: {:?}\nCould not parse event: {}", event_id, e),
),
));
}
}
}
Err(e) => {
db.admin.send(AdminCommand::SendMessage(
message::MessageEventContent::text_plain(
format!(
"Invalid json in command body: {}",
e
),
),
));
}
}
} else {
db.admin.send(AdminCommand::SendMessage(
message::MessageEventContent::text_plain(
"Expected code block in command body.",
),
));
}
}
"get_pdu" => { "get_pdu" => {
if args.len() == 1 { if args.len() == 1 {
if let Ok(event_id) = EventId::try_from(args[0]) { if let Ok(event_id) = EventId::try_from(args[0]) {
@@ -1783,8 +1677,8 @@ impl Rooms {
}; };
self.save_state_from_diff( self.save_state_from_diff(
shortstatehash, shortstatehash,
statediffnew, statediffnew.clone(),
statediffremoved, statediffremoved.clone(),
1_000_000, // high number because no state will be based on this one 1_000_000, // high number because no state will be based on this one
states_parents, states_parents,
)?; )?;
@@ -1908,37 +1802,6 @@ impl Rooms {
Ok(()) Ok(())
} }
pub fn associate_token_shortstatehash(
&self,
room_id: &RoomId,
token: u64,
shortstatehash: u64,
) -> Result<()> {
let shortroomid = self.get_shortroomid(room_id)?.expect("room exists");
let mut key = shortroomid.to_be_bytes().to_vec();
key.extend_from_slice(&token.to_be_bytes());
self.roomsynctoken_shortstatehash
.insert(&key, &shortstatehash.to_be_bytes())
}
pub fn get_token_shortstatehash(&self, room_id: &RoomId, token: u64) -> Result<Option<u64>> {
let shortroomid = self.get_shortroomid(room_id)?.expect("room exists");
let mut key = shortroomid.to_be_bytes().to_vec();
key.extend_from_slice(&token.to_be_bytes());
self.roomsynctoken_shortstatehash
.get(&key)?
.map(|bytes| {
utils::u64_from_bytes(&bytes).map_err(|_| {
Error::bad_database("Invalid shortstatehash in roomsynctoken_shortstatehash")
})
})
.transpose()
}
/// Creates a new persisted data unit and adds it to a room. /// Creates a new persisted data unit and adds it to a room.
#[tracing::instrument(skip(self, db, _mutex_lock))] #[tracing::instrument(skip(self, db, _mutex_lock))]
pub fn build_and_append_pdu( pub fn build_and_append_pdu(
@@ -2125,11 +1988,6 @@ impl Rooms {
} }
for appservice in db.appservice.all()? { for appservice in db.appservice.all()? {
if self.appservice_in_room(room_id, &appservice, db)? {
db.sending.send_pdu_appservice(&appservice.0, &pdu_id)?;
continue;
}
if let Some(namespaces) = appservice.1.get("namespaces") { if let Some(namespaces) = appservice.1.get("namespaces") {
let users = namespaces let users = namespaces
.get("users") .get("users")
@@ -2153,6 +2011,17 @@ impl Rooms {
.get("rooms") .get("rooms")
.and_then(|rooms| rooms.as_sequence()); .and_then(|rooms| rooms.as_sequence());
let bridge_user_id = appservice
.1
.get("sender_localpart")
.and_then(|string| string.as_str())
.and_then(|string| {
UserId::parse_with_server_name(string, db.globals.server_name()).ok()
});
let user_is_joined =
|bridge_user_id| self.is_joined(&bridge_user_id, room_id).unwrap_or(false);
let matching_users = |users: &Regex| { let matching_users = |users: &Regex| {
users.is_match(pdu.sender.as_str()) users.is_match(pdu.sender.as_str())
|| pdu.kind == EventType::RoomMember || pdu.kind == EventType::RoomMember
@@ -2160,6 +2029,9 @@ impl Rooms {
.state_key .state_key
.as_ref() .as_ref()
.map_or(false, |state_key| users.is_match(&state_key)) .map_or(false, |state_key| users.is_match(&state_key))
|| self.room_members(&room_id).any(|userid| {
userid.map_or(false, |userid| users.is_match(userid.as_str()))
})
}; };
let matching_aliases = |aliases: &Regex| { let matching_aliases = |aliases: &Regex| {
self.room_aliases(&room_id) self.room_aliases(&room_id)
@@ -2167,7 +2039,8 @@ impl Rooms {
.any(|room_alias| aliases.is_match(room_alias.as_str())) .any(|room_alias| aliases.is_match(room_alias.as_str()))
}; };
if aliases.iter().any(matching_aliases) if bridge_user_id.map_or(false, user_is_joined)
|| aliases.iter().any(matching_aliases)
|| rooms.map_or(false, |rooms| rooms.contains(&room_id.as_str().into())) || rooms.map_or(false, |rooms| rooms.contains(&room_id.as_str().into()))
|| users.iter().any(matching_users) || users.iter().any(matching_users)
{ {
@@ -2489,15 +2362,16 @@ impl Rooms {
self.roomuserid_leftcount.remove(&roomuser_id)?; self.roomuserid_leftcount.remove(&roomuser_id)?;
} }
member::MembershipState::Leave | member::MembershipState::Ban => { member::MembershipState::Leave | member::MembershipState::Ban => {
if update_joined_count if update_joined_count {
&& self if self
.room_members(room_id) .room_members(room_id)
.chain(self.room_members_invited(room_id)) .chain(self.room_members_invited(room_id))
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.all(|u| u.server_name() != user_id.server_name()) .all(|u| u.server_name() != user_id.server_name())
{ {
self.roomserverids.remove(&roomserver_id)?; self.roomserverids.remove(&roomserver_id)?;
self.serverroomids.remove(&serverroom_id)?; self.serverroomids.remove(&serverroom_id)?;
}
} }
self.userroomid_leftstate.insert( self.userroomid_leftstate.insert(
&userroom_id, &userroom_id,
@@ -2514,45 +2388,29 @@ impl Rooms {
} }
if update_joined_count { if update_joined_count {
self.update_joined_count(room_id, db)?; self.update_joined_count(room_id)?;
} }
Ok(()) Ok(())
} }
#[tracing::instrument(skip(self, room_id, db))] #[tracing::instrument(skip(self))]
pub fn update_joined_count(&self, room_id: &RoomId, db: &Database) -> Result<()> { pub 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 joined_servers = HashSet::new(); let mut joined_servers = HashSet::new();
let mut real_users = HashSet::new();
for joined in self.room_members(&room_id).filter_map(|r| r.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() == db.globals.server_name()
&& !db.users.is_deactivated(&joined).unwrap_or(true)
{
real_users.insert(joined);
}
joinedcount += 1; joinedcount += 1;
} }
for invited in self.room_members_invited(&room_id).filter_map(|r| r.ok()) { for invited in self.room_members_invited(&room_id).filter_map(|r| r.ok()) {
joined_servers.insert(invited.server_name().to_owned()); joined_servers.insert(invited.server_name().to_owned());
invitedcount += 1;
} }
self.roomid_joinedcount self.roomid_joinedcount
.insert(room_id.as_bytes(), &joinedcount.to_be_bytes())?; .insert(room_id.as_bytes(), &joinedcount.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.clone(), Arc::new(real_users));
for old_joined_server in self.room_servers(room_id).filter_map(|r| r.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
@@ -2583,97 +2441,9 @@ impl Rooms {
self.serverroomids.insert(&serverroom_id, &[])?; self.serverroomids.insert(&serverroom_id, &[])?;
} }
self.appservice_in_room_cache
.write()
.unwrap()
.remove(room_id);
Ok(()) Ok(())
} }
#[tracing::instrument(skip(self, room_id, db))]
pub fn get_our_real_users(
&self,
room_id: &RoomId,
db: &Database,
) -> Result<Arc<HashSet<UserId>>> {
let maybe = self
.our_real_users_cache
.read()
.unwrap()
.get(room_id)
.cloned();
if let Some(users) = maybe {
Ok(users)
} else {
self.update_joined_count(room_id, &db)?;
Ok(Arc::clone(
self.our_real_users_cache
.read()
.unwrap()
.get(room_id)
.unwrap(),
))
}
}
#[tracing::instrument(skip(self, room_id, appservice, db))]
pub fn appservice_in_room(
&self,
room_id: &RoomId,
appservice: &(String, serde_yaml::Value),
db: &Database,
) -> Result<bool> {
let maybe = self
.appservice_in_room_cache
.read()
.unwrap()
.get(room_id)
.and_then(|map| map.get(&appservice.0))
.copied();
if let Some(b) = maybe {
Ok(b)
} else if let Some(namespaces) = appservice.1.get("namespaces") {
let users = namespaces
.get("users")
.and_then(|users| users.as_sequence())
.map_or_else(Vec::new, |users| {
users
.iter()
.filter_map(|users| Regex::new(users.get("regex")?.as_str()?).ok())
.collect::<Vec<_>>()
});
let bridge_user_id = appservice
.1
.get("sender_localpart")
.and_then(|string| string.as_str())
.and_then(|string| {
UserId::parse_with_server_name(string, db.globals.server_name()).ok()
});
let in_room = bridge_user_id
.map_or(false, |id| self.is_joined(&id, room_id).unwrap_or(false))
|| self.room_members(&room_id).any(|userid| {
userid.map_or(false, |userid| {
users.iter().any(|r| r.is_match(userid.as_str()))
})
});
self.appservice_in_room_cache
.write()
.unwrap()
.entry(room_id.clone())
.or_default()
.insert(appservice.0.clone(), in_room);
Ok(in_room)
} else {
Ok(false)
}
}
#[tracing::instrument(skip(self, db))] #[tracing::instrument(skip(self, db))]
pub async fn leave_room( pub async fn leave_room(
&self, &self,
@@ -3094,15 +2864,6 @@ impl Rooms {
}) })
} }
#[tracing::instrument(skip(self))]
pub fn server_in_room<'a>(&'a self, server: &ServerName, room_id: &RoomId) -> Result<bool> {
let mut key = server.as_bytes().to_vec();
key.push(0xff);
key.extend_from_slice(room_id.as_bytes());
self.serverroomids.get(&key).map(|o| o.is_some())
}
/// Returns an iterator of all rooms a server participates in (as far as we know). /// Returns an iterator of all rooms a server participates in (as far as we know).
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn server_rooms<'a>( pub fn server_rooms<'a>(
@@ -3161,18 +2922,6 @@ impl Rooms {
.transpose()?) .transpose()?)
} }
#[tracing::instrument(skip(self))]
pub fn room_invited_count(&self, room_id: &RoomId) -> Result<Option<u64>> {
Ok(self
.roomid_invitedcount
.get(room_id.as_bytes())?
.map(|b| {
utils::u64_from_bytes(&b)
.map_err(|_| Error::bad_database("Invalid joinedcount in db."))
})
.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))]
pub fn room_useroncejoined<'a>( pub fn room_useroncejoined<'a>(
@@ -3419,61 +3168,144 @@ impl Rooms {
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn get_auth_chain_from_cache<'a>( pub fn auth_chain_cache(&self) -> std::sync::MutexGuard<'_, LruCache<Vec<u64>, HashSet<u64>>> {
&'a self, self.auth_chain_cache.lock().unwrap()
key: &[u64],
) -> Result<Option<Arc<HashSet<u64>>>> {
// Check RAM cache
if let Some(result) = self.auth_chain_cache.lock().unwrap().get_mut(key) {
return Ok(Some(Arc::clone(result)));
}
// Check DB cache
if key.len() == 1 {
if let Some(chain) =
self.shorteventid_authchain
.get(&key[0].to_be_bytes())?
.map(|chain| {
chain
.chunks_exact(size_of::<u64>())
.map(|chunk| {
utils::u64_from_bytes(chunk).expect("byte length is correct")
})
.collect()
})
{
let chain = Arc::new(chain);
// Cache in RAM
self.auth_chain_cache
.lock()
.unwrap()
.insert(vec![key[0]], Arc::clone(&chain));
return Ok(Some(chain));
}
}
Ok(None)
}
#[tracing::instrument(skip(self))]
pub fn cache_auth_chain(&self, key: Vec<u64>, chain: Arc<HashSet<u64>>) -> Result<()> {
// Persist in db
if key.len() == 1 {
self.shorteventid_authchain.insert(
&key[0].to_be_bytes(),
&chain
.iter()
.map(|s| s.to_be_bytes().to_vec())
.flatten()
.collect::<Vec<u8>>(),
)?;
}
// Cache in RAM
self.auth_chain_cache.lock().unwrap().insert(key, chain);
Ok(())
} }
} }
#[test]
fn test_size_of_caches() {
let stateinfo_cache: LruCache<
u64,
Vec<(
u64, // sstatehash
HashSet<CompressedStateEvent>, // full state
HashSet<CompressedStateEvent>, // added
HashSet<CompressedStateEvent>, // removed
)>,
> = LruCache::new(1_000);
let mut total_max_cache_size: i32 = 0;
{
let pdu_cache: LruCache<EventId, Arc<PduEvent>> = LruCache::new(100_000);
let content_json = r#"
{
"body": "> <@fusetim:matrix.org> with my toaster, sure xd\n\nFor people with smaller machines, I can recomend gitpod. It is integrated with GitLab and gives you a quite powerful machine (see screenshot below) with vscode in the browser.",
"format": "org.matrix.custom.html",
"formatted_body": "<mx-reply><blockquote><a href=\"https://matrix.to/#/!pWCROeqlZcGggueJLt:fachschaften.org/$2Slj7obNBkOLVOiF5nhNLIRI7-gWLY6lc0F75ERJAmI?via=conduit.rs&via=matrix.org&via=privacytools.io\">In reply to</a> <a href=\"https://matrix.to/#/@fusetim:matrix.org\">@fusetim:matrix.org</a><br>with my toaster, sure xd</blockquote></mx-reply>For people with smaller machines, I can recomend gitpod. It is integrated with GitLab and gives you a quite powerful machine (see screenshot below) with vscode in the browser.",
"m.relates_to": {
"m.in_reply_to": {
"event_id": "$2Slj7obNBkOLVOiF5nhNLIRI7-gWLY6lc0F75ERJAmI"
}
},
"msgtype": "m.text"
}"#;
let pdu_event = PduEvent {
event_id: EventId::try_from(format!("$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk"))
.unwrap(),
room_id: RoomId::try_from("!n8f893n9:example.com").unwrap(),
sender: UserId::try_from("@carl:example.com").unwrap(),
origin_server_ts: uint!(400),
kind: EventType::Dummy,
content: serde_json::from_str(content_json).unwrap(),
auth_events: Vec::new(),
state_key: Some("#################################".to_string()),
prev_events: Vec::new(),
depth: uint!(400),
redacts: None,
unsigned: BTreeMap::default(),
hashes: ruma::events::pdu::EventHash::new(
"################################################################".to_string(),
),
signatures: BTreeMap::default(),
};
let pdu_event_size = std::mem::size_of_val(&pdu_event);
let event_id =
EventId::try_from(format!("$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk")).unwrap();
let event_id_size = std::mem::size_of_val(&event_id);
let total_pdu_mem = &pdu_cache.capacity() * (pdu_event_size + event_id_size);
let pdu_cache_size_in_mb =
(std::mem::size_of_val(&pdu_cache) + total_pdu_mem) as i32 / 100_000 as i32;
total_max_cache_size += pdu_cache_size_in_mb;
println!(
"size of filled ({}) pdu_cache is {} MB",
&pdu_cache.capacity(),
pdu_cache_size_in_mb
);
}
{
let auth_chain_cache: LruCache<u64, HashSet<u64>> = LruCache::new(100_000);
let mut a_hash_set: HashSet<u64> = HashSet::new();
a_hash_set.insert(100_000 as u64);
a_hash_set.insert(200_000 as u64);
a_hash_set.insert(300_000 as u64);
let entry_size = std::mem::size_of::<u64>() + std::mem::size_of_val(&a_hash_set);
let all_entry_sizes = &auth_chain_cache.capacity() * entry_size;
let auth_chain_cache_size_in_mb =
(std::mem::size_of_val(&auth_chain_cache) + all_entry_sizes) as i32 / 100_000 as i32;
total_max_cache_size += auth_chain_cache_size_in_mb;
println!(
"size of filled ({}) auth_chain_cache is {} MB",
&auth_chain_cache.capacity(),
auth_chain_cache_size_in_mb
);
}
{
let shorteventid_cache: LruCache<u64, EventId> = LruCache::new(1_000_000);
let event_id =
EventId::try_from(format!("$acR1l0raoZnm60CBwAVgqbZqoO/mYU81xysh1u7XcJk")).unwrap();
let event_id_size = std::mem::size_of_val(&event_id);
let entry_size = std::mem::size_of::<u64>() + event_id_size;
let all_entry_sizes = &shorteventid_cache.capacity() * entry_size;
let shorteventid_cache_size_in_mb =
(std::mem::size_of_val(&shorteventid_cache) + all_entry_sizes) as i32 / 100_000 as i32;
total_max_cache_size += shorteventid_cache_size_in_mb * 2;
println!(
"size of filled ({}) shorteventid_cache / eventidshort_cache is {} MB",
&shorteventid_cache.capacity(),
shorteventid_cache_size_in_mb
);
}
{
let statekeyshort_cache: LruCache<(EventType, String), u64> = LruCache::new(1_000_000);
let a_key = (EventType::Dummy, "###################################".to_string());
let a_value = "#####################################".to_string();
let entry_size = std::mem::size_of_val(&a_key) + std::mem::size_of_val(&a_value);
let all_entry_sizes = &statekeyshort_cache.capacity() * entry_size;
let statekeyshort_cache_size_in_mb =
(std::mem::size_of_val(&statekeyshort_cache) + all_entry_sizes) as i32 / 100_000 as i32;
total_max_cache_size += statekeyshort_cache_size_in_mb * 2;
println!(
"size of filled ({}) statekeyshort_cache / shortstatekey_cache is {} MB",
&statekeyshort_cache.capacity(),
statekeyshort_cache_size_in_mb
);
}
println!("All caches sum up to {} MB", &total_max_cache_size);
}
+4 -4
View File
@@ -422,7 +422,7 @@ impl RoomEdus {
} }
/// Sets all users to offline who have been quiet for too long. /// Sets all users to offline who have been quiet for too long.
fn _presence_maintain( fn presence_maintain(
&self, &self,
rooms: &super::Rooms, rooms: &super::Rooms,
globals: &super::super::globals::Globals, globals: &super::super::globals::Globals,
@@ -489,13 +489,13 @@ impl RoomEdus {
} }
/// Returns an iterator over the most recent presence updates that happened after the event with id `since`. /// Returns an iterator over the most recent presence updates that happened after the event with id `since`.
#[tracing::instrument(skip(self, since, _rooms, _globals))] #[tracing::instrument(skip(self, globals, rooms))]
pub fn presence_since( pub fn presence_since(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
since: u64, since: u64,
_rooms: &super::Rooms, rooms: &super::Rooms,
_globals: &super::super::globals::Globals, globals: &super::super::globals::Globals,
) -> Result<HashMap<UserId, PresenceEvent>> { ) -> Result<HashMap<UserId, PresenceEvent>> {
//self.presence_maintain(rooms, globals)?; //self.presence_maintain(rooms, globals)?;
+13 -18
View File
@@ -84,8 +84,8 @@ pub enum SendingEventType {
pub struct Sending { pub struct Sending {
/// The state for a given state hash. /// The state for a given state hash.
pub(super) servername_educount: Arc<dyn Tree>, // EduCount: Count of last EDU sync pub(super) servername_educount: Arc<dyn Tree>, // EduCount: Count of last EDU sync
pub(super) servernameevent_data: Arc<dyn Tree>, // ServernamEvent = (+ / $)SenderKey / ServerName / UserId + PduId / Id (for edus), Data = EDU content pub(super) servernameevent_data: Arc<dyn Tree>, // ServernamEvent = (+ / $)SenderKey / ServerName / UserId + PduId / * (for edus), Data = EDU content
pub(super) servercurrentevent_data: Arc<dyn Tree>, // ServerCurrentEvents = (+ / $)ServerName / UserId + PduId / Id (for edus), Data = EDU content pub(super) servercurrentevent_data: Arc<dyn Tree>, // ServerCurrentEvents = (+ / $)ServerName / UserId + PduId / * (for edus), Data = EDU content
pub(super) maximum_requests: Arc<Semaphore>, pub(super) maximum_requests: Arc<Semaphore>,
pub sender: mpsc::UnboundedSender<(Vec<u8>, Vec<u8>)>, pub sender: mpsc::UnboundedSender<(Vec<u8>, Vec<u8>)>,
} }
@@ -435,15 +435,10 @@ impl Sending {
} }
#[tracing::instrument(skip(self, server, serialized))] #[tracing::instrument(skip(self, server, serialized))]
pub fn send_reliable_edu( pub fn send_reliable_edu(&self, server: &ServerName, serialized: Vec<u8>) -> Result<()> {
&self,
server: &ServerName,
serialized: Vec<u8>,
id: u64,
) -> Result<()> {
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(&id.to_be_bytes()); key.push(b'*');
self.servernameevent_data.insert(&key, &serialized)?; self.servernameevent_data.insert(&key, &serialized)?;
self.sender.unbounded_send((key, serialized)).unwrap(); self.sender.unbounded_send((key, serialized)).unwrap();
@@ -719,10 +714,10 @@ impl Sending {
OutgoingKind::Appservice(Box::<ServerName>::try_from(server).map_err(|_| { OutgoingKind::Appservice(Box::<ServerName>::try_from(server).map_err(|_| {
Error::bad_database("Invalid server string in server_currenttransaction") Error::bad_database("Invalid server string in server_currenttransaction")
})?), })?),
if value.is_empty() { if event.starts_with(b"*") {
SendingEventType::Pdu(event.to_vec())
} else {
SendingEventType::Edu(value) SendingEventType::Edu(value)
} else {
SendingEventType::Pdu(event.to_vec())
}, },
) )
} else if key.starts_with(b"$") { } else if key.starts_with(b"$") {
@@ -737,10 +732,10 @@ impl Sending {
.ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?; .ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?;
( (
OutgoingKind::Push(user.to_vec(), pushkey.to_vec()), OutgoingKind::Push(user.to_vec(), pushkey.to_vec()),
if value.is_empty() { if event.starts_with(b"*") {
SendingEventType::Pdu(event.to_vec())
} else {
SendingEventType::Edu(value) SendingEventType::Edu(value)
} else {
SendingEventType::Pdu(event.to_vec())
}, },
) )
} else { } else {
@@ -758,10 +753,10 @@ impl Sending {
OutgoingKind::Normal(Box::<ServerName>::try_from(server).map_err(|_| { OutgoingKind::Normal(Box::<ServerName>::try_from(server).map_err(|_| {
Error::bad_database("Invalid server string in server_currenttransaction") Error::bad_database("Invalid server string in server_currenttransaction")
})?), })?),
if value.is_empty() { if event.starts_with(b"*") {
SendingEventType::Pdu(event.to_vec()) SendingEventType::Edu(event[1..].to_vec())
} else { } else {
SendingEventType::Edu(value) SendingEventType::Pdu(event.to_vec())
}, },
) )
}) })
+1 -5
View File
@@ -66,11 +66,7 @@ where
let limit = db.globals.max_request_size(); let limit = db.globals.max_request_size();
let mut handle = data.open(ByteUnit::Byte(limit.into())); let mut handle = data.open(ByteUnit::Byte(limit.into()));
let mut body = Vec::new(); let mut body = Vec::new();
if let Err(_) = handle.read_to_end(&mut body).await { handle.read_to_end(&mut body).await.unwrap();
// Client disconnected
// Missing Token
return Failure((Status::new(582), ()));
}
let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&body).ok(); let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&body).ok();
+213 -852
View File
File diff suppressed because it is too large Load Diff