Compare commits

...
Author SHA1 Message Date
Timo Kösters 0d6ae2e1e7 Merge branch 'thanks' into 'master'
docs: add thanks to

See merge request famedly/conduit!185
2021-09-02 11:10:23 +00:00
Timo Kösters d0baca44f8 docs: add thanks to 2021-09-02 13:05:19 +02:00
Timo Kösters 5536bfdca5 Merge branch 'ci-also-run-for-tags' into 'master'
Also run CI on git tags, not only new commits.

See merge request famedly/conduit!184
2021-09-02 07:33:25 +00:00
Jonas Zohren 3357bbec1e chore: Also run CI on git tags, not only new commits.
Signed-off-by: Jonas Zohren <git-pbkyr@jzohren.de>
2021-09-02 09:17:25 +02:00
Timo Kösters 102ff574ea Merge branch 'readme' into 'master'
docs: update readme and version

See merge request famedly/conduit!180
2021-09-01 21:28:28 +00:00
Timo Kösters 2770ce2cf6 fix: avoid panic 2021-09-01 23:00:24 +02:00
Timo Kösters 7cd7f1923f chore: update dependencies 2021-09-01 22:31:25 +02:00
Timo Kösters 43d693ca19 revert Arc<EventId> commit 2021-09-01 22:30:11 +02:00
Timo Kösters 875b345a5f docs: update readme and version 2021-09-01 22:18:19 +02:00
Timo Kösters 17adf096e9 Merge branch 'server-server-opt' into 'master'
Remove unneeded intermediary container collection

See merge request famedly/conduit!183
2021-09-01 20:02:37 +00:00
Jonas Platte 487601a249 Remove unneeded intermediary container collection 2021-09-01 21:46:05 +02:00
Timo Kösters 27788af022 Merge branch 'batch_keys' into 'master'
Get required keys in batch when joining a room

See merge request famedly/conduit!182
2021-09-01 19:12:21 +00:00
Timo Kösters 4b39d7cb64 fix: batch key fetching 2021-09-01 20:02:34 +02:00
Kurt Roeckx c53d79e287 fixup! Get required keys in batch when joining a room 2021-09-01 19:30:32 +02:00
Kurt Roeckx 984ad5ecd6 fixup! Get required keys in batch when joining a room 2021-09-01 19:30:31 +02:00
Kurt Roeckx b546a5bf15 Let our server signing be valid for 1 week
It was valid for 2 minutes, which can result in the server being
asked too much for something that never changes.
2021-09-01 19:30:31 +02:00
Kurt Roeckx a87519fb71 Get required keys in batch when joining a room
We now ask the trusted server for all keys in 1 request, instead of
asking each server individual for it's own keys.
2021-09-01 19:30:30 +02:00
Timo Kösters 9c3f1a9272 Merge branch 'master' into 'master'
Add Traefik setup, incl. step-by-step, to docker README.

See merge request famedly/conduit!158
2021-09-01 16:04:41 +00:00
Timo Kösters 8518d59a0b Merge branch 'clippy' into 'master'
Fix a bunch of clippy lints

See merge request famedly/conduit!178
2021-09-01 10:47:23 +00:00
Timo Kösters 4e68c22457 Merge branch 'docs' into 'master'
docs: documentation for every endpoint

See merge request famedly/conduit!177
2021-09-01 10:20:13 +00:00
Timo Kösters 73d876643c improvement: make pdu cache capacity configurable 2021-09-01 11:03:45 +02:00
Timo Kösters 22779c21d3 Merge branch 'health_script' into 'master'
Fix healthcheck.sh permissions and rearange ci dockerfile

See merge request famedly/conduit!179
2021-09-01 08:08:22 +00:00
Daniel Wiesenberg 8c584887c9 Fix healthcheck.sh permissions and rearange ci dockerfile 2021-08-31 23:17:32 +02:00
Timo Kösters 33738dbbc2 improvement: stop prev event fetching if too many events fail 2021-08-31 22:04:47 +02:00
Jonas Platte a6bb9bbe68 Fix a bunch of clippy lints 2021-08-31 21:20:03 +02:00
Timo Kösters b9eb39a9c6 docs: documentation for every endpoint 2021-08-31 19:20:34 +02:00
Timo Kösters 364820aae4 Merge branch 'registration-default' into 'master'
Default registration true

See merge request famedly/conduit!176
2021-08-31 17:03:05 +00:00
Timo Kösters ec38411620 Merge branch 'health_script' into 'master'
Move docker healthcheck into dedicated script.

See merge request famedly/conduit!173
2021-08-31 16:59:33 +00:00
Jonathan de Jong 9ec8b7f2b3 registration default true 2021-08-31 18:25:35 +02:00
Daniel Wiesenberg a08ea15695 Use $CI_COMMIT_SHORT_SHA for GIT_REF
Using `$CI_COMMIT_REF_NAME` means we get `master` for every image build,
which is not very useful/informative. Using `$CI_COMMIT_SHORT_SHA`,
on the other hand, makes it possible to see exactly from which commit an
image was built.
2021-08-31 18:03:44 +02:00
Timo Kösters 49dd3567c6 Merge branch 'connection-lifetime' into 'master'
thread_local connections

See merge request famedly/conduit!175
2021-08-30 19:05:22 +00:00
Jonathan de Jong 69df9a0145 add tls 2021-08-30 20:18:48 +02:00
Timo Kösters d0d47675d8 Merge branch 'speed' into 'master'
improvement: call /state_ids less often by using state res

See merge request famedly/conduit!174
2021-08-30 17:32:41 +00:00
Timo Kösters bd4ea14a29 improvement: call /state_ids less often by using state res 2021-08-30 16:07:59 +02:00
Timo Kösters 9033cc86aa Merge branch 'speed' into 'master'
fix: make appservices more efficient

See merge request famedly/conduit!172
2021-08-30 09:14:08 +00:00
Timo Kösters 1b25e78e3a fix: inviting dendrite users 2021-08-30 10:56:41 +02:00
Timo Kösters d57c19802d improvement: don't do state updates if the event was soft failed 2021-08-30 10:46:36 +02:00
Daniel Wiesenberg 9ded40e983 Change healthcheck in ci dockerfile 2021-08-30 09:14:08 +02:00
Daniel Wiesenberg a469ca0461 Move docker healthcheck into dedicated script. 2021-08-29 20:01:38 +02:00
Timo Kösters 632a1343eb fix: make appservices more efficient 2021-08-29 20:00:43 +02:00
Timo Kösters 00c9ad12bd Merge branch 'speed' into 'master'
Speed

See merge request famedly/conduit!168
2021-08-28 18:28:25 +00:00
Daniel Wiesenberg 5800e9b797 Add Traefik setup, incl. step-by-step, to docker README. 2021-08-26 12:26:32 +02:00
55 changed files with 1785 additions and 584 deletions
+6 -1
View File
@@ -19,6 +19,7 @@ variables:
needs: []
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
- if: '$CI_COMMIT_TAG'
interruptible: true
image: "rust:latest"
tags: ["docker"]
@@ -106,6 +107,7 @@ build:release:cargo:x86_64-unknown-linux-musl:
extends: ".build-cargo-shared-settings"
rules:
- if: '$CI_COMMIT_BRANCH'
- if: '$CI_COMMIT_TAG'
cache:
key: "build_cache-$TARGET-debug"
script:
@@ -151,6 +153,7 @@ build:debug:cargo:x86_64-unknown-linux-musl:
needs: [ ]
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
- if: '$CI_COMMIT_TAG'
interruptible: true
image: "rust:latest"
tags: ["docker"]
@@ -217,7 +220,7 @@ build:docker:main:
--context $CI_PROJECT_DIR
--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 "GIT_REF=$CI_COMMIT_REF_NAME"
--build-arg "GIT_REF=$CI_COMMIT_SHORT_SHA"
--dockerfile "$CI_PROJECT_DIR/docker/ci-binaries-packaging.Dockerfile"
--destination "$CI_REGISTRY_IMAGE/conduit:latest"
--destination "$CI_REGISTRY_IMAGE/conduit:alpine"
@@ -227,6 +230,7 @@ build:docker:main:
--destination "$DOCKER_HUB_IMAGE/matrixconduit/matrix-conduit:commit-$CI_COMMIT_SHORT_SHA"
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
- if: '$CI_COMMIT_TAG'
@@ -328,6 +332,7 @@ publish:package:
- "build:cargo-deb:x86_64-unknown-linux-gnu"
rules:
- if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
- if: '$CI_COMMIT_TAG'
image: curlimages/curl:latest
tags: ["docker"]
variables:
Generated
+111 -150
View File
@@ -196,9 +196,9 @@ checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8"
[[package]]
name = "cc"
version = "1.0.69"
version = "1.0.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e70cc2f62c6ce1868963827bd677764c62d07c3d9a3e1fb1177ee1a9ab199eb2"
checksum = "d26a6ce4b6a484fa3edb70f7efa6fc430fd2b87285fe8b84304fd0936faa0dc0"
dependencies = [
"jobserver",
]
@@ -236,7 +236,7 @@ checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
name = "conduit"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"base64 0.13.0",
"bytes",
@@ -248,7 +248,7 @@ dependencies = [
"jsonwebtoken",
"lru-cache",
"num_cpus",
"opentelemetry 0.16.0",
"opentelemetry",
"opentelemetry-jaeger",
"parking_lot",
"pretty_env_logger",
@@ -267,6 +267,7 @@ dependencies = [
"serde_yaml",
"sled",
"thiserror",
"thread_local",
"threadpool",
"tokio",
"tracing",
@@ -274,7 +275,7 @@ dependencies = [
"tracing-opentelemetry",
"tracing-subscriber",
"trust-dns-resolver",
"webpki",
"webpki 0.22.0",
]
[[package]]
@@ -656,9 +657,9 @@ dependencies = [
[[package]]
name = "futures"
version = "0.3.16"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1adc00f486adfc9ce99f77d717836f0c5aa84965eb0b4f051f4e83f7cab53f8b"
checksum = "a12aa0eb539080d55c3f2d45a67c3b58b6b0773c1a3ca2dfec66d58c97fd66ca"
dependencies = [
"futures-channel",
"futures-core",
@@ -671,9 +672,9 @@ dependencies = [
[[package]]
name = "futures-channel"
version = "0.3.16"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74ed2411805f6e4e3d9bc904c95d5d423b89b3b25dc0250aa74729de20629ff9"
checksum = "5da6ba8c3bb3c165d3c7319fc1cc8304facf1fb8db99c5de877183c08a273888"
dependencies = [
"futures-core",
"futures-sink",
@@ -681,15 +682,15 @@ dependencies = [
[[package]]
name = "futures-core"
version = "0.3.16"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af51b1b4a7fdff033703db39de8802c673eb91855f2e0d47dcf3bf2c0ef01f99"
checksum = "88d1c26957f23603395cd326b0ffe64124b818f4449552f960d815cfba83a53d"
[[package]]
name = "futures-executor"
version = "0.3.16"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d0d535a57b87e1ae31437b892713aee90cd2d7b0ee48727cd11fc72ef54761c"
checksum = "45025be030969d763025784f7f355043dc6bc74093e4ecc5000ca4dc50d8745c"
dependencies = [
"futures-core",
"futures-task",
@@ -698,15 +699,15 @@ dependencies = [
[[package]]
name = "futures-io"
version = "0.3.16"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b0e06c393068f3a6ef246c75cdca793d6a46347e75286933e5e75fd2fd11582"
checksum = "522de2a0fe3e380f1bc577ba0474108faf3f6b18321dbf60b3b9c39a75073377"
[[package]]
name = "futures-macro"
version = "0.3.16"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c54913bae956fb8df7f4dc6fc90362aa72e69148e3f39041fbe8742d21e0ac57"
checksum = "18e4a4b95cea4b4ccbcf1c5675ca7c4ee4e9e75eb79944d07defde18068f79bb"
dependencies = [
"autocfg",
"proc-macro-hack",
@@ -717,21 +718,21 @@ dependencies = [
[[package]]
name = "futures-sink"
version = "0.3.16"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0f30aaa67363d119812743aa5f33c201a7a66329f97d1a887022971feea4b53"
checksum = "36ea153c13024fe480590b3e3d4cad89a0cfacecc24577b68f86c6ced9c2bc11"
[[package]]
name = "futures-task"
version = "0.3.16"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbe54a98670017f3be909561f6ad13e810d9a51f3f061b902062ca3da80799f2"
checksum = "1d3d00f4eddb73e498a54394f228cd55853bdf059259e8e7bc6e69d408892e99"
[[package]]
name = "futures-util"
version = "0.3.16"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67eb846bfd58e44a8481a00049e82c43e0ccb5d61f8dc071057cb19249dd4d78"
checksum = "36568465210a3a6ee45e1f165136d68671471a501e632e9a98d96872222b5481"
dependencies = [
"autocfg",
"futures-channel",
@@ -999,7 +1000,7 @@ dependencies = [
"rustls",
"tokio",
"tokio-rustls",
"webpki",
"webpki 0.21.4",
]
[[package]]
@@ -1025,7 +1026,7 @@ dependencies = [
"gif",
"jpeg-decoder",
"num-iter",
"num-rational 0.3.2",
"num-rational",
"num-traits",
"png",
]
@@ -1202,9 +1203,9 @@ dependencies = [
[[package]]
name = "lock_api"
version = "0.4.4"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0382880606dff6d15c9476c416d18690b72742aa7b605bb6dd6ec9030fbf07eb"
checksum = "712a4d093c9976e24e7dbca41db895dabcbac38eb5f4045393d17a95bdfb1109"
dependencies = [
"scopeguard",
]
@@ -1348,20 +1349,6 @@ dependencies = [
"winapi",
]
[[package]]
name = "num"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43db66d1170d347f9a065114077f7dccb00c1b9478c89384490a3425279a4606"
dependencies = [
"num-bigint 0.4.0",
"num-complex",
"num-integer",
"num-iter",
"num-rational 0.4.0",
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.2.6"
@@ -1373,26 +1360,6 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e0d047c1062aa51e256408c560894e5251f08925980e53cf1aa5bd00eec6512"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-complex"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26873667bbbb7c5182d4a37c1add32cdf09f841af72da53318fdb81543c15085"
dependencies = [
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.44"
@@ -1425,18 +1392,6 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d41702bd167c2df5520b384281bc111a4b5efcf7fbc4c9c222c815b07e0a6a6a"
dependencies = [
"autocfg",
"num-bigint 0.4.0",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.14"
@@ -1474,23 +1429,6 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28988d872ab76095a6e6ac88d99b54fd267702734fd7ffe610ca27f533ddb95a"
[[package]]
name = "opentelemetry"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff27b33e30432e7b9854936693ca103d8591b0501f7ae9f633de48cda3bf2a67"
dependencies = [
"async-trait",
"crossbeam-channel",
"futures",
"js-sys",
"lazy_static",
"percent-encoding",
"pin-project",
"rand 0.8.4",
"thiserror",
]
[[package]]
name = "opentelemetry"
version = "0.16.0"
@@ -1518,7 +1456,7 @@ checksum = "db22f492873ea037bc267b35a0e8e4fb846340058cb7c864efe3d0bf23684593"
dependencies = [
"async-trait",
"lazy_static",
"opentelemetry 0.16.0",
"opentelemetry",
"opentelemetry-semantic-conventions",
"thiserror",
"thrift",
@@ -1531,7 +1469,7 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffeac823339e8b0f27b961f4385057bf9f97f2863bc745bd015fd6091f2270e9"
dependencies = [
"opentelemetry 0.16.0",
"opentelemetry",
]
[[package]]
@@ -1555,9 +1493,9 @@ dependencies = [
[[package]]
name = "parking_lot"
version = "0.11.1"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d7744ac029df22dca6284efe4e898991d28e3085c706c972bcd7da4a27a15eb"
checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
dependencies = [
"instant",
"lock_api",
@@ -1566,9 +1504,9 @@ dependencies = [
[[package]]
name = "parking_lot_core"
version = "0.8.3"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7a782938e745763fe6907fc6ba86946d72f49fe7e21de074e08128a99fb018"
checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216"
dependencies = [
"cfg-if 1.0.0",
"instant",
@@ -1725,9 +1663,9 @@ checksum = "bc881b2c22681370c6a780e47af9840ef841837bc98118431d4e1868bd0c1086"
[[package]]
name = "proc-macro2"
version = "1.0.28"
version = "1.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612"
checksum = "b9f5105d4fdaab20335ca9565e106a5d9b82b6219b5ba735731124ac6711d23d"
dependencies = [
"unicode-xid",
]
@@ -2061,8 +1999,9 @@ dependencies = [
[[package]]
name = "ruma"
version = "0.3.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "668031e3108d6a2cfbe6eca271d8698f4593440e71a44afdadcf67ce3cb93c1f"
dependencies = [
"assign",
"js_int",
@@ -2083,7 +2022,8 @@ dependencies = [
[[package]]
name = "ruma-api"
version = "0.18.3"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5f1843792b6749ec1ece62595cf99ad30bf9589c96bb237515235e71da396ea"
dependencies = [
"bytes",
"http",
@@ -2099,7 +2039,8 @@ dependencies = [
[[package]]
name = "ruma-api-macros"
version = "0.18.3"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b18abda5cca94178d08b622bca042e1cbb5eb7d4ebf3a2a81590a3bb3c57008"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2110,7 +2051,8 @@ dependencies = [
[[package]]
name = "ruma-appservice-api"
version = "0.4.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49369332a5f299e832e19661f92d49e08c345c3c6c4ab16e09cb31c5ff6da878"
dependencies = [
"ruma-api",
"ruma-common",
@@ -2124,7 +2066,8 @@ dependencies = [
[[package]]
name = "ruma-client-api"
version = "0.12.2"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9568a222c12cf6220e751484ab78feec28071f85965113a5bb802936a2920ff0"
dependencies = [
"assign",
"bytes",
@@ -2144,7 +2087,8 @@ dependencies = [
[[package]]
name = "ruma-common"
version = "0.6.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d5b7605f58dc0d9cf1848cc7f1af2bae4e4bcd1d2b7a87bbb9864c8a785b91"
dependencies = [
"indexmap",
"js_int",
@@ -2158,8 +2102,9 @@ dependencies = [
[[package]]
name = "ruma-events"
version = "0.24.4"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
version = "0.24.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87801e1207cfebdee02e7997ebf181a1c9837260b78c1b8ce96b896a2bcb3763"
dependencies = [
"indoc",
"js_int",
@@ -2174,8 +2119,9 @@ dependencies = [
[[package]]
name = "ruma-events-macros"
version = "0.24.4"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
version = "0.24.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5da4498845347de88adf1b7da4578e2ca7355ad4ce47b0976f6594bacf958660"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2185,8 +2131,9 @@ dependencies = [
[[package]]
name = "ruma-federation-api"
version = "0.3.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa3d1db1a064ab26484df6ef5d96c384fc053022004f34d96c3b4939e13dc204"
dependencies = [
"js_int",
"ruma-api",
@@ -2201,7 +2148,8 @@ dependencies = [
[[package]]
name = "ruma-identifiers"
version = "0.20.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb417d091e8dd5a633e4e5998231a156049d7fcc221045cfdc0642eb72067732"
dependencies = [
"paste",
"rand 0.8.4",
@@ -2215,7 +2163,8 @@ dependencies = [
[[package]]
name = "ruma-identifiers-macros"
version = "0.20.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c708edad7f605638f26c951cbad7501fbf28ab01009e5ca65ea5a2db74a882b1"
dependencies = [
"quote",
"ruma-identifiers-validation",
@@ -2225,15 +2174,14 @@ dependencies = [
[[package]]
name = "ruma-identifiers-validation"
version = "0.5.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
dependencies = [
"thiserror",
]
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42285e7fb5d5f2d5268e45bb683e36d5c6fd9fc1e11a4559ba3c3521f3bbb2cb"
[[package]]
name = "ruma-identity-service-api"
version = "0.3.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e76e66e24f2d5a31511fbf6c79e79f67a7a6a98ebf48d72381b7d5bb6c09f035"
dependencies = [
"js_int",
"ruma-api",
@@ -2246,7 +2194,8 @@ dependencies = [
[[package]]
name = "ruma-push-gateway-api"
version = "0.3.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ef5b29da7065efc5b1e1a8f61add7543c9ab4ecce5ee0dd1c1c5ecec83fbeec"
dependencies = [
"js_int",
"ruma-api",
@@ -2261,7 +2210,8 @@ dependencies = [
[[package]]
name = "ruma-serde"
version = "0.5.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b2b22aae842e7ecda695e42b7b39d4558959d9d9a27acc2a16acf4f4f7f00c3"
dependencies = [
"bytes",
"form_urlencoded",
@@ -2275,7 +2225,8 @@ dependencies = [
[[package]]
name = "ruma-serde-macros"
version = "0.5.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "243e9bef188b08f94c79bc2f8fd1eb307a9e636b2b8e4571acf8c7be16381d28"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2286,7 +2237,8 @@ dependencies = [
[[package]]
name = "ruma-signatures"
version = "0.9.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a4f64027165b59500162d10d435b1253898bf3ad4f5002cb0d56913fe7f76d7"
dependencies = [
"base64 0.13.0",
"ed25519-dalek",
@@ -2302,12 +2254,12 @@ dependencies = [
[[package]]
name = "ruma-state-res"
version = "0.3.0"
source = "git+https://github.com/DevinR528/ruma?rev=c7860fcb89dbde636e2c83d0636934fb9924f40c#c7860fcb89dbde636e2c83d0636934fb9924f40c"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "518c1afbddfcc5ffac8818a5cf0902709e6eca11aca8f24f6479df6f0601f1ba"
dependencies = [
"itertools 0.10.1",
"js_int",
"maplit",
"ruma-common",
"ruma-events",
"ruma-identifiers",
@@ -2364,7 +2316,7 @@ dependencies = [
"log",
"ring",
"sct",
"webpki",
"webpki 0.21.4",
]
[[package]]
@@ -2425,23 +2377,22 @@ dependencies = [
[[package]]
name = "security-framework"
version = "2.4.0"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b9bd29cdffb8875b04f71c51058f940cf4e390bbfd2ce669c4f22cd70b492a5"
checksum = "525bc1abfda2e1998d152c45cf13e696f76d0a4972310b22fac1658b05df7c87"
dependencies = [
"bitflags",
"core-foundation",
"core-foundation-sys",
"libc",
"num",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.4.0"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19133a286e494cc3311c165c4676ccb1fd47bed45b55f9d71fbd784ad4cea6f8"
checksum = "a9dd14d83160b528b7bfd66439110573efcfbe281b17fc2ca9f39f550d619c7e"
dependencies = [
"core-foundation-sys",
"libc",
@@ -2464,18 +2415,18 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
[[package]]
name = "serde"
version = "1.0.129"
version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1f72836d2aa753853178eda473a3b9d8e4eefdaf20523b919677e6de489f8f1"
checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.129"
version = "1.0.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57ae87ad533d9a56427558b516d0adac283614e347abf85b0dc0cbbf0a249f3"
checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b"
dependencies = [
"proc-macro2",
"quote",
@@ -2484,9 +2435,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.66"
version = "1.0.67"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "336b10da19a12ad094b59d870ebde26a45402e5b470add4b5fd03c5048a32127"
checksum = "a7f9e390c27c3c0ce8bc5d725f6e4d30a29d26659494aa4b17535f7522c5c950"
dependencies = [
"itoa",
"ryu",
@@ -2567,7 +2518,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692ca13de57ce0613a363c8c2f1de925adebc81b04c923ac60c5488bb44abe4b"
dependencies = [
"chrono",
"num-bigint 0.2.6",
"num-bigint",
"num-traits",
]
@@ -2781,18 +2732,18 @@ dependencies = [
[[package]]
name = "thiserror"
version = "1.0.26"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93119e4feac1cbe6c798c34d3a53ea0026b0b1de6a120deef895137c0529bfe2"
checksum = "283d5230e63df9608ac7d9691adc1dfb6e701225436eb64d0b9a7f0a5a04f6ec"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.26"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "060d69a0afe7796bf42e9e2ff91f5ee691fb15c53d38b4b62a9a53eb23164745"
checksum = "fa3884228611f5cd3608e2d409bf7dce832e4eb3135e3f11addbd7e41bd68e71"
dependencies = [
"proc-macro2",
"quote",
@@ -2895,9 +2846,9 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
[[package]]
name = "tokio"
version = "1.10.1"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92036be488bb6594459f2e03b60e42df6f937fe6ca5c5ffdcb539c6b84dc40f5"
checksum = "b4efe6fc2395938c8155973d7be49fe8d03a843726e285e100a8a383cc0154ce"
dependencies = [
"autocfg",
"bytes",
@@ -2931,7 +2882,7 @@ checksum = "bc6844de72e57df1980054b38be3a9f4702aba4858be64dd700181a8a6d0e1b6"
dependencies = [
"rustls",
"tokio",
"webpki",
"webpki 0.21.4",
]
[[package]]
@@ -3042,11 +2993,11 @@ dependencies = [
[[package]]
name = "tracing-opentelemetry"
version = "0.14.0"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c47440f2979c4cd3138922840eec122e3c0ba2148bc290f756bd7fd60fc97fff"
checksum = "599f388ecb26b28d9c1b2e4437ae019a7b336018b45ed911458cd9ebf91129f6"
dependencies = [
"opentelemetry 0.15.0",
"opentelemetry",
"tracing",
"tracing-core",
"tracing-log",
@@ -3148,9 +3099,9 @@ dependencies = [
[[package]]
name = "typenum"
version = "1.13.0"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f6906492a7cd215bfa4cf595b600146ccfac0c79bcbd1f3000162af5e8b06"
checksum = "b63708a265f51345575b27fe43f9500ad611579e764c79edbc2037b1121959ec"
[[package]]
name = "ubyte"
@@ -3350,6 +3301,16 @@ dependencies = [
"untrusted",
]
[[package]]
name = "webpki"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd"
dependencies = [
"ring",
"untrusted",
]
[[package]]
name = "weezl"
version = "0.1.5"
+14 -13
View File
@@ -6,7 +6,7 @@ authors = ["timokoesters <timo@koesters.xyz>"]
homepage = "https://conduit.rs"
repository = "https://gitlab.com/famedly/conduit"
readme = "README.md"
version = "0.1.0"
version = "0.2.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -18,29 +18,29 @@ edition = "2018"
rocket = { version = "0.5.0-rc.1", features = ["tls"] } # Used to handle requests
# Used for matrix spec type definitions and helpers
#ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { git = "https://github.com/ruma/ruma", rev = "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/DevinR528/ruma", rev = "c7860fcb89dbde636e2c83d0636934fb9924f40c", 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 = { 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
tokio = "1.8.2"
tokio = "1.11.0"
# Used for storing data permanently
sled = { version = "0.34.6", features = ["compression", "no_metrics"], optional = true }
#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
bytes = "1.0.1"
bytes = "1.1.0"
# Used for rocket<->ruma conversions
http = "0.2.4"
# Used to find data directory for default db path
directories = "3.0.2"
# Used for ruma wrapper
serde_json = { version = "1.0.64", features = ["raw_value"] }
serde_json = { version = "1.0.67", features = ["raw_value"] }
# Used for appservice registration files
serde_yaml = "0.8.17"
serde_yaml = "0.8.20"
# Used for pdu definition
serde = "1.0.126"
serde = "1.0.130"
# Used for secure identifiers
rand = "0.8.4"
# Used to hash passwords
@@ -50,9 +50,9 @@ reqwest = { version = "0.11.4", default-features = false, features = ["rustls-tl
# Custom TLS verifier
rustls = { version = "0.19.1", features = ["dangerous_configuration"] }
rustls-native-certs = "0.5.0"
webpki = "0.21.0"
webpki = "0.22.0"
# Used for conduit::Error type
thiserror = "1.0.26"
thiserror = "1.0.28"
# Used to generate thumbnails for images
image = { version = "0.23.14", default-features = false, features = ["jpeg", "png", "gif"] }
# Used to encode server public key
@@ -67,19 +67,20 @@ regex = "1.5.4"
jsonwebtoken = "7.2.0"
# Performance measurements
tracing = { version = "0.1.26", features = ["release_max_level_warn"] }
tracing-subscriber = "0.2.19"
tracing-opentelemetry = "0.14.0"
tracing-subscriber = "0.2.20"
tracing-opentelemetry = "0.15.0"
tracing-flame = "0.1.0"
opentelemetry = { version = "0.16.0", features = ["rt-tokio"] }
opentelemetry-jaeger = { version = "0.15.0", features = ["rt-tokio"] }
pretty_env_logger = "0.4.0"
lru-cache = "0.1.2"
rusqlite = { version = "0.25.3", optional = true, features = ["bundled"] }
parking_lot = { version = "0.11.1", optional = true }
parking_lot = { version = "0.11.2", optional = true }
crossbeam = { version = "0.8.1", optional = true }
num_cpus = "1.13.0"
threadpool = "1.8.1"
heed = { git = "https://github.com/timokoesters/heed.git", rev = "f6f825da7fb2c758867e05ad973ef800a6fe1d5d", optional = true }
thread_local = "1.1.3"
[features]
default = ["conduit_bin", "backend_sqlite"]
+18 -7
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:
```
```bash
sudo adduser --system conduit --no-create-home
```
@@ -107,8 +107,8 @@ port = 6167
# Max size for uploads
max_request_size = 20_000_000 # in bytes
# Disabling registration means no new users will be able to register on this server
allow_registration = false
# Enables registration. If set to false, no users can register on this server.
allow_registration = true
# Disable encryption, so no new encrypted rooms can be created
# 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.
To do that you can run this command on Debian:
```
```bash
sudo chown -R conduit:nogroup /etc/matrix-conduit
```
If you use the default database path you also need to run this:
```
```bash
sudo mkdir -p /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:
```
```apache
Listen 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
http section of `/etc/nginx/nginx.conf`
```
```nginx
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
@@ -231,4 +231,15 @@ Set it to start automatically when your system boots with:
$ 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).
+13 -11
View File
@@ -7,25 +7,29 @@
# Alpine build image to build Conduit's statically compiled binary
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
# from the official git repository. Defaults to the git repo.
ARG LOCAL=false
# Specifies which revision/commit is build. Defaults to HEAD
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 . .
# Build it from the copied local files or from the official git repository
RUN if [[ $LOCAL == "true" ]]; then \
mv ./docker/healthcheck.sh . ; \
echo "Building from local source..." ; \
cargo install --path . ; \
else \
cargo install --git "https://gitlab.com/famedly/conduit.git" --rev ${GIT_REF}; \
echo "Building revision '${GIT_REF}' from online source..." ; \
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
########################## RUNTIME IMAGE ##########################
@@ -64,6 +68,7 @@ EXPOSE 6167
# /srv/conduit and create data folder for database
RUN mkdir -p /srv/conduit/.local/share/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
# https://git.alpinelinux.org/aports/tree/main/nginx/nginx.pre-install
@@ -82,10 +87,7 @@ RUN apk add --no-cache \
libgcc
# Test if Conduit is still alive, uses the same endpoint as Element
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
HEALTHCHECK --start-period=5s --interval=60s CMD ./healthcheck.sh
# Set user to www-data
USER www-data
+26 -63
View File
@@ -3,90 +3,42 @@
#### What is the goal?
A fast Matrix homeserver that's easy to set up and just works. You can install
An efficient 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,
friends or company.
#### Can I try it out?
Yes! Just open a Matrix client (<https://app.element.io> or Element Android for
example) and register on the `https://conduit.koesters.xyz` homeserver.
Yes! You can test our Conduit instance by opening a Matrix client (<https://app.element.io> or Element Android for
example) and registering on the `conduit.rs` homeserver.
#### What is it built on?
- [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
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
HQ.
#### What is the current status?
Conduit can already be used chat with other users on Conduit, chat with users
from other Matrix servers and even to chat with users on other platforms using
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.
As of 2021-09-01, Conduit is Beta, meaning 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.
There are still a few important features missing:
- Database stability (currently you might have to do manual upgrades or even wipe the db for new versions)
- Edge cases for end-to-end encryption over federation
- Typing and presence over federation
- Lots of testing
- E2EE verification over federation
- Outgoing read receipts, typing, presence over federation
Check out the [Conduit 1.0 Release Milestone](https://gitlab.com/famedly/conduit/-/milestones/3).
#### How can I deploy my own?
##### Deploy
Simple install (this was tested the most): [DEPLOY.md](DEPLOY.md)\
Debian package: [debian/README.Debian](debian/README.Debian)\
Docker: [docker/README.md](docker/README.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)
If you want to connect an Appservice to Conduit, take a look at [APPSERVICES.md](APPSERVICES.md).
#### How can I contribute?
@@ -98,6 +50,17 @@ Or build and run it with docker or docker-compose. [Read more](docker/README.md)
3. Fork the repo and work on the issue. #conduit:nordgedanken.dev is happy to help :)
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
Liberapay: <https://liberapay.com/timokoesters/>\
+2 -2
View File
@@ -22,8 +22,8 @@ port = 6167
# Max size for uploads
max_request_size = 20_000_000 # in bytes
# Disable registration. No new users will be able to register on this server
#allow_registration = false
# Enables registration. If set to false, no users can register on this server.
allow_registration = true
# Disable encryption, so no new encrypted rooms can be created
# Note: existing rooms will continue to work
+2 -2
View File
@@ -62,8 +62,8 @@ port = ${CONDUIT_PORT}
# Max size for uploads
max_request_size = 20_000_000 # in bytes
# Disable registration. No new users will be able to register on this server.
#allow_registration = false
# Enables registration. If set to false, no users can register on this server.
allow_registration = true
# Disable encryption, so no new encrypted rooms can be created.
# Note: Existing rooms will continue to work.
+1 -1
View File
@@ -27,6 +27,7 @@ services:
environment:
CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
CONDUIT_ALLOW_REGISTRATION: 'true'
### Uncomment and change values as desired
# CONDUIT_ADDRESS: 0.0.0.0
# CONDUIT_PORT: 6167
@@ -34,7 +35,6 @@ services:
# 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_ALLOW_JAEGER: 'false'
# CONDUIT_ALLOW_REGISTRATION : 'false'
# CONDUIT_ALLOW_ENCRYPTION: 'false'
# CONDUIT_ALLOW_FEDERATION: 'false'
# CONDUIT_DATABASE_PATH: /srv/conduit/.local/share/conduit
+63 -5
View File
@@ -40,18 +40,27 @@ which also will tag the resulting image as `matrixconduit/matrix-conduit:latest`
After building the image you can simply run it with
``` bash
docker run -d -p 8448:8000 -v ~/conduit.toml:/srv/conduit/conduit.toml -v db:/srv/conduit/.local/share/conduit matrixconduit/matrix-conduit:latest
docker run -d -p 8448:6167 -v ~/conduit.toml:/srv/conduit/conduit.toml -v db:/srv/conduit/.local/share/conduit matrixconduit/matrix-conduit:latest
```
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).
or you can skip the build step and pull the image from one of the following registries:
| 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
too pass `-e CONDUIT_CONFIG=""` into your container. For an overview of possible values, please take a look at the `docker-compose.yml` file.
to pass `-e CONDUIT_CONFIG=""` into your container. For an overview of possible values, please take a look at the `docker-compose.yml` file.
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
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.
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
Conduit can be found [here](../DEPLOY.md).
### Build
@@ -67,8 +76,57 @@ This will also start the container right afterwards, so if want it to run in det
### Run
If you already have built the image, you can just start the container and everything else in the compose file in detached mode with:
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:
``` bash
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.
+12 -13
View File
@@ -9,6 +9,12 @@
FROM alpine:3.14
# Install packages needed to run Conduit
RUN apk add --no-cache \
ca-certificates \
curl \
libgcc
ARG CREATED
ARG VERSION
ARG GIT_REF
@@ -36,6 +42,10 @@ EXPOSE 6167
# create data folder for database
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
# https://git.alpinelinux.org/aports/tree/main/nginx/nginx.pre-install
RUN set -x ; \
@@ -45,18 +55,11 @@ RUN set -x ; \
# Change ownership of Conduit files to www-data user and group
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
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
HEALTHCHECK --start-period=5s --interval=60s CMD ./healthcheck.sh
# Set user to www-data
USER www-data
@@ -64,7 +67,3 @@ USER www-data
WORKDIR /srv/conduit
# Run 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,6 +10,29 @@ services:
- "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.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
# element-web:
+11 -1
View File
@@ -27,6 +27,7 @@ services:
environment:
CONDUIT_SERVER_NAME: localhost:6167 # replace with your own name
CONDUIT_TRUSTED_SERVERS: '["matrix.org"]'
CONDUIT_ALLOW_REGISTRATION : 'true'
### Uncomment and change values as desired
# CONDUIT_ADDRESS: 0.0.0.0
# CONDUIT_PORT: 6167
@@ -34,13 +35,22 @@ services:
# 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_ALLOW_JAEGER: 'false'
# CONDUIT_ALLOW_REGISTRATION : 'false'
# CONDUIT_ALLOW_ENCRYPTION: 'false'
# CONDUIT_ALLOW_FEDERATION: 'false'
# CONDUIT_DATABASE_PATH: /srv/conduit/.local/share/conduit
# CONDUIT_WORKERS: 10
# 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.
### 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
+13
View File
@@ -0,0 +1,13 @@
#!/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
+1 -1
View File
@@ -9,7 +9,7 @@ use std::{
};
use tracing::warn;
pub async fn send_request<T: OutgoingRequest>(
pub(crate) async fn send_request<T: OutgoingRequest>(
globals: &crate::database::globals::Globals,
registration: serde_yaml::Value,
request: T,
+42 -21
View File
@@ -40,8 +40,12 @@ const GUEST_NAME_LENGTH: usize = 10;
///
/// Checks if a username is valid and available on this server.
///
/// - Returns true if no user or appservice on this server claimed this username
/// - This will not reserve the username, so the username might become invalid when trying to register
/// Conditions for returning true:
/// - The user id is not historical
/// - 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(
feature = "conduit_bin",
get("/_matrix/client/r0/register/available", data = "<body>")
@@ -80,11 +84,15 @@ pub async fn get_register_available_route(
///
/// Register an account on this homeserver.
///
/// - Returns the device id and access_token unless `inhibit_login` is true
/// - When registering a guest account, all parameters except initial_device_display_name will be
/// ignored
/// - Creates a new account and a device for it
/// - The account will be populated with default account data
/// You can use [`GET /_matrix/client/r0/register/available`](fn.get_register_available_route.html)
/// to check if the user id is valid and available.
///
/// - Only works if registration is enabled
/// - If type is guest: ignores all parameters except initial_device_display_name
/// - 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(
feature = "conduit_bin",
post("/_matrix/client/r0/register", data = "<body>")
@@ -129,7 +137,7 @@ pub async fn register_route(
))?;
// Check if username is creative enough
if !missing_username && db.users.exists(&user_id)? {
if db.users.exists(&user_id)? {
return Err(Error::BadRequest(
ErrorKind::UserInUse,
"Desired user ID is already taken.",
@@ -193,12 +201,12 @@ pub async fn register_route(
// Create user
db.users.create(&user_id, password)?;
// Default to pretty displayname
let displayname = format!("{} ⚡️", user_id.localpart());
db.users
.set_displayname(&user_id, Some(displayname.clone()))?;
// Initial data
// Initial account data
db.account_data.update(
None,
&user_id,
@@ -211,6 +219,7 @@ pub async fn register_route(
&db.globals,
)?;
// Inhibit login does not work for guests
if !is_guest && body.inhibit_login {
return Ok(register::Response {
access_token: None,
@@ -231,7 +240,7 @@ pub async fn register_route(
// Generate new token for the device
let token = utils::random_string(TOKEN_LENGTH);
// Add device
// Create device for this account
db.users.create_device(
&user_id,
&device_id,
@@ -239,7 +248,7 @@ pub async fn register_route(
body.initial_device_display_name.clone(),
)?;
// If this is the first user on this server, create the admins room
// If this is the first user on this server, create the admin room
if db.users.count()? == 1 {
// Create a user for the server
let conduit_user = UserId::parse_with_server_name("conduit", db.globals.server_name())
@@ -498,8 +507,8 @@ pub async fn register_route(
PduBuilder {
event_type: EventType::RoomMessage,
content: serde_json::to_value(message::MessageEventContent::text_html(
"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(),
"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(),
"## 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(),
"<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(),
))
.expect("event is valid, we just created it"),
unsigned: None,
@@ -529,9 +538,16 @@ pub async fn register_route(
///
/// Changes the password of this account.
///
/// - Invalidates all other access tokens if logout_devices is true
/// - Deletes all other devices and most of their data (to-device events, last seen, etc.) if
/// logout_devices is true
/// - Requires UIAA to verify user password
/// - Changes the password of the sender user
/// - The password hash is calculated using argon2 with 32 character salt, the plain password is
/// 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(
feature = "conduit_bin",
post("/_matrix/client/r0/account/password", data = "<body>")
@@ -598,9 +614,9 @@ pub async fn change_password_route(
/// # `GET _matrix/client/r0/account/whoami`
///
/// Get user_id of this account.
/// Get user_id of the sender user.
///
/// - Also works for Application Services
/// Note: Also works for Application Services
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/account/whoami", data = "<body>")
@@ -616,11 +632,13 @@ pub async fn whoami_route(body: Ruma<whoami::Request>) -> ConduitResult<whoami::
/// # `POST /_matrix/client/r0/account/deactivate`
///
/// Deactivate this user's account
/// Deactivate sender user account.
///
/// - Leaves all rooms and rejects all invitations
/// - Invalidates all access tokens
/// - Deletes all devices
/// - Deletes all device metadata (device id, device display name, last seen ip, last seen ts)
/// - Forgets all to-device events
/// - Triggers device list updates
/// - Removes ability to log in again
#[cfg_attr(
feature = "conduit_bin",
@@ -667,6 +685,7 @@ pub async fn deactivate_route(
}
// Leave all joined rooms and reject all invitations
// TODO: work over federation invites
let all_rooms = db
.rooms
.rooms_joined(&sender_user)
@@ -730,6 +749,8 @@ pub async fn deactivate_route(
/// # `GET _matrix/client/r0/account/3pid`
///
/// Get a list of third party identifiers associated with this account.
///
/// - Currently always returns empty list
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/account/3pid", data = "<body>")
+31 -1
View File
@@ -15,6 +15,9 @@ use ruma::{
#[cfg(feature = "conduit_bin")]
use rocket::{delete, get, put};
/// # `PUT /_matrix/client/r0/directory/room/{roomAlias}`
///
/// Creates a new room alias on this server.
#[cfg_attr(
feature = "conduit_bin",
put("/_matrix/client/r0/directory/room/<_>", data = "<body>")
@@ -24,6 +27,13 @@ pub async fn create_alias_route(
db: DatabaseGuard,
body: Ruma<create_alias::Request<'_>>,
) -> 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() {
return Err(Error::Conflict("Alias already exists."));
}
@@ -36,6 +46,12 @@ pub async fn create_alias_route(
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(
feature = "conduit_bin",
delete("/_matrix/client/r0/directory/room/<_>", data = "<body>")
@@ -45,13 +61,27 @@ pub async fn delete_alias_route(
db: DatabaseGuard,
body: Ruma<delete_alias::Request<'_>>,
) -> 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)?;
// TODO: update alt_aliases?
db.flush()?;
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(
feature = "conduit_bin",
get("/_matrix/client/r0/directory/room/<_>", data = "<body>")
@@ -64,7 +94,7 @@ pub async fn get_alias_route(
get_alias_helper(&db, &body.room_alias).await
}
pub async fn get_alias_helper(
pub(crate) async fn get_alias_helper(
db: &Database,
room_alias: &RoomAliasId,
) -> ConduitResult<get_alias::Response> {
+89
View File
@@ -12,6 +12,9 @@ use ruma::api::client::{
#[cfg(feature = "conduit_bin")]
use rocket::{delete, get, post, put};
/// # `POST /_matrix/client/r0/room_keys/version`
///
/// Creates a new backup.
#[cfg_attr(
feature = "conduit_bin",
post("/_matrix/client/unstable/room_keys/version", data = "<body>")
@@ -31,6 +34,9 @@ pub async fn create_backup_route(
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(
feature = "conduit_bin",
put("/_matrix/client/unstable/room_keys/version/<_>", data = "<body>")
@@ -49,6 +55,9 @@ pub async fn update_backup_route(
Ok(update_backup::Response {}.into())
}
/// # `GET /_matrix/client/r0/room_keys/version`
///
/// Get information about the latest backup version.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/version", data = "<body>")
@@ -77,6 +86,9 @@ pub async fn get_latest_backup_route(
.into())
}
/// # `GET /_matrix/client/r0/room_keys/version`
///
/// Get information about an existing backup.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/version/<_>", data = "<body>")
@@ -104,6 +116,11 @@ pub async fn get_backup_route(
.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(
feature = "conduit_bin",
delete("/_matrix/client/unstable/room_keys/version/<_>", data = "<body>")
@@ -122,7 +139,13 @@ pub async fn delete_backup_route(
Ok(delete_backup::Response {}.into())
}
/// # `PUT /_matrix/client/r0/room_keys/keys`
///
/// 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(
feature = "conduit_bin",
put("/_matrix/client/unstable/room_keys/keys", data = "<body>")
@@ -134,6 +157,18 @@ pub async fn add_backup_keys_route(
) -> ConduitResult<add_backup_keys::Response> {
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 (session_id, key_data) in &room.sessions {
db.key_backups.add_key(
@@ -156,7 +191,13 @@ pub async fn add_backup_keys_route(
.into())
}
/// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}`
///
/// 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(
feature = "conduit_bin",
put("/_matrix/client/unstable/room_keys/keys/<_>", data = "<body>")
@@ -168,6 +209,18 @@ pub async fn add_backup_key_sessions_route(
) -> ConduitResult<add_backup_key_sessions::Response> {
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 {
db.key_backups.add_key(
&sender_user,
@@ -188,7 +241,13 @@ pub async fn add_backup_key_sessions_route(
.into())
}
/// # `PUT /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
///
/// 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(
feature = "conduit_bin",
put("/_matrix/client/unstable/room_keys/keys/<_>/<_>", data = "<body>")
@@ -200,6 +259,18 @@ pub async fn add_backup_key_session_route(
) -> ConduitResult<add_backup_key_session::Response> {
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(
&sender_user,
&body.version,
@@ -218,6 +289,9 @@ pub async fn add_backup_key_session_route(
.into())
}
/// # `GET /_matrix/client/r0/room_keys/keys`
///
/// Retrieves all keys from the backup.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/keys", data = "<body>")
@@ -234,6 +308,9 @@ pub async fn get_backup_keys_route(
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(
feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/keys/<_>", data = "<body>")
@@ -252,6 +329,9 @@ pub async fn get_backup_key_sessions_route(
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(
feature = "conduit_bin",
get("/_matrix/client/unstable/room_keys/keys/<_>/<_>", data = "<body>")
@@ -274,6 +354,9 @@ pub async fn get_backup_key_session_route(
Ok(get_backup_key_session::Response { key_data }.into())
}
/// # `DELETE /_matrix/client/r0/room_keys/keys`
///
/// Delete the keys from the backup.
#[cfg_attr(
feature = "conduit_bin",
delete("/_matrix/client/unstable/room_keys/keys", data = "<body>")
@@ -297,6 +380,9 @@ pub async fn delete_backup_keys_route(
.into())
}
/// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}`
///
/// Delete the keys from the backup for a given room.
#[cfg_attr(
feature = "conduit_bin",
delete("/_matrix/client/unstable/room_keys/keys/<_>", data = "<body>")
@@ -320,6 +406,9 @@ pub async fn delete_backup_key_sessions_route(
.into())
}
/// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}`
///
/// Delete a key from the backup.
#[cfg_attr(
feature = "conduit_bin",
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 information on this server's supported feature set and other relevent capabilities.
/// Get information on the supported feature set and other relevent capabilities of this server.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/capabilities", data = "<_body>")
+12 -2
View File
@@ -16,6 +16,9 @@ use serde_json::{json, value::RawValue as RawJsonValue};
#[cfg(feature = "conduit_bin")]
use rocket::{get, put};
/// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}`
///
/// Sets some account data for the sender user.
#[cfg_attr(
feature = "conduit_bin",
put("/_matrix/client/r0/user/<_>/account_data/<_>", data = "<body>")
@@ -48,6 +51,9 @@ pub async fn set_global_account_data_route(
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(
feature = "conduit_bin",
put(
@@ -83,6 +89,9 @@ pub async fn set_room_account_data_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/user/<_>/account_data/<_>", data = "<body>")
@@ -98,7 +107,6 @@ pub async fn get_global_account_data_route(
.account_data
.get::<Box<RawJsonValue>>(None, sender_user, body.event_type.clone().into())?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
db.flush()?;
let account_data = serde_json::from_str::<ExtractGlobalEventContent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
@@ -107,6 +115,9 @@ pub async fn get_global_account_data_route(
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(
feature = "conduit_bin",
get(
@@ -129,7 +140,6 @@ pub async fn get_room_account_data_route(
body.event_type.clone().into(),
)?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "Data not found."))?;
db.flush()?;
let account_data = serde_json::from_str::<ExtractRoomEventContent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
+6
View File
@@ -5,6 +5,12 @@ use std::convert::TryFrom;
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/context/<_>", data = "<body>")
+29
View File
@@ -11,6 +11,9 @@ use super::SESSION_ID_LENGTH;
#[cfg(feature = "conduit_bin")]
use rocket::{delete, get, post, put};
/// # `GET /_matrix/client/r0/devices`
///
/// Get metadata on all devices of the sender user.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/devices", data = "<body>")
@@ -31,6 +34,9 @@ pub async fn get_devices_route(
Ok(get_devices::Response { devices }.into())
}
/// # `GET /_matrix/client/r0/devices/{deviceId}`
///
/// Get metadata on a single device of the sender user.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/devices/<_>", data = "<body>")
@@ -50,6 +56,9 @@ pub async fn get_device_route(
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(
feature = "conduit_bin",
put("/_matrix/client/r0/devices/<_>", data = "<body>")
@@ -76,6 +85,15 @@ pub async fn update_device_route(
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(
feature = "conduit_bin",
delete("/_matrix/client/r0/devices/<_>", data = "<body>")
@@ -128,6 +146,17 @@ pub async fn delete_device_route(
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(
feature = "conduit_bin",
post("/_matrix/client/r0/delete_devices", data = "<body>")
+20 -3
View File
@@ -28,6 +28,11 @@ use tracing::{info, warn};
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
post("/_matrix/client/r0/publicRooms", data = "<body>")
@@ -48,6 +53,11 @@ pub async fn get_public_rooms_filtered_route(
.await
}
/// # `GET /_matrix/client/r0/publicRooms`
///
/// Lists the public rooms on this server.
///
/// - Rooms are ordered by the number of joined members
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/publicRooms", data = "<body>")
@@ -77,6 +87,11 @@ pub async fn get_public_rooms_route(
.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(
feature = "conduit_bin",
put("/_matrix/client/r0/directory/list/room/<_>", data = "<body>")
@@ -107,6 +122,9 @@ pub async fn set_room_visibility_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/directory/list/room/<_>", data = "<body>")
@@ -126,7 +144,7 @@ pub async fn get_room_visibility_route(
.into())
}
pub async fn get_public_rooms_filtered_helper(
pub(crate) async fn get_public_rooms_filtered_helper(
db: &Database,
server: Option<&ServerName>,
limit: Option<UInt>,
@@ -233,8 +251,7 @@ pub async fn get_public_rooms_filtered_helper(
.map_err(|_| {
Error::bad_database("Invalid room name event in database.")
})?
.name
.map(|n| n.to_owned().into()))
.name)
})?,
num_joined_members: db
.rooms
+6
View File
@@ -4,6 +4,9 @@ use ruma::api::client::r0::filter::{self, create_filter, get_filter};
#[cfg(feature = "conduit_bin")]
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/<_>"))]
#[tracing::instrument]
pub async fn get_filter_route() -> ConduitResult<get_filter::Response> {
@@ -18,6 +21,9 @@ pub async fn get_filter_route() -> ConduitResult<get_filter::Response> {
.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"))]
#[tracing::instrument]
pub async fn create_filter_route() -> ConduitResult<create_filter::Response> {
+32 -2
View File
@@ -24,6 +24,12 @@ use std::collections::{BTreeMap, HashMap, HashSet};
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
post("/_matrix/client/r0/keys/upload", data = "<body>")
@@ -49,6 +55,7 @@ pub async fn upload_keys_route(
}
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
if db
.users
@@ -73,6 +80,13 @@ pub async fn upload_keys_route(
.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(
feature = "conduit_bin",
post("/_matrix/client/r0/keys/query", data = "<body>")
@@ -95,6 +109,9 @@ pub async fn get_keys_route(
Ok(response.into())
}
/// # `POST /_matrix/client/r0/keys/claim`
///
/// Claims one-time keys
#[cfg_attr(
feature = "conduit_bin",
post("/_matrix/client/r0/keys/claim", data = "<body>")
@@ -111,6 +128,11 @@ pub async fn claim_keys_route(
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(
feature = "conduit_bin",
post("/_matrix/client/unstable/keys/device_signing/upload", data = "<body>")
@@ -172,6 +194,9 @@ pub async fn upload_signing_keys_route(
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(
feature = "conduit_bin",
post("/_matrix/client/unstable/keys/signatures/upload", data = "<body>")
@@ -233,6 +258,11 @@ pub async fn upload_signatures_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/keys/changes", data = "<body>")
@@ -284,7 +314,7 @@ pub async fn get_key_changes_route(
.into())
}
pub async fn get_keys_helper<F: Fn(&UserId) -> bool>(
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
sender_user: Option<&UserId>,
device_keys_input: &BTreeMap<UserId, Vec<Box<DeviceId>>>,
allowed_signatures: F,
@@ -409,7 +439,7 @@ pub async fn get_keys_helper<F: Fn(&UserId) -> bool>(
})
}
pub async fn claim_keys_helper(
pub(crate) async fn claim_keys_helper(
one_time_keys_input: &BTreeMap<UserId, BTreeMap<Box<DeviceId>, DeviceKeyAlgorithm>>,
db: &Database,
) -> Result<claim_keys::Response> {
+19
View File
@@ -12,6 +12,9 @@ use rocket::{get, post};
const MXC_LENGTH: usize = 32;
/// # `GET /_matrix/media/r0/config`
///
/// Returns max upload size.
#[cfg_attr(feature = "conduit_bin", get("/_matrix/media/r0/config"))]
#[tracing::instrument(skip(db))]
pub async fn get_media_config_route(
@@ -23,6 +26,12 @@ pub async fn get_media_config_route(
.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(
feature = "conduit_bin",
post("/_matrix/media/r0/upload", data = "<body>")
@@ -61,6 +70,11 @@ pub async fn create_content_route(
.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(
feature = "conduit_bin",
get("/_matrix/media/r0/download/<_>/<_>", data = "<body>")
@@ -114,6 +128,11 @@ 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(
feature = "conduit_bin",
get("/_matrix/media/r0/thumbnail/<_>/<_>", data = "<body>")
+81 -21
View File
@@ -5,7 +5,6 @@ use crate::{
server_server, utils, ConduitResult, Database, Error, Result, Ruma,
};
use member::{MemberEventContent, MembershipState};
use rocket::futures;
use ruma::{
api::{
client::{
@@ -38,6 +37,12 @@ use tracing::{debug, error, warn};
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/join", data = "<body>")
@@ -79,6 +84,12 @@ pub async fn join_room_by_id_route(
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(
feature = "conduit_bin",
post("/_matrix/client/r0/join/<_>", data = "<body>")
@@ -133,6 +144,11 @@ pub async fn join_room_by_id_or_alias_route(
.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(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/leave", data = "<body>")
@@ -151,6 +167,9 @@ pub async fn leave_room_route(
Ok(leave_room::Response::new().into())
}
/// # `POST /_matrix/client/r0/rooms/{roomId}/invite`
///
/// Tries to send an invite event into the room.
#[cfg_attr(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/invite", data = "<body>")
@@ -171,6 +190,9 @@ pub async fn invite_user_route(
}
}
/// # `POST /_matrix/client/r0/rooms/{roomId}/kick`
///
/// Tries to send a kick event into the room.
#[cfg_attr(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/kick", data = "<body>")
@@ -234,6 +256,9 @@ pub async fn kick_user_route(
Ok(kick_user::Response::new().into())
}
/// # `POST /_matrix/client/r0/rooms/{roomId}/ban`
///
/// Tries to send a ban event into the room.
#[cfg_attr(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/ban", data = "<body>")
@@ -307,6 +332,9 @@ pub async fn ban_user_route(
Ok(ban_user::Response::new().into())
}
/// # `POST /_matrix/client/r0/rooms/{roomId}/unban`
///
/// Tries to send an unban event into the room.
#[cfg_attr(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/unban", data = "<body>")
@@ -369,6 +397,14 @@ pub async fn unban_user_route(
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(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/forget", data = "<body>")
@@ -387,6 +423,9 @@ pub async fn forget_room_route(
Ok(forget_room::Response::new().into())
}
/// # `POST /_matrix/client/r0/joined_rooms`
///
/// Lists all rooms the user has joined.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/joined_rooms", data = "<body>")
@@ -408,6 +447,11 @@ pub async fn joined_rooms_route(
.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(
feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/members", data = "<body>")
@@ -419,6 +463,7 @@ pub async fn get_member_events_route(
) -> ConduitResult<get_member_events::Response> {
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)? {
return Err(Error::BadRequest(
ErrorKind::Forbidden,
@@ -438,6 +483,12 @@ pub async fn get_member_events_route(
.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(
feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/joined_members", data = "<body>")
@@ -449,11 +500,7 @@ pub async fn joined_members_route(
) -> ConduitResult<joined_members::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !db
.rooms
.is_joined(&sender_user, &body.room_id)
.unwrap_or(false)
{
if !db.rooms.is_joined(&sender_user, &body.room_id)? {
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"You aren't a member of the room.",
@@ -619,14 +666,19 @@ async fn join_room_by_id_helper(
let mut state = HashMap::new();
let pub_key_map = RwLock::new(BTreeMap::new());
for result in futures::future::join_all(
send_join_response
server_server::fetch_join_signing_keys(
&send_join_response,
&room_version,
&pub_key_map,
&db,
)
.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)),
)
.await
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map, &db))
{
let (event_id, value) = match result {
Ok(t) => t,
@@ -675,14 +727,11 @@ async fn join_room_by_id_helper(
&db,
)?;
for result in futures::future::join_all(
send_join_response
for result in send_join_response
.room_state
.auth_chain
.iter()
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map, &db)),
)
.await
.map(|pdu| validate_and_add_event_id(pdu, &room_version, &pub_key_map, &db))
{
let (event_id, value) = match result {
Ok(t) => t,
@@ -739,7 +788,7 @@ async fn join_room_by_id_helper(
Ok(join_room_by_id::Response::new(room_id.clone()).into())
}
async fn validate_and_add_event_id(
fn validate_and_add_event_id(
pdu: &Raw<Pdu>,
room_version: &RoomVersionId,
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, String>>>,
@@ -782,7 +831,6 @@ async 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(
&*pub_key_map
.read()
@@ -803,7 +851,7 @@ async fn validate_and_add_event_id(
Ok((event_id, value))
}
pub async fn invite_helper<'a>(
pub(crate) async fn invite_helper<'a>(
sender_user: &UserId,
user_id: &UserId,
room_id: &RoomId,
@@ -973,6 +1021,14 @@ pub async fn invite_helper<'a>(
(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
.sending
.send_federation_request(
@@ -980,9 +1036,9 @@ pub async fn invite_helper<'a>(
user_id.server_name(),
create_invite::v2::Request {
room_id: room_id.clone(),
event_id: ruma::event_id!("$receivingservershouldsetthis"),
event_id: expected_event_id.clone(),
room_version: room_version_id,
event: PduEvent::convert_to_outgoing_federation_event(pdu_json),
event: PduEvent::convert_to_outgoing_federation_event(pdu_json.clone()),
invite_room_state,
},
)
@@ -1002,6 +1058,10 @@ pub 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>>(
serde_json::to_value(value.get("origin").ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
+13
View File
@@ -16,6 +16,13 @@ use std::{
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
put("/_matrix/client/r0/rooms/<_>/send/<_>/<_>", data = "<body>")
@@ -92,6 +99,12 @@ pub async fn send_message_event_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/messages", data = "<body>")
+3
View File
@@ -71,6 +71,9 @@ pub const DEVICE_ID_LENGTH: usize = 10;
pub const TOKEN_LENGTH: usize = 256;
pub const SESSION_ID_LENGTH: usize = 256;
/// # `OPTIONS`
///
/// Web clients use this to get CORS headers.
#[cfg(feature = "conduit_bin")]
#[options("/<_..>")]
#[tracing::instrument]
+9
View File
@@ -5,6 +5,9 @@ use std::{convert::TryInto, time::Duration};
#[cfg(feature = "conduit_bin")]
use rocket::{get, put};
/// # `PUT /_matrix/client/r0/presence/{userId}/status`
///
/// Sets the presence state of the sender user.
#[cfg_attr(
feature = "conduit_bin",
put("/_matrix/client/r0/presence/<_>/status", data = "<body>")
@@ -46,6 +49,11 @@ pub async fn set_presence_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/presence/<_>/status", data = "<body>")
@@ -71,6 +79,7 @@ pub async fn get_presence_route(
.get_last_presence_event(&sender_user, &room_id)?
{
presence_event = Some(presence);
break;
}
}
+37 -10
View File
@@ -17,6 +17,11 @@ use std::{convert::TryInto, sync::Arc};
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
put("/_matrix/client/r0/profile/<_>/displayname", data = "<body>")
@@ -32,10 +37,9 @@ pub async fn set_displayname_route(
.set_displayname(&sender_user, body.displayname.clone())?;
// Send a new membership event and presence update into all joined rooms
let all_rooms_joined = db.rooms.rooms_joined(&sender_user).collect::<Vec<_>>();
for (pdu_builder, room_id) in all_rooms_joined
.into_iter()
let all_rooms_joined: Vec<_> = db
.rooms
.rooms_joined(&sender_user)
.filter_map(|r| r.ok())
.map(|room_id| {
Ok::<_, Error>((
@@ -72,7 +76,9 @@ pub async fn set_displayname_route(
))
})
.filter_map(|r| r.ok())
{
.collect();
for (pdu_builder, room_id) in all_rooms_joined {
let mutex_state = Arc::clone(
db.globals
.roomid_mutex_state
@@ -115,6 +121,11 @@ pub async fn set_displayname_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/profile/<_>/displayname", data = "<body>")
@@ -149,6 +160,11 @@ pub async fn get_displayname_route(
.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(
feature = "conduit_bin",
put("/_matrix/client/r0/profile/<_>/avatar_url", data = "<body>")
@@ -166,10 +182,9 @@ pub async fn set_avatar_url_route(
db.users.set_blurhash(&sender_user, body.blurhash.clone())?;
// Send a new membership event and presence update into all joined rooms
let all_joined_rooms = db.rooms.rooms_joined(&sender_user).collect::<Vec<_>>();
for (pdu_builder, room_id) in all_joined_rooms
.into_iter()
let all_joined_rooms: Vec<_> = db
.rooms
.rooms_joined(&sender_user)
.filter_map(|r| r.ok())
.map(|room_id| {
Ok::<_, Error>((
@@ -206,7 +221,9 @@ pub async fn set_avatar_url_route(
))
})
.filter_map(|r| r.ok())
{
.collect();
for (pdu_builder, room_id) in all_joined_rooms {
let mutex_state = Arc::clone(
db.globals
.roomid_mutex_state
@@ -249,6 +266,11 @@ pub async fn set_avatar_url_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/profile/<_>/avatar_url", data = "<body>")
@@ -285,6 +307,11 @@ pub async fn get_avatar_url_route(
.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(
feature = "conduit_bin",
get("/_matrix/client/r0/profile/<_>", data = "<body>")
+32
View File
@@ -15,6 +15,9 @@ use ruma::{
#[cfg(feature = "conduit_bin")]
use rocket::{delete, get, post, put};
/// # `GET /_matrix/client/r0/pushrules`
///
/// Retrieves the push rules event for this user.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/pushrules", data = "<body>")
@@ -40,6 +43,9 @@ pub async fn get_pushrules_all_route(
.into())
}
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
///
/// Retrieves a single specified push rule for this user.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/pushrules/<_>/<_>/<_>", data = "<body>")
@@ -94,6 +100,9 @@ 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(
feature = "conduit_bin",
put("/_matrix/client/r0/pushrules/<_>/<_>/<_>", data = "<req>")
@@ -197,6 +206,9 @@ pub async fn set_pushrule_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/pushrules/<_>/<_>/<_>/actions", data = "<body>")
@@ -256,6 +268,9 @@ pub async fn get_pushrule_actions_route(
.into())
}
/// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions`
///
/// Sets the actions of a single specified push rule for this user.
#[cfg_attr(
feature = "conduit_bin",
put("/_matrix/client/r0/pushrules/<_>/<_>/<_>/actions", data = "<body>")
@@ -330,6 +345,9 @@ pub async fn set_pushrule_actions_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/pushrules/<_>/<_>/<_>/enabled", data = "<body>")
@@ -391,6 +409,9 @@ pub async fn get_pushrule_enabled_route(
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(
feature = "conduit_bin",
put("/_matrix/client/r0/pushrules/<_>/<_>/<_>/enabled", data = "<body>")
@@ -470,6 +491,9 @@ pub async fn set_pushrule_enabled_route(
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(
feature = "conduit_bin",
delete("/_matrix/client/r0/pushrules/<_>/<_>/<_>", data = "<body>")
@@ -539,6 +563,9 @@ pub async fn delete_pushrule_route(
Ok(delete_pushrule::Response {}.into())
}
/// # `GET /_matrix/client/r0/pushers`
///
/// Gets all currently active pushers for the sender user.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/pushers", data = "<body>")
@@ -556,6 +583,11 @@ pub async fn get_pushers_route(
.into())
}
/// # `POST /_matrix/client/r0/pushers/set`
///
/// Adds a pusher for the sender user.
///
/// - TODO: Handle `append`
#[cfg_attr(
feature = "conduit_bin",
post("/_matrix/client/r0/pushers/set", data = "<body>")
+9
View File
@@ -13,6 +13,12 @@ use std::collections::BTreeMap;
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/read_markers", data = "<body>")
@@ -80,6 +86,9 @@ pub async fn set_read_marker_route(
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(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/receipt/<_>/<_>", data = "<body>")
+5
View File
@@ -9,6 +9,11 @@ use ruma::{
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
put("/_matrix/client/r0/rooms/<_>/redact/<_>/<_>", data = "<body>")
+36
View File
@@ -20,6 +20,22 @@ use tracing::{info, warn};
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
post("/_matrix/client/r0/createRoom", data = "<body>")
@@ -344,6 +360,11 @@ pub async fn create_room_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/event/<_>", data = "<body>")
@@ -372,6 +393,11 @@ pub async fn get_room_event_route(
.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(
feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/aliases", data = "<body>")
@@ -400,6 +426,16 @@ pub async fn get_room_aliases_route(
.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(
feature = "conduit_bin",
post("/_matrix/client/r0/rooms/<_>/upgrade", data = "<body>")
+5
View File
@@ -6,6 +6,11 @@ use rocket::post;
use search_events::{EventContextResult, ResultCategories, ResultRoomEvents, SearchResult};
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(
feature = "conduit_bin",
post("/_matrix/client/r0/search", data = "<body>")
+12 -7
View File
@@ -24,7 +24,7 @@ use rocket::{get, post};
/// # `GET /_matrix/client/r0/login`
///
/// Get the homeserver's supported login types. One of these should be used as the `type` field
/// Get the supported login types of this server. One of these should be used as the `type` field
/// when logging in.
#[cfg_attr(feature = "conduit_bin", get("/_matrix/client/r0/login"))]
#[tracing::instrument]
@@ -41,9 +41,10 @@ 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.
///
/// - The returned access token is associated with the user and device
/// - Old access tokens of that device should be invalidated
/// - If `device_id` is unknown, a new device will be created
/// - The user needs to authenticate using their password (or if enabled using a json web token)
/// - If `device_id` is known: invalidates old access token of that device
/// - If `device_id` is unknown: creates a new device
/// - 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
/// supported login types.
@@ -162,8 +163,10 @@ pub async fn login_route(
///
/// Log out the current device.
///
/// - Invalidates the access token
/// - Deletes the device and most of it's data (to-device events, last seen, etc.)
/// - 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(
feature = "conduit_bin",
post("/_matrix/client/r0/logout", data = "<body>")
@@ -188,7 +191,9 @@ pub async fn logout_route(
/// Log out all devices of this user.
///
/// - Invalidates all access tokens
/// - Deletes devices and most of their data (to-device events, last seen, etc.)
/// - Deletes all device metadata (device id, device display name, last seen ip, last seen ts)
/// - Forgets all to-device events
/// - Triggers device list updates
///
/// Note: This is equivalent to calling [`GET /_matrix/client/r0/logout`](fn.logout_route.html)
/// from each device of this user.
+32 -1
View File
@@ -22,6 +22,13 @@ use ruma::{
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
put("/_matrix/client/r0/rooms/<_>/state/<_>/<_>", data = "<body>")
@@ -48,6 +55,13 @@ pub async fn send_state_event_for_key_route(
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(
feature = "conduit_bin",
put("/_matrix/client/r0/rooms/<_>/state/<_>", data = "<body>")
@@ -74,6 +88,11 @@ pub async fn send_state_event_for_empty_key_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/state", data = "<body>")
@@ -121,6 +140,11 @@ pub async fn get_state_events_route(
.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(
feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/state/<_>/<_>", data = "<body>")
@@ -172,6 +196,11 @@ pub async fn get_state_events_for_key_route(
.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(
feature = "conduit_bin",
get("/_matrix/client/r0/rooms/<_>/state/<_>", data = "<body>")
@@ -223,7 +252,7 @@ pub async fn get_state_events_for_empty_key_route(
.into())
}
pub async fn send_state_event_for_key_helper(
async fn send_state_event_for_key_helper(
db: &Database,
sender: &UserId,
room_id: &RoomId,
@@ -233,6 +262,8 @@ pub async fn send_state_event_for_key_helper(
) -> Result<EventId> {
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) =
serde_json::from_str::<CanonicalAliasEventContent>(json.json().get())
{
+30 -18
View File
@@ -22,12 +22,33 @@ use rocket::{get, tokio};
/// 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
/// previous request.
/// - Calling this endpoint without a `since` parameter will return all recent events, the state
/// of all rooms and more data. This should only be called on the initial login of the device.
/// - To get incremental updates, you can call this endpoint with a `since` parameter. This will
/// return all recent events, state updates and more data that happened since the last /sync
/// request.
/// previous request for incremental syncs.
///
/// Calling this endpoint without a `since` parameter returns:
/// - Some of the most recent events of each timeline
/// - Notification counts for each room
/// - Joined and invited member counts, heroes
/// - 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(
feature = "conduit_bin",
get("/_matrix/client/r0/sync", data = "<body>")
@@ -106,7 +127,7 @@ pub async fn sync_events_route(
result
}
pub async fn sync_helper_wrapper(
async fn sync_helper_wrapper(
db: Arc<DatabaseGuard>,
sender_user: UserId,
sender_device: Box<DeviceId>,
@@ -246,12 +267,6 @@ async fn sync_helper(
.current_shortstatehash(&room_id)?
.expect("All rooms have state");
let pdus_after_since = db
.rooms
.pdus_after(&sender_user, &room_id, since)?
.next()
.is_some();
let since_shortstatehash = db.rooms.get_token_shortstatehash(&room_id, since)?;
// Calculates joined_member_count, invited_member_count and heroes
@@ -341,7 +356,7 @@ async fn sync_helper(
true,
state_events,
)
} else if !pdus_after_since && since_shortstatehash == Some(current_shortstatehash) {
} else if timeline_pdus.is_empty() && since_shortstatehash == Some(current_shortstatehash) {
// No state changes
(Vec::new(), None, None, false, Vec::new())
} else {
@@ -401,10 +416,7 @@ async fn sync_helper(
let send_member_count = state_events
.iter()
.any(|event| event.kind == EventType::RoomMember)
|| timeline_pdus.iter().any(|(_, event)| {
event.state_key.is_some() && event.kind == EventType::RoomMember
});
.any(|event| event.kind == EventType::RoomMember);
if encrypted_room {
for state_event in &state_events {
+15
View File
@@ -8,6 +8,11 @@ use std::collections::BTreeMap;
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
put("/_matrix/client/r0/user/<_>/rooms/<_>/tags/<_>", data = "<body>")
@@ -45,6 +50,11 @@ pub async fn update_tag_route(
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(
feature = "conduit_bin",
delete("/_matrix/client/r0/user/<_>/rooms/<_>/tags/<_>", data = "<body>")
@@ -79,6 +89,11 @@ pub async fn delete_tag_route(
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(
feature = "conduit_bin",
get("/_matrix/client/r0/user/<_>/rooms/<_>/tags", data = "<body>")
+3
View File
@@ -5,6 +5,9 @@ use ruma::api::client::r0::thirdparty::get_protocols;
use rocket::get;
use std::collections::BTreeMap;
/// # `GET /_matrix/client/r0/thirdparty/protocols`
///
/// TODO: Fetches all metadata about protocols supported by the homeserver.
#[cfg_attr(
feature = "conduit_bin",
get("/_matrix/client/r0/thirdparty/protocols")
+3
View File
@@ -13,6 +13,9 @@ use ruma::{
#[cfg(feature = "conduit_bin")]
use rocket::put;
/// # `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}`
///
/// Send a to-device event to a set of client devices.
#[cfg_attr(
feature = "conduit_bin",
put("/_matrix/client/r0/sendToDevice/<_>/<_>", data = "<body>")
+3
View File
@@ -5,6 +5,9 @@ use ruma::api::client::r0::typing::create_typing_event;
#[cfg(feature = "conduit_bin")]
use rocket::put;
/// # `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}`
///
/// Sets the typing state of the sender user.
#[cfg_attr(
feature = "conduit_bin",
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
/// - Only the latest PATCH release will be reported for each MAJOR.MINOR value
/// - Unstable features should be namespaced and may include version information in their name
/// - Unstable features are namespaced and may include version information in their name
///
/// Note: Unstable features are used while developing new features. Clients should avoid using
/// unstable features in their stable releases
+5
View File
@@ -4,6 +4,11 @@ use ruma::api::client::r0::user_directory::search_users;
#[cfg(feature = "conduit_bin")]
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(
feature = "conduit_bin",
post("/_matrix/client/r0/user_directory/search", data = "<body>")
+3
View File
@@ -5,6 +5,9 @@ use std::time::Duration;
#[cfg(feature = "conduit_bin")]
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"))]
#[tracing::instrument]
pub async fn turn_server_route() -> ConduitResult<get_turn_server_info::Response> {
+17 -7
View File
@@ -47,13 +47,15 @@ pub struct Config {
database_path: String,
#[serde(default = "default_db_cache_capacity_mb")]
db_cache_capacity_mb: f64,
#[serde(default = "default_pdu_cache_capacity")]
pdu_cache_capacity: u32,
#[serde(default = "default_sqlite_wal_clean_second_interval")]
sqlite_wal_clean_second_interval: u32,
#[serde(default = "default_max_request_size")]
max_request_size: u32,
#[serde(default = "default_max_concurrent_requests")]
max_concurrent_requests: u16,
#[serde(default = "true_fn")]
#[serde(default = "false_fn")]
allow_registration: bool,
#[serde(default = "true_fn")]
allow_encryption: bool,
@@ -107,6 +109,10 @@ fn default_db_cache_capacity_mb() -> f64 {
200.0
}
fn default_pdu_cache_capacity() -> u32 {
100_000
}
fn default_sqlite_wal_clean_second_interval() -> u32 {
1 * 60 // every minute
}
@@ -281,14 +287,20 @@ impl Database {
softfailedeventids: builder.open_tree("softfailedeventids")?,
referencedevents: builder.open_tree("referencedevents")?,
pdu_cache: Mutex::new(LruCache::new(100_000)),
pdu_cache: Mutex::new(LruCache::new(
config
.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)),
eventidshort_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)),
stateinfo_cache: Mutex::new(LruCache::new(1000)),
our_real_users_cache: RwLock::new(HashMap::new()),
appservice_in_room_cache: RwLock::new(HashMap::new()),
stateinfo_cache: Mutex::new(LruCache::new(1000)),
},
account_data: account_data::AccountData {
roomuserdataid_accountdata: builder.open_tree("roomuserdataid_accountdata")?,
@@ -643,7 +655,7 @@ impl Database {
if db.globals.database_version()? < 9 {
// Update tokenids db layout
let batch = db
let mut iter = db
.rooms
.tokenids
.iter()
@@ -671,9 +683,7 @@ impl Database {
println!("new {:?}", new_key);
Some((new_key, Vec::new()))
})
.collect::<Vec<_>>();
let mut iter = batch.into_iter().peekable();
.peekable();
while iter.peek().is_some() {
db.rooms
+33 -32
View File
@@ -10,6 +10,7 @@ use std::{
pin::Pin,
sync::Arc,
};
use thread_local::ThreadLocal;
use tokio::sync::oneshot::Sender;
use tracing::debug;
@@ -40,6 +41,8 @@ impl<T> Drop for NonAliasingBox<T> {
pub struct Engine {
writer: Mutex<Connection>,
read_conn_tls: ThreadLocal<Connection>,
read_iterator_conn_tls: ThreadLocal<Connection>,
path: PathBuf,
cache_size_per_thread: u32,
@@ -62,34 +65,14 @@ impl Engine {
self.writer.lock()
}
fn read_lock(&self) -> &'static Connection {
READ_CONNECTION.with(|cell| {
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);
fn read_lock(&self) -> &Connection {
self.read_conn_tls
.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap())
}
connection.unwrap()
})
}
fn read_lock_iterator(&self) -> &'static Connection {
READ_CONNECTION_ITERATOR.with(|cell| {
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 {
self.read_iterator_conn_tls
.get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap())
}
pub fn flush_wal(self: &Arc<Self>) -> Result<()> {
@@ -105,15 +88,18 @@ impl DatabaseEngine for Engine {
// calculates cache-size per permanent connection
// 1. convert MB to KiB
// 2. divide by permanent connections
// 2. divide by permanent connections + permanent iter connections + write connection
// 3. round down to nearest integer
let cache_size_per_thread: u32 =
((config.db_cache_capacity_mb * 1024.0) / (num_cpus::get().max(1) + 1) as f64) as u32;
let cache_size_per_thread: u32 = ((config.db_cache_capacity_mb * 1024.0)
/ ((num_cpus::get().max(1) * 2) + 1) as f64)
as u32;
let writer = Mutex::new(Self::prepare_conn(&path, cache_size_per_thread)?);
let arc = Arc::new(Engine {
writer,
read_conn_tls: ThreadLocal::new(),
read_iterator_conn_tls: ThreadLocal::new(),
path,
cache_size_per_thread,
});
@@ -148,6 +134,7 @@ type TupleOfBytes = (Vec<u8>, Vec<u8>);
impl SqliteTable {
#[tracing::instrument(skip(self, guard, key))]
fn get_with_guard(&self, guard: &Connection, key: &[u8]) -> Result<Option<Vec<u8>>> {
//dbg!(&self.name);
Ok(guard
.prepare(format!("SELECT value FROM {} WHERE key = ?", self.name).as_str())?
.query_row([key], |row| row.get(0))
@@ -156,6 +143,7 @@ impl SqliteTable {
#[tracing::instrument(skip(self, guard, key, value))]
fn insert_with_guard(&self, guard: &Connection, key: &[u8], value: &[u8]) -> Result<()> {
//dbg!(&self.name);
guard.execute(
format!(
"INSERT OR REPLACE INTO {} (key, value) VALUES (?, ?)",
@@ -182,11 +170,16 @@ impl SqliteTable {
let statement_ref = NonAliasingBox(statement);
//let name = self.name.clone();
let iterator = Box::new(
statement
.query_map([], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap()
.map(|r| r.unwrap()),
.map(move |r| {
//dbg!(&name);
r.unwrap()
}),
);
Box::new(PreparedStatementIterator {
@@ -294,6 +287,8 @@ impl Tree for SqliteTable {
let guard = self.engine.read_lock_iterator();
let from = from.to_vec(); // TODO change interface?
//let name = self.name.clone();
if backwards {
let statement = Box::leak(Box::new(
guard
@@ -310,7 +305,10 @@ impl Tree for SqliteTable {
statement
.query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap()
.map(|r| r.unwrap()),
.map(move |r| {
//dbg!(&name);
r.unwrap()
}),
);
Box::new(PreparedStatementIterator {
iterator,
@@ -332,7 +330,10 @@ impl Tree for SqliteTable {
statement
.query_map([from], |row| Ok((row.get_unwrap(0), row.get_unwrap(1))))
.unwrap()
.map(|r| r.unwrap()),
.map(move |r| {
//dbg!(&name);
r.unwrap()
}),
);
Box::new(PreparedStatementIterator {
+1 -1
View File
@@ -40,7 +40,7 @@ impl AccountData {
roomuserdataid.push(0xff);
roomuserdataid.extend_from_slice(&event_type.as_bytes());
let mut key = prefix.clone();
let mut key = prefix;
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
+13 -2
View File
@@ -227,7 +227,11 @@ impl Globals {
/// Remove the outdated keys and insert the new ones.
///
/// This doesn't actually check that the keys provided are newer than the old set.
pub fn add_signing_key(&self, origin: &ServerName, new_keys: ServerSigningKeys) -> Result<()> {
pub fn add_signing_key(
&self,
origin: &ServerName,
new_keys: ServerSigningKeys,
) -> Result<BTreeMap<ServerSigningKeyId, VerifyKey>> {
// Not atomic, but this is not critical
let signingkeys = self.server_signingkeys.get(origin.as_bytes())?;
@@ -252,7 +256,14 @@ impl Globals {
&serde_json::to_vec(&keys).expect("serversigningkeys can be serialized"),
)?;
Ok(())
let mut tree = keys.verify_keys;
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.
+21
View File
@@ -84,6 +84,27 @@ impl KeyBackups {
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)>> {
let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff);
+108 -36
View File
@@ -103,6 +103,7 @@ pub struct Rooms {
pub(super) statekeyshort_cache: Mutex<LruCache<(EventType, String), u64>>,
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<
LruCache<
u64,
@@ -384,7 +385,7 @@ impl Rooms {
self.save_state_from_diff(
new_shortstatehash,
statediffnew.clone(),
statediffremoved.clone(),
statediffremoved,
2, // every state change is 2 event changes on average
states_parents,
)?;
@@ -496,8 +497,7 @@ impl Rooms {
Ok(response)
} else {
let mut response = Vec::new();
response.push((shortstatehash, added.clone(), added, removed));
let response = vec![(shortstatehash, added.clone(), added, removed)];
self.stateinfo_cache
.lock()
.unwrap()
@@ -608,7 +608,7 @@ impl Rooms {
return Ok(());
}
if parent_states.len() == 0 {
if parent_states.is_empty() {
// There is no parent layer, create a new state
let mut value = 0_u64.to_be_bytes().to_vec(); // 0 means no parent
for new in &statediffnew {
@@ -688,7 +688,7 @@ impl Rooms {
state_hash: &StateHashId,
globals: &super::globals::Globals,
) -> Result<(u64, bool)> {
Ok(match self.statehash_shortstatehash.get(&state_hash)? {
Ok(match self.statehash_shortstatehash.get(state_hash)? {
Some(shortstatehash) => (
utils::u64_from_bytes(&shortstatehash)
.map_err(|_| Error::bad_database("Invalid shortstatehash in db."))?,
@@ -697,7 +697,7 @@ impl Rooms {
None => {
let shortstatehash = globals.next_count()?;
self.statehash_shortstatehash
.insert(&state_hash, &shortstatehash.to_be_bytes())?;
.insert(state_hash, &shortstatehash.to_be_bytes())?;
(shortstatehash, false)
}
})
@@ -1528,22 +1528,38 @@ impl Rooms {
"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!(
message::MessageEventContent::text_plain(
format!(
"Loaded auth chain with length {} in {:?}",
count, elapsed
)),
),
),
));
}
}
}
}
"parse_pdu" => {
if body.len() > 2
&& body[0].trim() == "```"
@@ -1767,8 +1783,8 @@ impl Rooms {
};
self.save_state_from_diff(
shortstatehash,
statediffnew.clone(),
statediffremoved.clone(),
statediffnew,
statediffremoved,
1_000_000, // high number because no state will be based on this one
states_parents,
)?;
@@ -1913,15 +1929,14 @@ impl Rooms {
let mut key = shortroomid.to_be_bytes().to_vec();
key.extend_from_slice(&token.to_be_bytes());
Ok(self
.roomsynctoken_shortstatehash
self.roomsynctoken_shortstatehash
.get(&key)?
.map(|bytes| {
utils::u64_from_bytes(&bytes).map_err(|_| {
Error::bad_database("Invalid shortstatehash in roomsynctoken_shortstatehash")
})
})
.transpose()?)
.transpose()
}
/// Creates a new persisted data unit and adds it to a room.
@@ -2110,6 +2125,11 @@ impl Rooms {
}
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") {
let users = namespaces
.get("users")
@@ -2133,17 +2153,6 @@ impl Rooms {
.get("rooms")
.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| {
users.is_match(pdu.sender.as_str())
|| pdu.kind == EventType::RoomMember
@@ -2151,9 +2160,6 @@ impl Rooms {
.state_key
.as_ref()
.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| {
self.room_aliases(&room_id)
@@ -2161,8 +2167,7 @@ impl Rooms {
.any(|room_alias| aliases.is_match(room_alias.as_str()))
};
if bridge_user_id.map_or(false, user_is_joined)
|| aliases.iter().any(matching_aliases)
if aliases.iter().any(matching_aliases)
|| rooms.map_or(false, |rooms| rooms.contains(&room_id.as_str().into()))
|| users.iter().any(matching_users)
{
@@ -2484,8 +2489,8 @@ impl Rooms {
self.roomuserid_leftcount.remove(&roomuser_id)?;
}
member::MembershipState::Leave | member::MembershipState::Ban => {
if update_joined_count {
if self
if update_joined_count
&& self
.room_members(room_id)
.chain(self.room_members_invited(room_id))
.filter_map(|r| r.ok())
@@ -2494,7 +2499,6 @@ impl Rooms {
self.roomserverids.remove(&roomserver_id)?;
self.serverroomids.remove(&serverroom_id)?;
}
}
self.userroomid_leftstate.insert(
&userroom_id,
&serde_json::to_vec(&Vec::<Raw<AnySyncStateEvent>>::new()).unwrap(),
@@ -2579,6 +2583,11 @@ impl Rooms {
self.serverroomids.insert(&serverroom_id, &[])?;
}
self.appservice_in_room_cache
.write()
.unwrap()
.remove(room_id);
Ok(())
}
@@ -2608,6 +2617,63 @@ impl Rooms {
}
}
#[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))]
pub async fn leave_room(
&self,
@@ -3028,6 +3094,15 @@ 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).
#[tracing::instrument(skip(self))]
pub fn server_rooms<'a>(
@@ -3397,10 +3472,7 @@ impl Rooms {
}
// Cache in RAM
self.auth_chain_cache
.lock()
.unwrap()
.insert(key.clone(), chain);
self.auth_chain_cache.lock().unwrap().insert(key, chain);
Ok(())
}
+4 -4
View File
@@ -422,7 +422,7 @@ impl RoomEdus {
}
/// Sets all users to offline who have been quiet for too long.
fn presence_maintain(
fn _presence_maintain(
&self,
rooms: &super::Rooms,
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`.
#[tracing::instrument(skip(self, globals, rooms))]
#[tracing::instrument(skip(self, since, _rooms, _globals))]
pub fn presence_since(
&self,
room_id: &RoomId,
since: u64,
rooms: &super::Rooms,
globals: &super::super::globals::Globals,
_rooms: &super::Rooms,
_globals: &super::super::globals::Globals,
) -> Result<HashMap<UserId, PresenceEvent>> {
//self.presence_maintain(rooms, globals)?;
+5 -1
View File
@@ -66,7 +66,11 @@ where
let limit = db.globals.max_request_size();
let mut handle = data.open(ByteUnit::Byte(limit.into()));
let mut body = Vec::new();
handle.read_to_end(&mut body).await.unwrap();
if let Err(_) = handle.read_to_end(&mut body).await {
// Client disconnected
// Missing Token
return Failure((Status::new(582), ()));
}
let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&body).ok();
+624 -124
View File
File diff suppressed because it is too large Load Diff