mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-11-17 05:57:35 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af570c481e | ||
|
|
dc9314de1f | ||
|
|
cf005ee537 | ||
|
|
6455ef72cd | ||
|
|
7115fb2796 | ||
|
|
959c559bd8 | ||
|
|
a1bf188504 | ||
|
|
87770fefeb | ||
|
|
0c7ba1dd5a | ||
|
|
7b2079f714 | ||
|
|
c5508bba58 | ||
|
|
88a6b72f0f | ||
|
|
22c5f0207d | ||
|
|
3af78ac851 | ||
|
|
b5f50c3fda | ||
|
|
c9a26a0280 | ||
|
|
417e9ba052 | ||
|
|
085cdb30f4 | ||
|
|
77474479b5 | ||
|
|
d244e8027c | ||
|
|
4fea0abac4 | ||
|
|
cab0b3fd9f | ||
|
|
f311332bad | ||
|
|
fb0c2a2832 | ||
|
|
3403943880 | ||
|
|
7e69e9b051 | ||
|
|
27ed9b88f1 | ||
|
|
10edc3bd5e | ||
|
|
6553ba829f | ||
|
|
1ce3d2b01f | ||
|
|
50bfb0fe5e | ||
|
|
74f8cd3708 | ||
|
|
bcc2be7661 | ||
|
|
4f9b1d6dbd | ||
|
|
c9362b8605 | ||
|
|
e84d6666c0 | ||
|
|
7666bb63d8 | ||
|
|
3125b7e291 | ||
|
|
aebe2d72de | ||
|
|
8f54d9dc09 | ||
|
|
52b156e034 | ||
|
|
d2d6a98180 | ||
|
|
0bbc228f7a | ||
|
|
0d782095ad | ||
|
|
f6b95ff1c4 | ||
|
|
347298d7d6 | ||
|
|
442a5aafeb | ||
|
|
8bb0d02619 | ||
|
|
71f3ccf140 | ||
|
|
98affbdeaf | ||
|
|
e5073165f0 | ||
|
|
6705efc760 | ||
|
|
61085f4707 | ||
|
|
deb5c65885 | ||
|
|
11c4cbf54e | ||
|
|
a748edd621 | ||
|
|
9e539d0a22 | ||
|
|
5260912c3b | ||
|
|
b924412efb | ||
|
|
120ab1d068 | ||
|
|
e60e86e9ed | ||
|
|
5147b541b5 | ||
|
|
f4eeaaf167 | ||
|
|
54fe4bdf56 | ||
|
|
fe12daead9 | ||
|
|
6f29a34ffb | ||
|
|
dafbe59d00 | ||
|
|
0746f4b1ad | ||
|
|
90228e4865 | ||
|
|
53b5eb4ba6 | ||
|
|
20f080fc49 | ||
|
|
424ed3d7ad | ||
|
|
728085bd1b |
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
||||
[advisories]
|
||||
ignore = ["RUSTSEC-2024-0436", "RUSTSEC-2025-0014"] # advisory IDs to ignore e.g. ["RUSTSEC-2019-0001", ...]
|
||||
ignore = ["RUSTSEC-2024-0436", "RUSTSEC-2025-0014", "RUSTSEC-2025-0134"] # advisory IDs to ignore e.g. ["RUSTSEC-2019-0001", ...]
|
||||
informational_warnings = [] # warn for categories of informational advisories
|
||||
severity_threshold = "none" # CVSS severity ("none", "low", "medium", "high", "critical")
|
||||
|
||||
|
||||
@@ -106,7 +106,6 @@ jobs:
|
||||
excludes: ${{inputs.excludes}}
|
||||
includes: ${{inputs.includes}}
|
||||
|
||||
# disabled due to excessive build time issue installing cargo lychee
|
||||
lychee:
|
||||
if: >
|
||||
!failure() && !cancelled()
|
||||
@@ -114,7 +113,6 @@ jobs:
|
||||
&& contains(fromJSON(inputs.feat_sets), fromJSON('["all"]')[0])
|
||||
&& contains(fromJSON(inputs.rust_toolchains), fromJSON('["nightly"]')[0])
|
||||
&& contains(fromJSON(inputs.sys_targets), fromJSON('["x86_64-v1-linux-gnu"]')[0])
|
||||
&& false
|
||||
|
||||
name: Lychee
|
||||
uses: ./.github/workflows/bake.yml
|
||||
|
||||
@@ -42,7 +42,7 @@ jobs:
|
||||
publish: ${{vars.PUBLISH != 'false'}}
|
||||
build_nix: ${{vars.BUILD_NIX != 'false'}}
|
||||
build_pkgs: ${{vars.BUILD_PKGS || github.ref == 'refs/heads/main' || github.ref == 'refs/heads/test' || contains(github.ref, 'tags/v')}}
|
||||
check_pkgs: ${{vars.CHECK_PKGS || 'false'}}
|
||||
check_pkgs: ${{vars.CHECK_PKGS || github.ref == 'refs/heads/test'}}
|
||||
complement: ${{vars.COMPLEMENT != 'false'}}
|
||||
complement_runner: 'het'
|
||||
docker_repo: ${{vars.DOCKER_REPO}}
|
||||
|
||||
@@ -395,7 +395,7 @@ jobs:
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: complement_output-${{matrix.feat_set}}-${{matrix.sys_name}}-${{matrix.sys_target}}.jsonl
|
||||
path: ./complement.jsonl
|
||||
path: ./tests/complement/logs.jsonl
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Accept
|
||||
|
||||
+1
-1
@@ -94,7 +94,7 @@ public/
|
||||
rustc-ice-*
|
||||
|
||||
# complement test logs are huge
|
||||
tests/test_results/complement/test_logs.jsonl
|
||||
tests/complement/logs.jsonl
|
||||
|
||||
# cargo profiles from -Z self-profile
|
||||
*.mm_profdata
|
||||
|
||||
Generated
+580
-454
File diff suppressed because it is too large.
Load diff
+12
-30
@@ -29,7 +29,7 @@ license = "Apache-2.0"
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/matrix-construct/tuwunel"
|
||||
rust-version = "1.89.0"
|
||||
version = "1.4.6"
|
||||
version = "1.4.8"
|
||||
|
||||
[workspace.metadata.crane]
|
||||
name = "tuwunel"
|
||||
@@ -231,6 +231,10 @@ version = "0.1"
|
||||
[workspace.dependencies.itertools]
|
||||
version = "0.14"
|
||||
|
||||
[workspace.dependencies.jevmalloc]
|
||||
git = "https://github.com/matrix-construct/jevmalloc"
|
||||
rev = "93795449913f65ab533b7fa482333eef63fc3ae0"
|
||||
|
||||
[workspace.dependencies.jsonwebtoken]
|
||||
version = "9.3"
|
||||
default-features = false
|
||||
@@ -238,7 +242,7 @@ features = ["use_pem"]
|
||||
|
||||
[workspace.dependencies.ldap3]
|
||||
git = "https://github.com/matrix-construct/ldap3"
|
||||
rev = "7d423314b9dbc66347284e38fc2b78c3d8f3d494"
|
||||
rev = "fdfbba2bf916b53e5f73cdb1a495ebb649978079"
|
||||
default-features = false
|
||||
features = ["sync", "tls-rustls"]
|
||||
|
||||
@@ -320,7 +324,7 @@ default-features = false
|
||||
|
||||
[workspace.dependencies.ruma]
|
||||
git = "https://github.com/matrix-construct/ruma"
|
||||
rev = "db4bf59eaa1757735f38489f8924348ae05a6a17"
|
||||
rev = "214ab27fdc3d7004f6d46e0aa89fba573b59c66f"
|
||||
features = [
|
||||
"__compat",
|
||||
"appservice-api-c",
|
||||
@@ -360,7 +364,7 @@ features = [
|
||||
[workspace.dependencies.rustls]
|
||||
version = "0.23"
|
||||
default-features = false
|
||||
features = ["aws_lc_rs"]
|
||||
features = ["aws_lc_rs", "logging", "tls12", "prefer-post-quantum"]
|
||||
|
||||
[workspace.dependencies.rustyline-async]
|
||||
version = "0.4.6"
|
||||
@@ -368,14 +372,16 @@ default-features = false
|
||||
|
||||
[workspace.dependencies.rust-rocksdb]
|
||||
git = "https://github.com/matrix-construct/rust-rocksdb"
|
||||
rev = "225a42519276e502205bdc845cebdb22d70ee245"
|
||||
rev = "c11395350bc1f2090a0152f2d15c8c5847821eba"
|
||||
default-features = false
|
||||
features = [
|
||||
"bzip2",
|
||||
"lto",
|
||||
"lz4",
|
||||
"multi-threaded-cf",
|
||||
"mt_static",
|
||||
"serde1",
|
||||
"zstd",
|
||||
"zstd-static-linking-only",
|
||||
]
|
||||
|
||||
[workspace.dependencies.sanitize-filename]
|
||||
@@ -475,30 +481,6 @@ default-features = false
|
||||
version = "2.0"
|
||||
default-features = false
|
||||
|
||||
[workspace.dependencies.tikv-jemallocator]
|
||||
git = "https://github.com/matrix-construct/jemallocator"
|
||||
rev = "03bed96afbbc898bef4d4f7d335c0519e3d1afad"
|
||||
default-features = false
|
||||
features = [
|
||||
"background_threads_runtime_support",
|
||||
"unprefixed_malloc_on_supported_platforms",
|
||||
]
|
||||
|
||||
[workspace.dependencies.tikv-jemalloc-ctl]
|
||||
git = "https://github.com/matrix-construct/jemallocator"
|
||||
rev = "03bed96afbbc898bef4d4f7d335c0519e3d1afad"
|
||||
default-features = false
|
||||
features = ["use_std"]
|
||||
|
||||
[workspace.dependencies.tikv-jemalloc-sys]
|
||||
git = "https://github.com/matrix-construct/jemallocator"
|
||||
rev = "03bed96afbbc898bef4d4f7d335c0519e3d1afad"
|
||||
default-features = false
|
||||
features = [
|
||||
"background_threads_runtime_support",
|
||||
"unprefixed_malloc_on_supported_platforms",
|
||||
]
|
||||
|
||||
[workspace.dependencies.tokio]
|
||||
version = "1.48"
|
||||
default-features = false
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# Tuwunel<sup>💕</sup>
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://github.com/matrix-construct/tuwunel/actions/workflows/main.yml)
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://github.com/matrix-construct/tuwunel/actions/workflows/main.yml)
|
||||
|
||||
<!-- ANCHOR: catchphrase -->
|
||||
|
||||
@@ -15,19 +15,20 @@
|
||||
|
||||
<!-- ANCHOR: body -->
|
||||
|
||||
[](https://matrix-construct.github.io/tuwunel/)
|
||||
[](https://matrix.to/#/#tuwunel:grin.hu)
|
||||
|
||||
Tuwunel is a featureful [Matrix](https://matrix.org/) homeserver you can use instead of Synapse
|
||||
with your favorite [client](https://matrix.org/ecosystem/clients/),
|
||||
[bridge](https://matrix.org/ecosystem/bridges/) or
|
||||
[bot](https://matrix.org/ecosystem/integrations/). It is written entirely in Rust to be a scalable,
|
||||
lightweight, low-cost, community-driven alternative covering all but the most niche uses.
|
||||
low-cost, enterprise-ready, community-driven alternative, fully implementing the
|
||||
[Matrix Specification](https://spec.matrix.org/latest/) for all but the most niche uses.
|
||||
|
||||
This project is the official successor to conduwuit, which
|
||||
was a featureful and high-performance fork of [Conduit](https://gitlab.com/famedly/conduit), all
|
||||
community-lead homeservers implementing the compatible
|
||||
[Matrix Specification](https://spec.matrix.org/latest/).
|
||||
|
||||
Tuwunel is operated by enterprise users with a vested interest in sponsoring its continued
|
||||
development. It is now maintained by full-time staff.
|
||||
This project is the official successor to [conduwuit](https://github.com/x86pup/conduwuit) after it
|
||||
reached stability. Tuwunel is now used by many companies with a vested interest in its continued
|
||||
development by full-time staff. It is primarily sponsored by the government of
|
||||
Switzerland 🇨🇭 where it is currently deployed for citizens.
|
||||
|
||||
### Getting Started
|
||||
|
||||
@@ -38,7 +39,7 @@ development. It is now maintained by full-time staff.
|
||||
- Static binaries available as [releases](https://github.com/matrix-construct/tuwunel/releases) or [build artifacts](https://github.com/matrix-construct/tuwunel/actions?query=branch%3Amain).
|
||||
- Deb and RPM packages available as [releases](https://github.com/matrix-construct/tuwunel/releases) or [build artifacts](https://github.com/matrix-construct/tuwunel/actions?query=branch%3Amain).
|
||||
- Arch package available as [tuwunel](https://aur.archlinux.org/packages/tuwunel) or [tuwunel-git](https://aur.archlinux.org/packages/tuwunel-git).
|
||||
- Nix package still [needs some love](https://github.com/NixOS/nixpkgs/issues/415469).
|
||||
- Nix package available as [`matrix-tuwunel`](https://search.nixos.org/packages?query=matrix-tuwunel) and NixOS module available as [`services.matrix-tuwunel`](https://search.nixos.org/options?query=services.matrix-tuwunel).
|
||||
|
||||
**1.** [Configure](https://matrix-construct.github.io/tuwunel/configuration.html) by
|
||||
copying and editing the `tuwunel-example.toml`. The `server_name` and `database_path` must be
|
||||
|
||||
+5
-43
@@ -1,47 +1,9 @@
|
||||
# Tuwunel 1.4.6
|
||||
# Tuwunel 1.4.8
|
||||
|
||||
November 6, 2025
|
||||
December 21, 2025
|
||||
|
||||
### New Features
|
||||
All federating deployments must upgrade to this patch for mitigations to severe vulnerabilities in Matrix protocol implementation logic. This is an off-schedule coordinated security release. Full release notes will be included with the next scheduled release.
|
||||
|
||||
- Element Call discovery support was implemented by @tototomate123 in (#209). Adding a `[[global.well_known.rtc_transports]]` section in your [config file](https://github.com/matrix-construct/tuwunel/blob/e1f89b69ea117f166be423f035a5a34f4c0e7366/tuwunel-example.toml#L1835-L1851) enables discovery. More information on setting up Element Call can be found at [Spaetzblog](https://sspaeth.de/2024/11/sfu/), skipping step one, and performing step three in your Tuwunel config.
|
||||
### Security Fixes
|
||||
|
||||
- Dehydrated Device support (MSC3814) is now available (#200). This feature allows users to receive encrypted messages without being logged in. Supporting clients will setup the dehydrated device automatically and it will "just work" behind the scenes; in fact, these clients will also hide it from the sessions list to avoid confusion. Support is not widespread yet but it has been tested with matrix-js-sdk clients such as Element-web. This feature was commissioned and made public by an enterprise sponsor.
|
||||
|
||||
- Notification panel (the 🔔 button) has been implemented in (#201). Even though Element-web now requires enabling it in the Labs menu, the underlying support (`GET /_matrix/client/v3/notifications`) enhances the push-notification handling of other clients.
|
||||
|
||||
- Live room previews are now available. This support (`GET /_matrix/client/v3/events`) allows users, including guests, to sync updates for a public room without joining (4afd6f347b1).
|
||||
|
||||
- Thanks to a suggestion by @cyberdoors in (#29), the configuration option `encryption_enabled_by_default_for_room_type` is now available. This feature can enable encryption for a room even when the client does not. The values `all` or `invite` are accepted, the latter roughly meaning DM's only. Neither are enabled by default.
|
||||
|
||||
### Enhancements
|
||||
|
||||
- Thank you @tototomate123 for improving the reverse-proxy docs, adding dedicated pages for both [Caddy](https://github.com/matrix-construct/tuwunel/blob/e0a997c22784b453735b24907e607412b153ba56/docs/deploying/reverse-proxy-caddy.md) and [Nginx](https://github.com/matrix-construct/tuwunel/blob/e0a997c22784b453735b24907e607412b153ba56/docs/deploying/reverse-proxy-nginx.md) in (#209). Thanks to @tycode for pointing out the docs were missing for alternative proxies in (#197).
|
||||
|
||||
- Thanks to an observation by @iwalkalone69 in (#40), the last-seen time for a device in the session list is now updated acceptably. This function piggybacks on the presence system to prevent writing too frequently; testing has never shown it more than a minute or few out of date.
|
||||
|
||||
- Thanks to an inquiry by @EntityinArray in (#189) guest-accounts can now be enabled while registration tokens are also enabled to prevent fully open account registration. Note that registration tokens don't apply to guest-accounts and those are still fully open.
|
||||
|
||||
- Courtesy of @dasha-uwu the list of servers attempted when joining a room is now properly shuffled to increase the odds of finding a viable server, especially if an additional join attempt is made.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Special thanks to @BVollmerhaus for finding the TURN secret file configured by `turn_secret_file` was broken in (#211), forcing users to configure `turn_secret` directly. Thank you for fixing this in (#212).
|
||||
|
||||
- Thank you @scvalex for updating the nix build for Tuwunel's integration tests and re-enabling all checks. (#215)
|
||||
|
||||
- Thanks to a report by @Anagastes in (#146) **Nheko and NeoChat users can now enjoy properly verified devices.** Special thanks for the assistance of @deepbluev7 with diagnosing the cross-signing signature issue.
|
||||
|
||||
- Database columns intended for deletion, notably `roomsynctoken_shortstatehash`, never had the deletion command actually invoked on them 😭 explaining the lack of enthusiasm after the 1.4.3 release introduced stateless sync. **Users will now see the free disk space they were promised.** This was uncovered during an unrelated issue investigation courtesy of @frebib.
|
||||
|
||||
- Thanks to investigation by @dasha-uwu the pagination tokens in the `/relations` endpoint were buggy and now operate correctly.
|
||||
|
||||
- Thanks to @Polve for identifying the `DynamicUser=yes` directive in the systemd files was invalid and advising a replacement in (#207).
|
||||
|
||||
- Thanks to @daudix for reporting an edge-case where the server will refuse to start rather than robustly reporting errors during startup checks and recreate a missing media directory (#213).
|
||||
|
||||
- Push rule evaluation was never implemented for invites arriving over federation. Notifications are now properly sent in this case.
|
||||
|
||||
- Sliding-sync handlers were susceptible to errors under rare circumstances escaping to cause an HTTP 500, which wreaks havoc on the rust-sdk. This has now been prevented.
|
||||
|
||||
- Federating with Conduit over several non-essential endpoints was broken. It is unclear whether this affected an actual Conduit release version, but thanks to @kladki a fix is scheduled and we have included a workaround now on this end.
|
||||
- Requests to the [Federation Invite API](https://spec.matrix.org/v1.17/server-server-api/#put_matrixfederationv2inviteroomideventid) lacked sufficient validation on all input fields. An attacker can use this route to process other kinds of events: upon acceptance, they are signed by the victim's server as specified by the Matrix protocol. The attacker can therefore forge events on behalf of the victim's authority to gain control of a room. This vulnerability was present in all versions and derivatives of Conduit.
|
||||
@@ -5,7 +5,6 @@ authors = [
|
||||
]
|
||||
description = "Tuwunel, a high performance successor to Conduit and Conduwuit"
|
||||
language = "en"
|
||||
multilingual = false
|
||||
src = "docs"
|
||||
title = "Tuwunel One"
|
||||
text-direction = "ltr"
|
||||
@@ -15,7 +14,9 @@ build-dir = "public"
|
||||
create-missing = true
|
||||
extra-watch-dirs = [
|
||||
"debian",
|
||||
"docker",
|
||||
"docs",
|
||||
"rpm",
|
||||
]
|
||||
|
||||
[rust]
|
||||
@@ -24,7 +25,7 @@ edition = "2024"
|
||||
[output.html]
|
||||
git-repository-url = "https://github.com/matrix-construct/tuwunel"
|
||||
edit-url-template = "https://github.com/matrix-construct/tuwunel/edit/main/{path}"
|
||||
git-repository-icon = "fa-github-square"
|
||||
git-repository-icon = "fab-github"
|
||||
|
||||
[output.html.search]
|
||||
limit-results = 15
|
||||
+6
-6
@@ -1,11 +1,11 @@
|
||||
stack-size-threshold = 393216
|
||||
future-size-threshold = 24576
|
||||
array-size-threshold = 4096
|
||||
cognitive-complexity-threshold = 100 # TODO reduce me ALARA
|
||||
excessive-nesting-threshold = 8
|
||||
future-size-threshold = 8192
|
||||
stack-size-threshold = 196608 # TODO reduce me ALARA
|
||||
too-many-lines-threshold = 780 # TODO reduce me to <= 100
|
||||
type-complexity-threshold = 250 # reduce me to ~200
|
||||
large-error-threshold = 256 # TODO reduce me ALARA
|
||||
too-many-lines-threshold = 780 # TODO reduce me to <= 100
|
||||
excessive-nesting-threshold = 8
|
||||
type-complexity-threshold = 250 # reduce me to ~200
|
||||
cognitive-complexity-threshold = 100 # TODO reduce me ALARA
|
||||
|
||||
#disallowed-macros = [
|
||||
# { path = "log::error", reason = "use tuwunel_core::error" },
|
||||
|
||||
@@ -128,7 +128,7 @@ ENTRYPOINT valgrind \
|
||||
FROM input AS complement-base
|
||||
ARG var_cache
|
||||
ARG var_lib_apt
|
||||
ARG complement_ref="426bc3458e5287398ec39ab7d2b8f2e3103dcf39"
|
||||
ARG complement_ref="4d3130f06d0dc3f794b5d48fbdba0b466792b52b"
|
||||
ARG complement_tags="conduwuit_blacklist"
|
||||
ARG complement_tests="./tests/..."
|
||||
ARG complement_run=".*"
|
||||
|
||||
@@ -15,15 +15,17 @@ ENV src_path="${CARGO_TARGET_DIR}/${rust_target}/${cargo_target_profile}/tuwunel
|
||||
ENV dst_path="${install_prefix}/bin/tuwunel"
|
||||
COPY --from=bins $src_path $dst_path
|
||||
RUN <<EOF
|
||||
ret=$(ldd "${dst_path}")
|
||||
ldd -v "${dst_path}"
|
||||
ret=$?
|
||||
if [ "$ret" = "0" ] && [ "$assert_linkage" = "static" ]; then
|
||||
echo "($ret) expected a static binary"
|
||||
exit 1
|
||||
elif [ "$ret" != "0" ] && [ "$assert_linkage" = "dynamic" ]; then
|
||||
echo "($ret) expected a dynamic binary"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
set -eux
|
||||
ldd -v ${dst_path} || true
|
||||
du -h ${dst_path}
|
||||
sha1sum ${dst_path}
|
||||
du -h "${dst_path}"
|
||||
sha1sum "${dst_path}"
|
||||
EOF
|
||||
@@ -28,10 +28,12 @@ FROM input AS rocksdb-build
|
||||
ARG rocksdb_shared=0
|
||||
ARG rocksdb_portable="1"
|
||||
ARG rocksdb_opt_level="3"
|
||||
ARG rocksdb_lto="-flto -ffat-lto-objects"
|
||||
ARG rocksdb_build_type="Release"
|
||||
ARG rocksdb_cxx_flags="-ftls-model=initial-exec"
|
||||
ARG rocksdb_make_verbose="ON"
|
||||
ARG rocksdb_make_rule_messages="OFF"
|
||||
ARG rocksdb_numa=0
|
||||
ARG rocksdb_jemalloc=1
|
||||
ARG rocksdb_iouring=1
|
||||
ARG rocksdb_zstd=1
|
||||
@@ -59,7 +61,7 @@ RUN <<EOF
|
||||
"-DBUILD_SHARED_LIBS=${rocksdb_shared}" \
|
||||
"-DROCKSDB_BUILD_SHARED=${rocksdb_shared}" \
|
||||
"-DCMAKE_CXX_FLAGS:STRING=${rocksdb_cxx_flags}" \
|
||||
"-DCMAKE_CXX_FLAGS_RELEASE:STRING=-g0 -O${rocksdb_opt_level} -DNDEBUG" \
|
||||
"-DCMAKE_CXX_FLAGS_RELEASE:STRING=-g0 -O${rocksdb_opt_level} -DNDEBUG ${rocksdb_lto}" \
|
||||
"-DPORTABLE=${rocksdb_portable}" \
|
||||
"-DFAIL_ON_WARNINGS=0" \
|
||||
"-DUSE_RTTI=0" \
|
||||
@@ -73,6 +75,7 @@ RUN <<EOF
|
||||
"-DWITH_TOOLS=0" \
|
||||
"-DWITH_TESTS=0" \
|
||||
"-DWITH_GFLAGS=0" \
|
||||
"-DWITH_NUMA=${rocksdb_numa}" \
|
||||
"-DWITH_LIBURING=${rocksdb_iouring}" \
|
||||
"-DWITH_JEMALLOC=${rocksdb_jemalloc}" \
|
||||
"-DWITH_ZSTD=${rocksdb_zstd}" \
|
||||
|
||||
+17
-5
@@ -84,6 +84,9 @@ variable "rocksdb_build_type" {
|
||||
variable "rocksdb_make_verbose" {
|
||||
default = "ON"
|
||||
}
|
||||
variable "rocksdb_numa" {
|
||||
default = "0"
|
||||
}
|
||||
|
||||
# Complement options
|
||||
variable "complement_count" {
|
||||
@@ -865,6 +868,12 @@ target "install" {
|
||||
}
|
||||
args = {
|
||||
install_prefix = install_prefix
|
||||
assert_linkage = (
|
||||
substr(cargo_profile, 0, 5) == "bench"? "static":
|
||||
substr(cargo_profile, 0, 7) == "release"? "static":
|
||||
substr(rust_toolchain, 0, 6) == "stable"? "static":
|
||||
""
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1411,7 +1420,7 @@ target "deps-base" {
|
||||
join(" ", static_rustflags),
|
||||
join(" ", static_nightly_rustflags),
|
||||
join(" ", native_rustflags),
|
||||
"-C link-arg=-L/usr/lib/gcc/${sys_target_triple(sys_target)}/14", #FIXME
|
||||
"-C link-arg=-L/usr/lib/gcc/${sys_target_triple(sys_target)}/15", #FIXME
|
||||
contains(split(",", cargo_feat_sets[feat_set]), "bzip2_compression")?
|
||||
"-C link-arg=-l:libbz2.a": "",
|
||||
contains(split(",", cargo_feat_sets[feat_set]), "lz4_compression")?
|
||||
@@ -1433,7 +1442,7 @@ target "deps-base" {
|
||||
join(" ", static_nightly_rustflags),
|
||||
sys_target_triple(sys_target) == "x86_64-linux-gnu"?
|
||||
"-C target-cpu=${sys_target_isa(sys_target)}": "",
|
||||
"-C link-arg=-L/usr/lib/gcc/${sys_target_triple(sys_target)}/14", #FIXME
|
||||
"-C link-arg=-L/usr/lib/gcc/${sys_target_triple(sys_target)}/15", #FIXME
|
||||
contains(split(",", cargo_feat_sets[feat_set]), "bzip2_compression")?
|
||||
"-C link-arg=-l:libbz2.a": "",
|
||||
contains(split(",", cargo_feat_sets[feat_set]), "lz4_compression")?
|
||||
@@ -1453,7 +1462,7 @@ target "deps-base" {
|
||||
join(" ", static_rustflags),
|
||||
sys_target_triple(sys_target) == "x86_64-linux-gnu"?
|
||||
"-C target-cpu=${sys_target_isa(sys_target)}": "",
|
||||
"-C link-arg=-L/usr/lib/gcc/${sys_target_triple(sys_target)}/14", #FIXME
|
||||
"-C link-arg=-L/usr/lib/gcc/${sys_target_triple(sys_target)}/15", #FIXME
|
||||
contains(split(",", cargo_feat_sets[feat_set]), "bzip2_compression")?
|
||||
"-C link-arg=-l:libbz2.a": "",
|
||||
contains(split(",", cargo_feat_sets[feat_set]), "lz4_compression")?
|
||||
@@ -1473,7 +1482,7 @@ target "deps-base" {
|
||||
join(" ", static_rustflags),
|
||||
sys_target_triple(sys_target) == "x86_64-linux-gnu"?
|
||||
"-C target-cpu=${sys_target_isa(sys_target)}": "",
|
||||
"-C link-arg=-L/usr/lib/gcc/${sys_target_triple(sys_target)}/14", #FIXME
|
||||
"-C link-arg=-L/usr/lib/gcc/${sys_target_triple(sys_target)}/15", #FIXME
|
||||
contains(split(",", cargo_feat_sets[feat_set]), "bzip2_compression")?
|
||||
"-C link-arg=-l:libbz2.a": "",
|
||||
contains(split(",", cargo_feat_sets[feat_set]), "lz4_compression")?
|
||||
@@ -1552,6 +1561,7 @@ target "rocksdb-build" {
|
||||
rocksdb_zstd = contains(split(",", cargo_feat_sets[feat_set]), "zstd_compression")? 1: 0
|
||||
rocksdb_jemalloc = contains(split(",", cargo_feat_sets[feat_set]), "jemalloc")? 1: 0
|
||||
rocksdb_iouring = contains(split(",", cargo_feat_sets[feat_set]), "io_uring")? 1: 0
|
||||
rocksdb_numa = rocksdb_numa
|
||||
rocksdb_shared = 0
|
||||
rocksdb_opt_level = rocksdb_opt_level
|
||||
rocksdb_build_type = rocksdb_build_type
|
||||
@@ -1716,7 +1726,7 @@ cargo_installs = [
|
||||
"cargo-deb",
|
||||
"cargo-generate-rpm",
|
||||
"cargo-valgrind",
|
||||
#"lychee",
|
||||
"lychee",
|
||||
"mdbook",
|
||||
"typos-cli",
|
||||
]
|
||||
@@ -1805,6 +1815,8 @@ kitchen_packages = [
|
||||
"gzip",
|
||||
"jq",
|
||||
"libc6-dev",
|
||||
"libclang-dev",
|
||||
"libnuma-dev",
|
||||
"libssl-dev",
|
||||
"libsqlite3-dev",
|
||||
"make",
|
||||
|
||||
@@ -82,7 +82,7 @@ if test "$CI" = "true"; then
|
||||
fi
|
||||
|
||||
output_src="$cid:/usr/src/complement/full_output.jsonl"
|
||||
output_dst="complement.jsonl"
|
||||
output_dst="tests/complement/logs.jsonl"
|
||||
extract_output() {
|
||||
docker cp "$output_src" "$output_dst"
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ services:
|
||||
TUWUNEL_REGISTRATION_TOKEN: 'YOUR_TOKEN' # A registration token is required when registration is allowed.
|
||||
#TUWUNEL_YES_I_AM_VERY_VERY_SURE_I_WANT_AN_OPEN_REGISTRATION_SERVER_PRONE_TO_ABUSE: 'true'
|
||||
TUWUNEL_ALLOW_FEDERATION: 'true'
|
||||
TUWUNEL_ALLOW_CHECK_FOR_UPDATES: 'true'
|
||||
TUWUNEL_TRUSTED_SERVERS: '["matrix.org"]'
|
||||
#TUWUNEL_LOG: warn,state_res=warn
|
||||
TUWUNEL_ADDRESS: 0.0.0.0
|
||||
|
||||
@@ -36,7 +36,6 @@ services:
|
||||
TUWUNEL_REGISTRATION_TOKEN: 'YOUR_TOKEN' # A registration token is required when registration is allowed.
|
||||
#TUWUNEL_YES_I_AM_VERY_VERY_SURE_I_WANT_AN_OPEN_REGISTRATION_SERVER_PRONE_TO_ABUSE: 'true'
|
||||
TUWUNEL_ALLOW_FEDERATION: 'true'
|
||||
TUWUNEL_ALLOW_CHECK_FOR_UPDATES: 'true'
|
||||
TUWUNEL_TRUSTED_SERVERS: '["matrix.org"]'
|
||||
#TUWUNEL_LOG: warn,state_res=warn
|
||||
TUWUNEL_ADDRESS: 0.0.0.0
|
||||
|
||||
@@ -26,7 +26,6 @@ services:
|
||||
# TUWUNEL_LOG: info # default is: "warn,state_res=warn"
|
||||
# TUWUNEL_ALLOW_ENCRYPTION: 'true'
|
||||
# TUWUNEL_ALLOW_FEDERATION: 'true'
|
||||
# TUWUNEL_ALLOW_CHECK_FOR_UPDATES: 'true'
|
||||
# TUWUNEL_ALLOW_INCOMING_PRESENCE: true
|
||||
# TUWUNEL_ALLOW_OUTGOING_PRESENCE: true
|
||||
# TUWUNEL_ALLOW_LOCAL_PRESENCE: true
|
||||
|
||||
@@ -20,7 +20,6 @@ services:
|
||||
TUWUNEL_REGISTRATION_TOKEN: 'YOUR_TOKEN' # A registration token is required when registration is allowed.
|
||||
#TUWUNEL_YES_I_AM_VERY_VERY_SURE_I_WANT_AN_OPEN_REGISTRATION_SERVER_PRONE_TO_ABUSE: 'true'
|
||||
TUWUNEL_ALLOW_FEDERATION: 'true'
|
||||
TUWUNEL_ALLOW_CHECK_FOR_UPDATES: 'true'
|
||||
TUWUNEL_TRUSTED_SERVERS: '["matrix.org"]'
|
||||
#TUWUNEL_LOG: warn,state_res=warn
|
||||
TUWUNEL_ADDRESS: 0.0.0.0
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
# Generic deployment documentation
|
||||
|
||||
> ### Getting help
|
||||
> [!TIP]
|
||||
>
|
||||
> If you run into any problems while setting up Tuwunel [open an issue on
|
||||
> GitHub](https://github.com/matrix-construct/tuwunel/issues/new).
|
||||
> Getting help: If you run into any problems while setting up Tuwunel
|
||||
> [open an issue on GitHub](https://github.com/matrix-construct/tuwunel/issues/new).
|
||||
|
||||
## Installing Tuwunel
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[Container]
|
||||
Environment=TUWUNEL_SERVER_NAME=your.domain.here TUWUNEL_DATABASE_PATH=/var/lib/tuwunel TUWUNEL_PORT=6167 TUWUNEL_MAX_REQUEST_SIZE=20000000 TUWUNEL_ALLOW_REGISTRATION=true TUWUNEL_REGISTRATION_TOKEN=YOUR_TOKEN TUWUNEL_ALLOW_FEDERATION=true TUWUNEL_ALLOW_CHECK_FOR_UPDATES=true TUWUNEL_TRUSTED_SERVERS=["matrix.org"] TUWUNEL_ADDRESS=0.0.0.0 # Add TUWUNEL_CONFIG: '/etc/tuwunel.toml' if the config is mapped
|
||||
Environment=TUWUNEL_SERVER_NAME=your.domain.here TUWUNEL_DATABASE_PATH=/var/lib/tuwunel TUWUNEL_PORT=6167 TUWUNEL_MAX_REQUEST_SIZE=20000000 TUWUNEL_ALLOW_REGISTRATION=true TUWUNEL_REGISTRATION_TOKEN=YOUR_TOKEN TUWUNEL_ALLOW_FEDERATION=true TUWUNEL_TRUSTED_SERVERS=["matrix.org"] TUWUNEL_ADDRESS=0.0.0.0 # Add TUWUNEL_CONFIG: '/etc/tuwunel.toml' if the config is mapped
|
||||
Image=docker.io/jevolk/tuwunel:latest
|
||||
PublishPort=8448:6167
|
||||
Volume=/path/to/db:/var/lib/tuwunel
|
||||
|
||||
Generated
+27
-27
@@ -32,11 +32,11 @@
|
||||
"nixpkgs": "nixpkgs_2"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1761150191,
|
||||
"narHash": "sha256-fPQmV+K836jR/Tu6slfMdm9HL3p0IEPB5x5I7Zc6v5E=",
|
||||
"lastModified": 1763236786,
|
||||
"narHash": "sha256-JB19RGXDr6loKSdqwvA15jhRHwf6+9Crq2glqqVar84=",
|
||||
"owner": "cachix",
|
||||
"repo": "cachix",
|
||||
"rev": "5629a7d84c91df9c06650b18eb428cce4166c4fc",
|
||||
"rev": "938a275857047c300596092beaabaee6d892e243",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -85,11 +85,11 @@
|
||||
"complement": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1756358878,
|
||||
"narHash": "sha256-H/4TkbFcGsMRDZ7gNaXZ7NxeO3b1YgkVt9zPb+3ATSg=",
|
||||
"lastModified": 1761739261,
|
||||
"narHash": "sha256-XdzSBbJIYG6thrHbo44/qBiMu5R4bayfy/dlWo9AXBA=",
|
||||
"owner": "matrix-construct",
|
||||
"repo": "complement",
|
||||
"rev": "403840348f6bcc9cc8ed1671dc2f638c2b1ce4ac",
|
||||
"rev": "350d7666cab14cb0051ef53da7a1b0b3216d7269",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -116,11 +116,11 @@
|
||||
},
|
||||
"crane_2": {
|
||||
"locked": {
|
||||
"lastModified": 1760924934,
|
||||
"narHash": "sha256-tuuqY5aU7cUkR71sO2TraVKK2boYrdW3gCSXUkF4i44=",
|
||||
"lastModified": 1763511871,
|
||||
"narHash": "sha256-KKZWi+ij7oT0Ag8yC6MQkzfHGcytyjMJDD+47ZV1YNU=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "c6b4d5308293d0d04fcfeee92705017537cad02f",
|
||||
"rev": "099f9014bc8d0cd6e445470ea1df0fd691d5a548",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -170,11 +170,11 @@
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1761547629,
|
||||
"narHash": "sha256-4OH1CVm2PdjKRqEJ3RLfkQMDSBdn7VId6iyYCwKOK+U=",
|
||||
"lastModified": 1763707297,
|
||||
"narHash": "sha256-Bd9VGavwFBLpyU4pjiWfv73gUibNj8dc3xmOW8ff3bI=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "d82a7c64ea441e397914577c9a18f2867e5b364b",
|
||||
"rev": "7c2d3a165a4a080fdcb6c191d8f9768281c99f75",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -219,11 +219,11 @@
|
||||
"flake-compat_3": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1747046372,
|
||||
"narHash": "sha256-CIVLLkVgvHYbgI2UpXvIIBJ12HWgX+fjA8Xf8PUmqCY=",
|
||||
"lastModified": 1761588595,
|
||||
"narHash": "sha256-XKUZz9zewJNUj46b4AJdiRZJAvSZ0Dqj2BNfXvFlJC4=",
|
||||
"owner": "edolstra",
|
||||
"repo": "flake-compat",
|
||||
"rev": "9100a0f413b0c601e0533d1d94ffd501ce2e7885",
|
||||
"rev": "f387cd2afec9419c8ee37694406ca490c3f34ee5",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -346,11 +346,11 @@
|
||||
"liburing": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1761487364,
|
||||
"narHash": "sha256-PmRdt9dQUFGcVrX7XCh7z2FpRm1SqKgiYbIwpkJPjRU=",
|
||||
"lastModified": 1763758538,
|
||||
"narHash": "sha256-cDsxLOqeC7imBcArolTHvejSnWoadgpvDy1DJ2/3MOw=",
|
||||
"owner": "axboe",
|
||||
"repo": "liburing",
|
||||
"rev": "65ec4223032a38870dde2bce646ba4de13d2feff",
|
||||
"rev": "e1ef1e680ee38ed9116989155fca47921698c25f",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -493,11 +493,11 @@
|
||||
},
|
||||
"nixpkgs_3": {
|
||||
"locked": {
|
||||
"lastModified": 1761349956,
|
||||
"narHash": "sha256-tH3wHnOJms+U4k/rK2Nn1RfBrhffX92jLP/2VndSn0w=",
|
||||
"lastModified": 1763618868,
|
||||
"narHash": "sha256-v5afmLjn/uyD9EQuPBn7nZuaZVV9r+JerayK/4wvdWA=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "02f2cb8e0feb4596d20cc52fda73ccee960e3538",
|
||||
"rev": "a8d610af3f1a5fb71e23e08434d8d61a466fc942",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -510,11 +510,11 @@
|
||||
"rocksdb": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1749358049,
|
||||
"narHash": "sha256-ZSjvAZBfZkJrBIpw8ANZMbJVb8AeuogvuAipGVE4Qe4=",
|
||||
"lastModified": 1763593074,
|
||||
"narHash": "sha256-aOV/jJjRjNJ3hrRqhCsXlIz05NvEhDF/j5Q5UOQuvp8=",
|
||||
"owner": "matrix-construct",
|
||||
"repo": "rocksdb",
|
||||
"rev": "cf7f65d0b377af019661c240f9165b3ef60640c3",
|
||||
"rev": "9a3a213b55df0b11408102c899a940675c0d90e4",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -542,11 +542,11 @@
|
||||
"rust-analyzer-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1761500479,
|
||||
"narHash": "sha256-syeBTCCU96qPJHcVpwHeCwmPCiLTDHHgYQYhpZ0iwLo=",
|
||||
"lastModified": 1763648203,
|
||||
"narHash": "sha256-/WJdebbRD+m5vr2xy/bJdCpqd7YHSMapjuXAM/0lvtA=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "049767e6faa84b2d1a951d8f227e6ebd99d728a2",
|
||||
"rev": "eaaa2da9fbbfd7a79ff501e0563351cb2004574a",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -21,7 +21,6 @@ media_startup_check = true
|
||||
prune_missing_media = true
|
||||
log_colors = true
|
||||
admin_room_notices = false
|
||||
allow_check_for_updates = false
|
||||
intentionally_unknown_config_option_for_testing = true
|
||||
rocksdb_log_level = "info"
|
||||
rocksdb_max_log_files = 1
|
||||
|
||||
@@ -236,8 +236,8 @@ pub(super) async fn get_remote_pdu(
|
||||
|
||||
match self
|
||||
.services
|
||||
.sending
|
||||
.send_federation_request(&server, ruma::api::federation::event::get_event::v1::Request {
|
||||
.federation
|
||||
.execute(&server, ruma::api::federation::event::get_event::v1::Request {
|
||||
event_id: event_id.clone(),
|
||||
})
|
||||
.await
|
||||
@@ -327,11 +327,8 @@ pub(super) async fn ping(&self, server: OwnedServerName) -> Result {
|
||||
|
||||
match self
|
||||
.services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
&server,
|
||||
ruma::api::federation::discovery::get_server_version::v1::Request {},
|
||||
)
|
||||
.federation
|
||||
.execute(&server, ruma::api::federation::discovery::get_server_version::v1::Request {})
|
||||
.await
|
||||
{
|
||||
| Err(e) => {
|
||||
@@ -571,8 +568,8 @@ pub(super) async fn force_set_room_state_from_server(
|
||||
|
||||
let remote_state_response = self
|
||||
.services
|
||||
.sending
|
||||
.send_federation_request(&server_name, get_room_state::v1::Request {
|
||||
.federation
|
||||
.execute(&server_name, get_room_state::v1::Request {
|
||||
room_id: room_id.clone(),
|
||||
event_id: first_pdu.event_id().to_owned(),
|
||||
})
|
||||
|
||||
@@ -15,7 +15,7 @@ pub(crate) enum SyncCommand {
|
||||
/// Show details of sliding sync connection by ID.
|
||||
ShowConnection {
|
||||
user_id: OwnedUserId,
|
||||
device_id: OwnedDeviceId,
|
||||
device_id: Option<OwnedDeviceId>,
|
||||
conn_id: Option<String>,
|
||||
},
|
||||
|
||||
@@ -43,7 +43,7 @@ pub(super) async fn list_connections(&self) -> Result {
|
||||
pub(super) async fn show_connection(
|
||||
&self,
|
||||
user_id: OwnedUserId,
|
||||
device_id: OwnedDeviceId,
|
||||
device_id: Option<OwnedDeviceId>,
|
||||
conn_id: Option<String>,
|
||||
) -> Result {
|
||||
let key = into_connection_key(user_id, device_id, conn_id);
|
||||
|
||||
+15
-155
@@ -1,4 +1,4 @@
|
||||
use std::{collections::BTreeMap, fmt::Write as _};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use futures::{FutureExt, StreamExt};
|
||||
use ruma::{
|
||||
@@ -13,10 +13,9 @@ use ruma::{
|
||||
},
|
||||
};
|
||||
use tuwunel_core::{
|
||||
Err, Result, debug, debug_warn, error, info, is_equal_to,
|
||||
Err, Result, debug_warn, info,
|
||||
matrix::{Event, pdu::PduBuilder},
|
||||
utils::{self, ReadyExt},
|
||||
warn,
|
||||
};
|
||||
use tuwunel_service::Services;
|
||||
|
||||
@@ -62,148 +61,11 @@ pub(super) async fn create_user(&self, username: String, password: Option<String
|
||||
|
||||
let password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
|
||||
|
||||
// Create user
|
||||
self.services
|
||||
.users
|
||||
.create(&user_id, Some(password.as_str()), None)
|
||||
.full_register(&user_id, Some(&password), None, None, false, true)
|
||||
.await?;
|
||||
|
||||
// Default to pretty displayname
|
||||
let mut displayname = user_id.localpart().to_owned();
|
||||
|
||||
// If `new_user_displayname_suffix` is set, registration will push whatever
|
||||
// content is set to the user's display name with a space before it
|
||||
if !self
|
||||
.services
|
||||
.server
|
||||
.config
|
||||
.new_user_displayname_suffix
|
||||
.is_empty()
|
||||
{
|
||||
write!(
|
||||
displayname,
|
||||
" {}",
|
||||
self.services
|
||||
.server
|
||||
.config
|
||||
.new_user_displayname_suffix
|
||||
)?;
|
||||
}
|
||||
|
||||
self.services
|
||||
.users
|
||||
.set_displayname(&user_id, Some(displayname));
|
||||
|
||||
// Initial account data
|
||||
self.services
|
||||
.account_data
|
||||
.update(
|
||||
None,
|
||||
&user_id,
|
||||
ruma::events::GlobalAccountDataEventType::PushRules
|
||||
.to_string()
|
||||
.into(),
|
||||
&serde_json::to_value(ruma::events::push_rules::PushRulesEvent {
|
||||
content: ruma::events::push_rules::PushRulesEventContent {
|
||||
global: ruma::push::Ruleset::server_default(&user_id),
|
||||
},
|
||||
})?,
|
||||
)
|
||||
.await?;
|
||||
|
||||
if !self
|
||||
.services
|
||||
.server
|
||||
.config
|
||||
.auto_join_rooms
|
||||
.is_empty()
|
||||
{
|
||||
for room in &self.services.server.config.auto_join_rooms {
|
||||
let Ok(room_id) = self.services.alias.maybe_resolve(room).await else {
|
||||
error!(
|
||||
%user_id,
|
||||
"Failed to resolve room alias to room ID when attempting to auto join {room}, skipping"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
|
||||
if !self
|
||||
.services
|
||||
.state_cache
|
||||
.server_in_room(self.services.globals.server_name(), &room_id)
|
||||
.await
|
||||
{
|
||||
warn!(
|
||||
"Skipping room {room} to automatically join as we have never joined before."
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let state_lock = self.services.state.mutex.lock(&room_id).await;
|
||||
|
||||
if let Some(room_server_name) = room.server_name() {
|
||||
match self
|
||||
.services
|
||||
.membership
|
||||
.join(
|
||||
&user_id,
|
||||
&room_id,
|
||||
Some("Automatically joining this room upon registration".to_owned()),
|
||||
&[
|
||||
self.services.globals.server_name().to_owned(),
|
||||
room_server_name.to_owned(),
|
||||
],
|
||||
&None,
|
||||
&state_lock,
|
||||
)
|
||||
.await
|
||||
{
|
||||
| Ok(_response) => {
|
||||
info!("Automatically joined room {room} for user {user_id}");
|
||||
},
|
||||
| Err(e) => {
|
||||
// don't return this error so we don't fail registrations
|
||||
error!(
|
||||
"Failed to automatically join room {room} for user {user_id}: {e}"
|
||||
);
|
||||
self.services
|
||||
.admin
|
||||
.send_text(&format!(
|
||||
"Failed to automatically join room {room} for user {user_id}: \
|
||||
{e}"
|
||||
))
|
||||
.await;
|
||||
},
|
||||
}
|
||||
|
||||
drop(state_lock);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// we dont add a device since we're not the user, just the creator
|
||||
|
||||
// if this account creation is from the CLI / --execute, invite the first user
|
||||
// to admin room
|
||||
if let Ok(admin_room) = self.services.admin.get_admin_room().await {
|
||||
if self
|
||||
.services
|
||||
.state_cache
|
||||
.room_joined_count(&admin_room)
|
||||
.await
|
||||
.is_ok_and(is_equal_to!(1))
|
||||
{
|
||||
self.services
|
||||
.admin
|
||||
.make_user_admin(&user_id)
|
||||
.boxed()
|
||||
.await?;
|
||||
warn!("Granting {user_id} admin privileges as the first user");
|
||||
}
|
||||
} else {
|
||||
debug!("create_user admin command called without an admin room being available");
|
||||
}
|
||||
|
||||
self.write_str(&format!("Created user with user_id: {user_id} and password: `{password}`"))
|
||||
.await
|
||||
}
|
||||
@@ -403,7 +265,7 @@ pub(super) async fn list_joined_rooms(&self, user_id: String) -> Result {
|
||||
#[admin_command]
|
||||
pub(super) async fn force_join_list_of_local_users(
|
||||
&self,
|
||||
room_id: OwnedRoomOrAliasId,
|
||||
room: OwnedRoomOrAliasId,
|
||||
yes_i_want_to_do_this: bool,
|
||||
) -> Result {
|
||||
if self.body.len() < 2
|
||||
@@ -415,7 +277,7 @@ pub(super) async fn force_join_list_of_local_users(
|
||||
|
||||
if !yes_i_want_to_do_this {
|
||||
return Err!(
|
||||
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to force \
|
||||
"You must pass the --yes-i-want-to-do-this flag to ensure you really want to force \
|
||||
bulk join all specified local users.",
|
||||
);
|
||||
}
|
||||
@@ -427,7 +289,7 @@ pub(super) async fn force_join_list_of_local_users(
|
||||
let (room_id, servers) = self
|
||||
.services
|
||||
.alias
|
||||
.maybe_resolve_with_servers(&room_id, None)
|
||||
.maybe_resolve_with_servers(&room, None)
|
||||
.await?;
|
||||
|
||||
if !self
|
||||
@@ -505,9 +367,10 @@ pub(super) async fn force_join_list_of_local_users(
|
||||
.join(
|
||||
&user_id,
|
||||
&room_id,
|
||||
Some(&room),
|
||||
Some(String::from(BULK_JOIN_REASON)),
|
||||
&servers,
|
||||
&None,
|
||||
false,
|
||||
&state_lock,
|
||||
)
|
||||
.await
|
||||
@@ -534,7 +397,7 @@ pub(super) async fn force_join_list_of_local_users(
|
||||
#[admin_command]
|
||||
pub(super) async fn force_join_all_local_users(
|
||||
&self,
|
||||
room_id: OwnedRoomOrAliasId,
|
||||
room: OwnedRoomOrAliasId,
|
||||
yes_i_want_to_do_this: bool,
|
||||
) -> Result {
|
||||
if !yes_i_want_to_do_this {
|
||||
@@ -551,7 +414,7 @@ pub(super) async fn force_join_all_local_users(
|
||||
let (room_id, servers) = self
|
||||
.services
|
||||
.alias
|
||||
.maybe_resolve_with_servers(&room_id, None)
|
||||
.maybe_resolve_with_servers(&room, None)
|
||||
.await?;
|
||||
|
||||
if !self
|
||||
@@ -600,9 +463,10 @@ pub(super) async fn force_join_all_local_users(
|
||||
.join(
|
||||
user_id,
|
||||
&room_id,
|
||||
Some(&room),
|
||||
Some(String::from(BULK_JOIN_REASON)),
|
||||
&servers,
|
||||
&None,
|
||||
false,
|
||||
&state_lock,
|
||||
)
|
||||
.await
|
||||
@@ -627,16 +491,12 @@ pub(super) async fn force_join_all_local_users(
|
||||
}
|
||||
|
||||
#[admin_command]
|
||||
pub(super) async fn force_join_room(
|
||||
&self,
|
||||
user_id: String,
|
||||
room_id: OwnedRoomOrAliasId,
|
||||
) -> Result {
|
||||
pub(super) async fn force_join_room(&self, user_id: String, room: OwnedRoomOrAliasId) -> Result {
|
||||
let user_id = parse_local_user_id(self.services, &user_id)?;
|
||||
let (room_id, servers) = self
|
||||
.services
|
||||
.alias
|
||||
.maybe_resolve_with_servers(&room_id, None)
|
||||
.maybe_resolve_with_servers(&room, None)
|
||||
.await?;
|
||||
|
||||
assert!(
|
||||
@@ -648,7 +508,7 @@ pub(super) async fn force_join_room(
|
||||
|
||||
self.services
|
||||
.membership
|
||||
.join(&user_id, &room_id, None, &servers, &None, &state_lock)
|
||||
.join(&user_id, &room_id, Some(&room), None, &servers, false, &state_lock)
|
||||
.await?;
|
||||
|
||||
drop(state_lock);
|
||||
|
||||
@@ -78,7 +78,7 @@ pub(super) enum UserCommand {
|
||||
/// - Manually join a local user to a room.
|
||||
ForceJoinRoom {
|
||||
user_id: String,
|
||||
room_id: OwnedRoomOrAliasId,
|
||||
room: OwnedRoomOrAliasId,
|
||||
},
|
||||
|
||||
/// - Manually leave a local user from a room.
|
||||
@@ -148,7 +148,7 @@ pub(super) enum UserCommand {
|
||||
///
|
||||
/// Requires the `--yes-i-want-to-do-this` flag.
|
||||
ForceJoinListOfLocalUsers {
|
||||
room_id: OwnedRoomOrAliasId,
|
||||
room: OwnedRoomOrAliasId,
|
||||
|
||||
#[arg(long)]
|
||||
yes_i_want_to_do_this: bool,
|
||||
@@ -160,7 +160,7 @@ pub(super) enum UserCommand {
|
||||
///
|
||||
/// Requires the `--yes-i-want-to-do-this` flag.
|
||||
ForceJoinAllLocalUsers {
|
||||
room_id: OwnedRoomOrAliasId,
|
||||
room: OwnedRoomOrAliasId,
|
||||
|
||||
#[arg(long)]
|
||||
yes_i_want_to_do_this: bool,
|
||||
|
||||
@@ -5,7 +5,7 @@ use ruma::api::client::account::{
|
||||
ThirdPartyIdRemovalStatus, change_password, deactivate, get_3pids,
|
||||
request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn, whoami,
|
||||
};
|
||||
use tuwunel_core::{Err, Result, info, utils::ReadyExt};
|
||||
use tuwunel_core::{Err, Result, err, info, utils::ReadyExt};
|
||||
|
||||
use crate::{Ruma, router::auth_uiaa};
|
||||
|
||||
@@ -73,10 +73,12 @@ pub(crate) async fn whoami_route(
|
||||
Ok(whoami::v3::Response {
|
||||
user_id: body.sender_user().to_owned(),
|
||||
device_id: body.sender_device.clone(),
|
||||
is_guest: services
|
||||
.users
|
||||
.is_deactivated(body.sender_user())
|
||||
.await? && body.appservice_info.is_none(),
|
||||
is_guest: body.appservice_info.is_none()
|
||||
&& services
|
||||
.users
|
||||
.is_deactivated(body.sender_user())
|
||||
.await
|
||||
.map_err(|_| err!(Request(Forbidden("User does not exist."))))?,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+7
-17
@@ -121,26 +121,16 @@ async fn room_available_servers(
|
||||
|
||||
// insert our server as the very first choice if in list, else check if we can
|
||||
// prefer the room alias server first
|
||||
match servers
|
||||
if let Some(server_index) = servers
|
||||
.iter()
|
||||
.position(|server_name| services.globals.server_is_ours(server_name))
|
||||
{
|
||||
| Some(server_index) => {
|
||||
servers.swap_remove(server_index);
|
||||
servers.insert(0, services.globals.server_name().to_owned());
|
||||
},
|
||||
| _ => {
|
||||
match servers
|
||||
.iter()
|
||||
.position(|server| server == room_alias.server_name())
|
||||
{
|
||||
| Some(alias_server_index) => {
|
||||
servers.swap_remove(alias_server_index);
|
||||
servers.insert(0, room_alias.server_name().into());
|
||||
},
|
||||
| _ => {},
|
||||
}
|
||||
},
|
||||
servers.swap(0, server_index);
|
||||
} else if let Some(alias_server_index) = servers
|
||||
.iter()
|
||||
.position(|server| server == room_alias.server_name())
|
||||
{
|
||||
servers.swap(0, alias_server_index);
|
||||
}
|
||||
|
||||
servers
|
||||
|
||||
@@ -37,13 +37,10 @@ pub(crate) async fn appservice_ping(
|
||||
let timer = tokio::time::Instant::now();
|
||||
|
||||
let _response = services
|
||||
.sending
|
||||
.send_appservice_request(
|
||||
appservice_info.registration.clone(),
|
||||
ping::send_ping::v1::Request {
|
||||
transaction_id: body.transaction_id.clone(),
|
||||
},
|
||||
)
|
||||
.appservice
|
||||
.send_request(appservice_info.registration.clone(), ping::send_ping::v1::Request {
|
||||
transaction_id: body.transaction_id.clone(),
|
||||
})
|
||||
.await?
|
||||
.expect("We already validated if an appservice URL exists above");
|
||||
|
||||
|
||||
@@ -32,8 +32,8 @@ pub(crate) async fn get_context_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_context::v3::Request>,
|
||||
) -> Result<get_context::v3::Response> {
|
||||
let sender = body.sender();
|
||||
let (sender_user, sender_device) = sender;
|
||||
let sender_user = body.sender_user();
|
||||
let sender_device = body.sender_device.as_deref();
|
||||
let room_id = &body.room_id;
|
||||
let event_id = &body.event_id;
|
||||
let filter = &body.filter;
|
||||
@@ -110,7 +110,7 @@ pub(crate) async fn get_context_route(
|
||||
|
||||
let lazy_loading_context = lazy_loading::Context {
|
||||
user_id: sender_user,
|
||||
device_id: Some(sender_device),
|
||||
device_id: sender_device,
|
||||
room_id,
|
||||
token: Some(base_count.into_unsigned()),
|
||||
options: Some(&filter.lazy_load_options),
|
||||
|
||||
@@ -2,14 +2,14 @@ use axum::extract::State;
|
||||
use axum_client_ip::InsecureClientIp;
|
||||
use futures::StreamExt;
|
||||
use ruma::{
|
||||
MilliSecondsSinceUnixEpoch, OwnedDeviceId,
|
||||
MilliSecondsSinceUnixEpoch,
|
||||
api::client::device::{
|
||||
self, delete_device, delete_devices, get_device, get_devices, update_device,
|
||||
},
|
||||
};
|
||||
use tuwunel_core::{Err, Result, debug, err, utils, utils::string::to_small_string};
|
||||
use tuwunel_core::{Err, Result, debug, err, utils::string::to_small_string};
|
||||
|
||||
use crate::{Ruma, client::DEVICE_ID_LENGTH, router::auth_uiaa};
|
||||
use crate::{Ruma, router::auth_uiaa};
|
||||
|
||||
/// # `GET /_matrix/client/r0/devices`
|
||||
///
|
||||
@@ -94,13 +94,11 @@ pub(crate) async fn update_device_route(
|
||||
appservice.registration.id
|
||||
);
|
||||
|
||||
let device_id = OwnedDeviceId::from(utils::random_string(DEVICE_ID_LENGTH));
|
||||
|
||||
services
|
||||
.users
|
||||
.create_device(
|
||||
sender_user,
|
||||
&device_id,
|
||||
None,
|
||||
(Some(&appservice.registration.as_token), None),
|
||||
None,
|
||||
None,
|
||||
|
||||
@@ -220,8 +220,8 @@ pub(crate) async fn get_public_rooms_filtered_helper(
|
||||
server.filter(|server_name| !services.globals.server_is_ours(server_name))
|
||||
{
|
||||
let response = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
.federation
|
||||
.execute(
|
||||
other_server,
|
||||
federation::directory::get_public_rooms_filtered::v1::Request {
|
||||
limit,
|
||||
|
||||
@@ -23,7 +23,7 @@ pub(crate) async fn events_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<Request>,
|
||||
) -> Result<Response> {
|
||||
let (sender_user, sender_device) = body.sender();
|
||||
let sender_user = body.sender_user();
|
||||
|
||||
let from = body
|
||||
.body
|
||||
@@ -62,9 +62,11 @@ pub(crate) async fn events_route(
|
||||
.expect("configuration must limit maximum timeout");
|
||||
|
||||
loop {
|
||||
let watchers = services
|
||||
.sync
|
||||
.watch(sender_user, sender_device, once(room_id).stream());
|
||||
let watchers = services.sync.watch(
|
||||
sender_user,
|
||||
body.sender_device.as_deref(),
|
||||
once(room_id).stream(),
|
||||
);
|
||||
|
||||
let next_batch = services.globals.wait_pending().await?;
|
||||
|
||||
|
||||
@@ -35,7 +35,8 @@ pub(crate) async fn upload_keys_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<upload_keys::v3::Request>,
|
||||
) -> Result<upload_keys::v3::Response> {
|
||||
let (sender_user, sender_device) = body.sender();
|
||||
let sender_user = body.sender_user();
|
||||
let sender_device = body.sender_device()?;
|
||||
|
||||
let one_time_keys = body
|
||||
.one_time_keys
|
||||
@@ -503,10 +504,7 @@ where
|
||||
let request =
|
||||
federation::keys::get_keys::v1::Request { device_keys: device_keys_input_fed };
|
||||
|
||||
let response = services
|
||||
.sending
|
||||
.send_federation_request(server, request)
|
||||
.await;
|
||||
let response = services.federation.execute(server, request).await;
|
||||
|
||||
(server, response)
|
||||
})
|
||||
@@ -631,8 +629,8 @@ pub(crate) async fn claim_keys_helper(
|
||||
(
|
||||
server,
|
||||
services
|
||||
.sending
|
||||
.send_federation_request(server, federation::keys::claim_keys::v1::Request {
|
||||
.federation
|
||||
.execute(server, federation::keys::claim_keys::v1::Request {
|
||||
one_time_keys: one_time_keys_input_fed,
|
||||
})
|
||||
.await,
|
||||
|
||||
@@ -22,8 +22,7 @@ pub(crate) async fn invite_user_route(
|
||||
|
||||
invite_check(&services, sender_user, room_id).await?;
|
||||
|
||||
banned_room_check(&services, sender_user, Some(room_id), room_id.server_name(), client)
|
||||
.await?;
|
||||
banned_room_check(&services, sender_user, room_id, None, client).await?;
|
||||
|
||||
let invite_user::v3::InvitationRecipient::UserId { user_id } = &body.recipient else {
|
||||
return Err!(Request(ThreepidDenied("Third party identifiers are not implemented")));
|
||||
|
||||
@@ -2,13 +2,13 @@ use axum::extract::State;
|
||||
use axum_client_ip::InsecureClientIp;
|
||||
use futures::FutureExt;
|
||||
use ruma::{
|
||||
RoomId, RoomOrAliasId,
|
||||
RoomId,
|
||||
api::client::membership::{join_room_by_id, join_room_by_id_or_alias},
|
||||
};
|
||||
use tuwunel_core::Result;
|
||||
use tuwunel_core::{Result, warn};
|
||||
|
||||
use super::banned_room_check;
|
||||
use crate::{Ruma, client::membership::get_join_params};
|
||||
use crate::Ruma;
|
||||
|
||||
/// # `POST /_matrix/client/r0/rooms/{roomId}/join`
|
||||
///
|
||||
@@ -28,30 +28,38 @@ pub(crate) async fn join_room_by_id_route(
|
||||
|
||||
let room_id: &RoomId = &body.room_id;
|
||||
|
||||
banned_room_check(&services, sender_user, Some(room_id), room_id.server_name(), client)
|
||||
.await?;
|
||||
banned_room_check(&services, sender_user, room_id, None, client).await?;
|
||||
|
||||
let (room_id, servers) =
|
||||
get_join_params(&services, sender_user, <&RoomOrAliasId>::from(room_id), &[]).await?;
|
||||
let state_lock = services.state.mutex.lock(room_id).await;
|
||||
|
||||
let state_lock = services.state.mutex.lock(&room_id).await;
|
||||
|
||||
services
|
||||
let mut errors = 0_usize;
|
||||
while let Err(e) = services
|
||||
.membership
|
||||
.join(
|
||||
sender_user,
|
||||
&room_id,
|
||||
room_id,
|
||||
None,
|
||||
body.reason.clone(),
|
||||
&servers,
|
||||
&body.appservice_info,
|
||||
&[],
|
||||
body.appservice_info.is_some(),
|
||||
&state_lock,
|
||||
)
|
||||
.boxed()
|
||||
.await?;
|
||||
.await
|
||||
{
|
||||
errors = errors.saturating_add(1);
|
||||
if errors >= services.config.max_join_attempts_per_join_request {
|
||||
warn!(
|
||||
"Several servers failed. Giving up for this request. Try again for different \
|
||||
server selection."
|
||||
);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
drop(state_lock);
|
||||
|
||||
Ok(join_room_by_id::v3::Response { room_id })
|
||||
Ok(join_room_by_id::v3::Response { room_id: room_id.to_owned() })
|
||||
}
|
||||
|
||||
/// # `POST /_matrix/client/r0/join/{roomIdOrAlias}`
|
||||
@@ -72,28 +80,42 @@ pub(crate) async fn join_room_by_id_or_alias_route(
|
||||
let sender_user = body.sender_user();
|
||||
let appservice_info = &body.appservice_info;
|
||||
|
||||
let (room_id, servers) =
|
||||
get_join_params(&services, sender_user, &body.room_id_or_alias, &body.via).await?;
|
||||
let (room_id, servers) = services
|
||||
.alias
|
||||
.maybe_resolve_with_servers(&body.room_id_or_alias, Some(&body.via))
|
||||
.await?;
|
||||
|
||||
banned_room_check(&services, sender_user, Some(&room_id), room_id.server_name(), client)
|
||||
banned_room_check(&services, sender_user, &room_id, Some(&body.room_id_or_alias), client)
|
||||
.await?;
|
||||
|
||||
let state_lock = services.state.mutex.lock(&room_id).await;
|
||||
|
||||
services
|
||||
let mut errors = 0_usize;
|
||||
while let Err(e) = services
|
||||
.membership
|
||||
.join(
|
||||
sender_user,
|
||||
&room_id,
|
||||
Some(&body.room_id_or_alias),
|
||||
body.reason.clone(),
|
||||
&servers,
|
||||
appservice_info,
|
||||
appservice_info.is_some(),
|
||||
&state_lock,
|
||||
)
|
||||
.boxed()
|
||||
.await?;
|
||||
.await
|
||||
{
|
||||
errors = errors.saturating_add(1);
|
||||
if errors >= services.config.max_join_attempts_per_join_request {
|
||||
warn!(
|
||||
"Several servers failed. Giving up for this request. Try again for different \
|
||||
server selection."
|
||||
);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
drop(state_lock);
|
||||
|
||||
Ok(join_room_by_id_or_alias::v3::Response { room_id })
|
||||
Ok(join_room_by_id_or_alias::v3::Response { room_id: room_id.clone() })
|
||||
}
|
||||
@@ -1,45 +1,10 @@
|
||||
use std::{borrow::Borrow, collections::HashMap, iter::once, sync::Arc};
|
||||
|
||||
use axum::extract::State;
|
||||
use axum_client_ip::InsecureClientIp;
|
||||
use futures::{FutureExt, StreamExt};
|
||||
use ruma::{
|
||||
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedServerName, RoomId,
|
||||
RoomVersionId, UserId,
|
||||
api::{
|
||||
client::knock::knock_room,
|
||||
federation::{
|
||||
membership::RawStrippedState,
|
||||
{self},
|
||||
},
|
||||
},
|
||||
canonical_json::to_canonical_value,
|
||||
events::{
|
||||
StateEventType,
|
||||
room::member::{MembershipState, RoomMemberEventContent},
|
||||
},
|
||||
};
|
||||
use tuwunel_core::{
|
||||
Err, Result, debug, debug_info, debug_warn, err, extract_variant, info,
|
||||
matrix::{
|
||||
PduCount,
|
||||
event::{Event, gen_event_id},
|
||||
pdu::{PduBuilder, PduEvent},
|
||||
},
|
||||
trace,
|
||||
utils::{self},
|
||||
warn,
|
||||
};
|
||||
use tuwunel_service::{
|
||||
Services,
|
||||
rooms::{
|
||||
state::RoomMutexGuard,
|
||||
state_compressor::{CompressedState, HashSetCompressStateEvent},
|
||||
},
|
||||
};
|
||||
use ruma::api::client::knock::knock_room;
|
||||
use tuwunel_core::Result;
|
||||
|
||||
use super::banned_room_check;
|
||||
use crate::{Ruma, client::membership::get_join_params};
|
||||
use crate::Ruma;
|
||||
|
||||
/// # `POST /_matrix/client/*/knock/{roomIdOrAlias}`
|
||||
///
|
||||
@@ -51,545 +16,30 @@ pub(crate) async fn knock_room_route(
|
||||
body: Ruma<knock_room::v3::Request>,
|
||||
) -> Result<knock_room::v3::Response> {
|
||||
let sender_user = body.sender_user();
|
||||
let body = &body.body;
|
||||
|
||||
let (room_id, servers) =
|
||||
get_join_params(&services, sender_user, &body.room_id_or_alias, &body.via).await?;
|
||||
|
||||
banned_room_check(&services, sender_user, Some(&room_id), room_id.server_name(), client)
|
||||
let (room_id, servers) = services
|
||||
.alias
|
||||
.maybe_resolve_with_servers(&body.room_id_or_alias, Some(&body.via))
|
||||
.await?;
|
||||
|
||||
knock_room_by_id_helper(&services, sender_user, &room_id, body.reason.clone(), &servers).await
|
||||
}
|
||||
|
||||
async fn knock_room_by_id_helper(
|
||||
services: &Services,
|
||||
sender_user: &UserId,
|
||||
room_id: &RoomId,
|
||||
reason: Option<String>,
|
||||
servers: &[OwnedServerName],
|
||||
) -> Result<knock_room::v3::Response> {
|
||||
let state_lock = services.state.mutex.lock(room_id).await;
|
||||
|
||||
if services
|
||||
.state_cache
|
||||
.is_invited(sender_user, room_id)
|
||||
.await
|
||||
{
|
||||
debug_warn!("{sender_user} is already invited in {room_id} but attempted to knock");
|
||||
return Err!(Request(Forbidden(
|
||||
"You cannot knock on a room you are already invited/accepted to."
|
||||
)));
|
||||
}
|
||||
|
||||
if services
|
||||
.state_cache
|
||||
.is_joined(sender_user, room_id)
|
||||
.await
|
||||
{
|
||||
debug_warn!("{sender_user} is already joined in {room_id} but attempted to knock");
|
||||
return Err!(Request(Forbidden("You cannot knock on a room you are already joined in.")));
|
||||
}
|
||||
|
||||
if services
|
||||
.state_cache
|
||||
.is_knocked(sender_user, room_id)
|
||||
.await
|
||||
{
|
||||
debug_warn!("{sender_user} is already knocked in {room_id}");
|
||||
return Ok(knock_room::v3::Response { room_id: room_id.into() });
|
||||
}
|
||||
|
||||
if let Ok(membership) = services
|
||||
.state_accessor
|
||||
.get_member(room_id, sender_user)
|
||||
.await
|
||||
{
|
||||
if membership.membership == MembershipState::Ban {
|
||||
debug_warn!("{sender_user} is banned from {room_id} but attempted to knock");
|
||||
return Err!(Request(Forbidden("You cannot knock on a room you are banned from.")));
|
||||
}
|
||||
}
|
||||
|
||||
let server_in_room = services
|
||||
.state_cache
|
||||
.server_in_room(services.globals.server_name(), room_id)
|
||||
.await;
|
||||
|
||||
let local_knock = server_in_room
|
||||
|| servers.is_empty()
|
||||
|| (servers.len() == 1 && services.globals.server_is_ours(&servers[0]));
|
||||
|
||||
if local_knock {
|
||||
knock_room_helper_local(services, sender_user, room_id, reason, servers, state_lock)
|
||||
.boxed()
|
||||
.await?;
|
||||
} else {
|
||||
knock_room_helper_remote(services, sender_user, room_id, reason, servers, state_lock)
|
||||
.boxed()
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(knock_room::v3::Response::new(room_id.to_owned()))
|
||||
}
|
||||
|
||||
async fn knock_room_helper_local(
|
||||
services: &Services,
|
||||
sender_user: &UserId,
|
||||
room_id: &RoomId,
|
||||
reason: Option<String>,
|
||||
servers: &[OwnedServerName],
|
||||
state_lock: RoomMutexGuard,
|
||||
) -> Result {
|
||||
debug_info!("We can knock locally");
|
||||
|
||||
let room_version_id = services.state.get_room_version(room_id).await?;
|
||||
|
||||
if matches!(
|
||||
room_version_id,
|
||||
RoomVersionId::V1
|
||||
| RoomVersionId::V2
|
||||
| RoomVersionId::V3
|
||||
| RoomVersionId::V4
|
||||
| RoomVersionId::V5
|
||||
| RoomVersionId::V6
|
||||
) {
|
||||
return Err!(Request(Forbidden("This room does not support knocking.")));
|
||||
}
|
||||
|
||||
let content = RoomMemberEventContent {
|
||||
displayname: services.users.displayname(sender_user).await.ok(),
|
||||
avatar_url: services.users.avatar_url(sender_user).await.ok(),
|
||||
blurhash: services.users.blurhash(sender_user).await.ok(),
|
||||
reason: reason.clone(),
|
||||
..RoomMemberEventContent::new(MembershipState::Knock)
|
||||
};
|
||||
|
||||
// Try normal knock first
|
||||
let Err(error) = services
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PduBuilder::state(sender_user.to_string(), &content),
|
||||
sender_user,
|
||||
room_id,
|
||||
&state_lock,
|
||||
)
|
||||
.await
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if servers.is_empty() || (servers.len() == 1 && services.globals.server_is_ours(&servers[0]))
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
warn!("We couldn't do the knock locally, maybe federation can help to satisfy the knock");
|
||||
|
||||
let (make_knock_response, remote_server) =
|
||||
make_knock_request(services, sender_user, room_id, servers).await?;
|
||||
|
||||
info!("make_knock finished");
|
||||
|
||||
let room_version_id = make_knock_response.room_version;
|
||||
|
||||
if !services
|
||||
.server
|
||||
.supported_room_version(&room_version_id)
|
||||
{
|
||||
return Err!(BadServerResponse(
|
||||
"Remote room version {room_version_id} is not supported by tuwunel"
|
||||
));
|
||||
}
|
||||
|
||||
let mut knock_event_stub = serde_json::from_str::<CanonicalJsonObject>(
|
||||
make_knock_response.event.get(),
|
||||
)
|
||||
.map_err(|e| {
|
||||
err!(BadServerResponse("Invalid make_knock event json received from server: {e:?}"))
|
||||
})?;
|
||||
|
||||
knock_event_stub.insert(
|
||||
"origin".into(),
|
||||
CanonicalJsonValue::String(services.globals.server_name().as_str().to_owned()),
|
||||
);
|
||||
knock_event_stub.insert(
|
||||
"origin_server_ts".into(),
|
||||
CanonicalJsonValue::Integer(
|
||||
utils::millis_since_unix_epoch()
|
||||
.try_into()
|
||||
.expect("Timestamp is valid js_int value"),
|
||||
),
|
||||
);
|
||||
knock_event_stub.insert(
|
||||
"content".into(),
|
||||
to_canonical_value(RoomMemberEventContent {
|
||||
displayname: services.users.displayname(sender_user).await.ok(),
|
||||
avatar_url: services.users.avatar_url(sender_user).await.ok(),
|
||||
blurhash: services.users.blurhash(sender_user).await.ok(),
|
||||
reason,
|
||||
..RoomMemberEventContent::new(MembershipState::Knock)
|
||||
})
|
||||
.expect("event is valid, we just created it"),
|
||||
);
|
||||
|
||||
// In order to create a compatible ref hash (EventID) the `hashes` field needs
|
||||
// to be present
|
||||
services
|
||||
.server_keys
|
||||
.hash_and_sign_event(&mut knock_event_stub, &room_version_id)?;
|
||||
|
||||
// Generate event id
|
||||
let event_id = gen_event_id(&knock_event_stub, &room_version_id)?;
|
||||
|
||||
// Add event_id
|
||||
knock_event_stub
|
||||
.insert("event_id".into(), CanonicalJsonValue::String(event_id.clone().into()));
|
||||
|
||||
// It has enough fields to be called a proper event now
|
||||
let knock_event = knock_event_stub;
|
||||
|
||||
info!("Asking {remote_server} for send_knock in room {room_id}");
|
||||
let send_knock_request = federation::membership::create_knock_event::v1::Request {
|
||||
room_id: room_id.to_owned(),
|
||||
event_id: event_id.clone(),
|
||||
pdu: services
|
||||
.federation
|
||||
.format_pdu_into(knock_event.clone(), Some(&room_version_id))
|
||||
.await,
|
||||
};
|
||||
|
||||
let send_knock_response = services
|
||||
.sending
|
||||
.send_federation_request(&remote_server, send_knock_request)
|
||||
banned_room_check(&services, sender_user, &room_id, Some(&body.room_id_or_alias), client)
|
||||
.await?;
|
||||
|
||||
info!("send_knock finished");
|
||||
let state_lock = services.state.mutex.lock(&room_id).await;
|
||||
|
||||
services
|
||||
.short
|
||||
.get_or_create_shortroomid(room_id)
|
||||
.await;
|
||||
|
||||
info!("Parsing knock event");
|
||||
|
||||
let parsed_knock_pdu = PduEvent::from_id_val(&event_id, knock_event.clone())
|
||||
.map_err(|e| err!(BadServerResponse("Invalid knock event PDU: {e:?}")))?;
|
||||
|
||||
info!("Updating membership locally to knock state with provided stripped state events");
|
||||
let count = services.globals.next_count();
|
||||
services
|
||||
.state_cache
|
||||
.update_membership(
|
||||
room_id,
|
||||
.membership
|
||||
.knock(
|
||||
sender_user,
|
||||
parsed_knock_pdu
|
||||
.get_content::<RoomMemberEventContent>()
|
||||
.expect("we just created this"),
|
||||
sender_user,
|
||||
Some(
|
||||
send_knock_response
|
||||
.knock_room_state
|
||||
.into_iter()
|
||||
.filter_map(|s| extract_variant!(s, RawStrippedState::Stripped))
|
||||
.collect(),
|
||||
),
|
||||
None,
|
||||
false,
|
||||
PduCount::Normal(*count),
|
||||
)
|
||||
.await?;
|
||||
|
||||
info!("Appending room knock event locally");
|
||||
services
|
||||
.timeline
|
||||
.append_pdu(
|
||||
&parsed_knock_pdu,
|
||||
knock_event,
|
||||
once(parsed_knock_pdu.event_id.borrow()),
|
||||
&room_id,
|
||||
Some(&body.room_id_or_alias),
|
||||
body.reason.clone(),
|
||||
&servers,
|
||||
&state_lock,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
drop(state_lock);
|
||||
|
||||
async fn knock_room_helper_remote(
|
||||
services: &Services,
|
||||
sender_user: &UserId,
|
||||
room_id: &RoomId,
|
||||
reason: Option<String>,
|
||||
servers: &[OwnedServerName],
|
||||
state_lock: RoomMutexGuard,
|
||||
) -> Result {
|
||||
info!("Knocking {room_id} over federation.");
|
||||
|
||||
let (make_knock_response, remote_server) =
|
||||
make_knock_request(services, sender_user, room_id, servers).await?;
|
||||
|
||||
info!("make_knock finished");
|
||||
|
||||
let room_version_id = make_knock_response.room_version;
|
||||
|
||||
if !services
|
||||
.server
|
||||
.supported_room_version(&room_version_id)
|
||||
{
|
||||
return Err!(BadServerResponse(
|
||||
"Remote room version {room_version_id} is not supported by tuwunel"
|
||||
));
|
||||
}
|
||||
|
||||
let mut knock_event_stub: CanonicalJsonObject =
|
||||
serde_json::from_str(make_knock_response.event.get()).map_err(|e| {
|
||||
err!(BadServerResponse("Invalid make_knock event json received from server: {e:?}"))
|
||||
})?;
|
||||
|
||||
knock_event_stub.insert(
|
||||
"origin".into(),
|
||||
CanonicalJsonValue::String(services.globals.server_name().as_str().to_owned()),
|
||||
);
|
||||
knock_event_stub.insert(
|
||||
"origin_server_ts".into(),
|
||||
CanonicalJsonValue::Integer(
|
||||
utils::millis_since_unix_epoch()
|
||||
.try_into()
|
||||
.expect("Timestamp is valid js_int value"),
|
||||
),
|
||||
);
|
||||
knock_event_stub.insert(
|
||||
"content".into(),
|
||||
to_canonical_value(RoomMemberEventContent {
|
||||
displayname: services.users.displayname(sender_user).await.ok(),
|
||||
avatar_url: services.users.avatar_url(sender_user).await.ok(),
|
||||
blurhash: services.users.blurhash(sender_user).await.ok(),
|
||||
reason,
|
||||
..RoomMemberEventContent::new(MembershipState::Knock)
|
||||
})
|
||||
.expect("event is valid, we just created it"),
|
||||
);
|
||||
|
||||
// In order to create a compatible ref hash (EventID) the `hashes` field needs
|
||||
// to be present
|
||||
services
|
||||
.server_keys
|
||||
.hash_and_sign_event(&mut knock_event_stub, &room_version_id)?;
|
||||
|
||||
// Generate event id
|
||||
let event_id = gen_event_id(&knock_event_stub, &room_version_id)?;
|
||||
|
||||
// Add event_id
|
||||
knock_event_stub
|
||||
.insert("event_id".into(), CanonicalJsonValue::String(event_id.clone().into()));
|
||||
|
||||
// It has enough fields to be called a proper event now
|
||||
let knock_event = knock_event_stub;
|
||||
|
||||
info!("Asking {remote_server} for send_knock in room {room_id}");
|
||||
let send_knock_request = federation::membership::create_knock_event::v1::Request {
|
||||
room_id: room_id.to_owned(),
|
||||
event_id: event_id.clone(),
|
||||
pdu: services
|
||||
.federation
|
||||
.format_pdu_into(knock_event.clone(), Some(&room_version_id))
|
||||
.await,
|
||||
};
|
||||
|
||||
let send_knock_response = services
|
||||
.sending
|
||||
.send_federation_request(&remote_server, send_knock_request)
|
||||
.await?;
|
||||
|
||||
info!("send_knock finished");
|
||||
|
||||
services
|
||||
.short
|
||||
.get_or_create_shortroomid(room_id)
|
||||
.await;
|
||||
|
||||
info!("Parsing knock event");
|
||||
let parsed_knock_pdu = PduEvent::from_id_val(&event_id, knock_event.clone())
|
||||
.map_err(|e| err!(BadServerResponse("Invalid knock event PDU: {e:?}")))?;
|
||||
|
||||
info!("Going through send_knock response knock state events");
|
||||
let state = send_knock_response
|
||||
.knock_room_state
|
||||
.iter()
|
||||
.map(|event| {
|
||||
serde_json::from_str::<CanonicalJsonObject>(
|
||||
extract_variant!(event.clone(), RawStrippedState::Stripped)
|
||||
.expect("Raw<AnyStrippedStateEvent>")
|
||||
.json()
|
||||
.get(),
|
||||
)
|
||||
})
|
||||
.filter_map(Result::ok);
|
||||
|
||||
let mut state_map: HashMap<u64, OwnedEventId> = HashMap::new();
|
||||
|
||||
for event in state {
|
||||
let Some(state_key) = event.get("state_key") else {
|
||||
debug_warn!("send_knock stripped state event missing state_key: {event:?}");
|
||||
continue;
|
||||
};
|
||||
let Some(event_type) = event.get("type") else {
|
||||
debug_warn!("send_knock stripped state event missing event type: {event:?}");
|
||||
continue;
|
||||
};
|
||||
|
||||
let Ok(state_key) = serde_json::from_value::<String>(state_key.clone().into()) else {
|
||||
debug_warn!("send_knock stripped state event has invalid state_key: {event:?}");
|
||||
continue;
|
||||
};
|
||||
let Ok(event_type) = serde_json::from_value::<StateEventType>(event_type.clone().into())
|
||||
else {
|
||||
debug_warn!("send_knock stripped state event has invalid event type: {event:?}");
|
||||
continue;
|
||||
};
|
||||
|
||||
let event_id = gen_event_id(&event, &room_version_id)?;
|
||||
let shortstatekey = services
|
||||
.short
|
||||
.get_or_create_shortstatekey(&event_type, &state_key)
|
||||
.await;
|
||||
|
||||
services
|
||||
.timeline
|
||||
.add_pdu_outlier(&event_id, &event);
|
||||
|
||||
state_map.insert(shortstatekey, event_id.clone());
|
||||
}
|
||||
|
||||
info!("Compressing state from send_knock");
|
||||
let compressed: CompressedState = services
|
||||
.state_compressor
|
||||
.compress_state_events(
|
||||
state_map
|
||||
.iter()
|
||||
.map(|(ssk, eid)| (ssk, eid.borrow())),
|
||||
)
|
||||
.collect()
|
||||
.await;
|
||||
|
||||
debug!("Saving compressed state");
|
||||
let HashSetCompressStateEvent {
|
||||
shortstatehash: statehash_before_knock,
|
||||
added,
|
||||
removed,
|
||||
} = services
|
||||
.state_compressor
|
||||
.save_state(room_id, Arc::new(compressed))
|
||||
.await?;
|
||||
|
||||
debug!("Forcing state for new room");
|
||||
services
|
||||
.state
|
||||
.force_state(room_id, statehash_before_knock, added, removed, &state_lock)
|
||||
.await?;
|
||||
|
||||
let statehash_after_knock = services
|
||||
.state
|
||||
.append_to_state(&parsed_knock_pdu)
|
||||
.await?;
|
||||
|
||||
info!("Updating membership locally to knock state with provided stripped state events");
|
||||
let count = services.globals.next_count();
|
||||
services
|
||||
.state_cache
|
||||
.update_membership(
|
||||
room_id,
|
||||
sender_user,
|
||||
parsed_knock_pdu
|
||||
.get_content::<RoomMemberEventContent>()
|
||||
.expect("we just created this"),
|
||||
sender_user,
|
||||
Some(
|
||||
send_knock_response
|
||||
.knock_room_state
|
||||
.into_iter()
|
||||
.filter_map(|s| extract_variant!(s, RawStrippedState::Stripped))
|
||||
.collect(),
|
||||
),
|
||||
None,
|
||||
false,
|
||||
PduCount::Normal(*count),
|
||||
)
|
||||
.await?;
|
||||
|
||||
info!("Appending room knock event locally");
|
||||
services
|
||||
.timeline
|
||||
.append_pdu(
|
||||
&parsed_knock_pdu,
|
||||
knock_event,
|
||||
once(parsed_knock_pdu.event_id.borrow()),
|
||||
&state_lock,
|
||||
)
|
||||
.await?;
|
||||
|
||||
info!("Setting final room state for new room");
|
||||
// We set the room state after inserting the pdu, so that we never have a moment
|
||||
// in time where events in the current room state do not exist
|
||||
services
|
||||
.state
|
||||
.set_room_state(room_id, statehash_after_knock, &state_lock);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn make_knock_request(
|
||||
services: &Services,
|
||||
sender_user: &UserId,
|
||||
room_id: &RoomId,
|
||||
servers: &[OwnedServerName],
|
||||
) -> Result<(federation::membership::prepare_knock_event::v1::Response, OwnedServerName)> {
|
||||
let mut make_knock_response_and_server =
|
||||
Err!(BadServerResponse("No server available to assist in knocking."));
|
||||
|
||||
let mut make_knock_counter: usize = 0;
|
||||
|
||||
for remote_server in servers {
|
||||
if services.globals.server_is_ours(remote_server) {
|
||||
continue;
|
||||
}
|
||||
|
||||
info!("Asking {remote_server} for make_knock ({make_knock_counter})");
|
||||
|
||||
let make_knock_response = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
remote_server,
|
||||
federation::membership::prepare_knock_event::v1::Request {
|
||||
room_id: room_id.to_owned(),
|
||||
user_id: sender_user.to_owned(),
|
||||
ver: services
|
||||
.server
|
||||
.supported_room_versions()
|
||||
.collect(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
trace!("make_knock response: {make_knock_response:?}");
|
||||
make_knock_counter = make_knock_counter.saturating_add(1);
|
||||
|
||||
make_knock_response_and_server = make_knock_response.map(|r| (r, remote_server.clone()));
|
||||
|
||||
if make_knock_response_and_server.is_ok() {
|
||||
break;
|
||||
}
|
||||
|
||||
if make_knock_counter > 40 {
|
||||
warn!(
|
||||
"50 servers failed to provide valid make_knock response, assuming no server can \
|
||||
assist in knocking."
|
||||
);
|
||||
make_knock_response_and_server =
|
||||
Err!(BadServerResponse("No server available to assist in knocking."));
|
||||
|
||||
return make_knock_response_and_server;
|
||||
}
|
||||
}
|
||||
|
||||
make_knock_response_and_server
|
||||
Ok(knock_room::v3::Response::new(room_id.clone()))
|
||||
}
|
||||
@@ -8,15 +8,12 @@ mod leave;
|
||||
mod members;
|
||||
mod unban;
|
||||
|
||||
use std::{cmp::Ordering, net::IpAddr};
|
||||
use std::net::IpAddr;
|
||||
|
||||
use axum::extract::State;
|
||||
use futures::{FutureExt, StreamExt};
|
||||
use ruma::{
|
||||
OwnedRoomId, OwnedServerName, RoomId, RoomOrAliasId, ServerName, UserId,
|
||||
api::client::membership::joined_rooms,
|
||||
};
|
||||
use tuwunel_core::{Err, Result, result::LogErr, utils::shuffle, warn};
|
||||
use ruma::{RoomId, RoomOrAliasId, UserId, api::client::membership::joined_rooms};
|
||||
use tuwunel_core::{Err, Result, result::LogErr, warn};
|
||||
use tuwunel_service::Services;
|
||||
|
||||
pub(crate) use self::{
|
||||
@@ -58,57 +55,42 @@ pub(crate) async fn joined_rooms_route(
|
||||
pub(crate) async fn banned_room_check(
|
||||
services: &Services,
|
||||
user_id: &UserId,
|
||||
room_id: Option<&RoomId>,
|
||||
server_name: Option<&ServerName>,
|
||||
room_id: &RoomId,
|
||||
orig_room_id: Option<&RoomOrAliasId>,
|
||||
client_ip: IpAddr,
|
||||
) -> Result {
|
||||
if services.users.is_admin(user_id).await {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// TODO: weird condition
|
||||
if let Some(room_id) = room_id {
|
||||
if services.metadata.is_banned(room_id).await
|
||||
|| (room_id.server_name().is_some()
|
||||
&& services
|
||||
.config
|
||||
.forbidden_remote_server_names
|
||||
.is_match(
|
||||
room_id
|
||||
.server_name()
|
||||
.expect("legacy room mxid")
|
||||
.host(),
|
||||
)) {
|
||||
warn!(
|
||||
"User {user_id} who is not an admin attempted to send an invite for or \
|
||||
attempted to join a banned room or banned room server name: {room_id}"
|
||||
);
|
||||
// room id is banned ...
|
||||
if services.metadata.is_banned(room_id).await
|
||||
// ... or legacy room id server is banned ...
|
||||
|| room_id.server_name().is_some_and(|server_name| {
|
||||
services
|
||||
.config
|
||||
.forbidden_remote_server_names
|
||||
.is_match(server_name.host())
|
||||
})
|
||||
// ... or alias server is banned
|
||||
|| orig_room_id.is_some_and(|orig_room_id| {
|
||||
orig_room_id.server_name().is_some_and(|orig_server_name|
|
||||
services
|
||||
.config
|
||||
.forbidden_remote_server_names
|
||||
.is_match(orig_server_name.host()))
|
||||
}) {
|
||||
warn!(
|
||||
"User {user_id} who is not an admin attempted to send an invite for or attempted to \
|
||||
join a banned room or banned room server name: {room_id}"
|
||||
);
|
||||
|
||||
maybe_deactivate(services, user_id, client_ip)
|
||||
.await
|
||||
.log_err()
|
||||
.ok();
|
||||
maybe_deactivate(services, user_id, client_ip)
|
||||
.await
|
||||
.log_err()
|
||||
.ok();
|
||||
|
||||
return Err!(Request(Forbidden("This room is banned on this homeserver.")));
|
||||
}
|
||||
} else if let Some(server_name) = server_name {
|
||||
if services
|
||||
.config
|
||||
.forbidden_remote_server_names
|
||||
.is_match(server_name.host())
|
||||
{
|
||||
warn!(
|
||||
"User {user_id} who is not an admin tried joining a room which has the server \
|
||||
name {server_name} that is globally forbidden. Rejecting.",
|
||||
);
|
||||
|
||||
maybe_deactivate(services, user_id, client_ip)
|
||||
.await
|
||||
.log_err()
|
||||
.ok();
|
||||
|
||||
return Err!(Request(Forbidden("This remote server is banned on this homeserver.")));
|
||||
}
|
||||
return Err!(Request(Forbidden("This room is banned on this homeserver.")));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -120,16 +102,15 @@ async fn maybe_deactivate(services: &Services, user_id: &UserId, client_ip: IpAd
|
||||
.config
|
||||
.auto_deactivate_banned_room_attempts
|
||||
{
|
||||
warn!("Automatically deactivating user {user_id} due to attempted banned room join");
|
||||
let notice = format!(
|
||||
"Automatically deactivating user {user_id} due to attempted banned room join from \
|
||||
IP {client_ip}"
|
||||
);
|
||||
|
||||
warn!("{notice}");
|
||||
|
||||
if services.server.config.admin_room_notices {
|
||||
services
|
||||
.admin
|
||||
.send_text(&format!(
|
||||
"Automatically deactivating user {user_id} due to attempted banned room \
|
||||
join from IP {client_ip}"
|
||||
))
|
||||
.await;
|
||||
services.admin.send_text(¬ice).await;
|
||||
}
|
||||
|
||||
services
|
||||
@@ -141,86 +122,3 @@ async fn maybe_deactivate(services: &Services, user_id: &UserId, client_ip: IpAd
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// TODO: should this be in services? banned check would have to resolve again if
|
||||
// room_id is not available at callsite
|
||||
async fn get_join_params(
|
||||
services: &Services,
|
||||
user_id: &UserId,
|
||||
room_id_or_alias: &RoomOrAliasId,
|
||||
via: &[OwnedServerName],
|
||||
) -> Result<(OwnedRoomId, Vec<OwnedServerName>)> {
|
||||
// servers tried first, additional_servers shuffled then tried after
|
||||
let (room_id, mut servers, mut additional_servers) =
|
||||
match OwnedRoomId::try_from(room_id_or_alias.to_owned()) {
|
||||
// if room id, shuffle via + room_id server_name ...
|
||||
| Ok(room_id) => {
|
||||
let mut additional_servers = via.to_vec();
|
||||
|
||||
if let Some(server) = room_id.server_name() {
|
||||
additional_servers.push(server.to_owned());
|
||||
}
|
||||
|
||||
(room_id, Vec::new(), additional_servers)
|
||||
},
|
||||
// ... if room alias, resolve and don't shuffle ...
|
||||
| Err(room_alias) => {
|
||||
let (room_id, servers) = services.alias.resolve_alias(&room_alias).await?;
|
||||
|
||||
(room_id, servers, Vec::new())
|
||||
},
|
||||
};
|
||||
|
||||
// either way, add invited vias
|
||||
additional_servers.extend(
|
||||
services
|
||||
.state_cache
|
||||
.servers_invite_via(&room_id)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>()
|
||||
.await,
|
||||
);
|
||||
|
||||
// either way, add invite senders' servers
|
||||
additional_servers.extend(
|
||||
services
|
||||
.state_cache
|
||||
.invite_state(user_id, &room_id)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|event| event.get_field("sender").ok().flatten())
|
||||
.filter_map(|sender: &str| UserId::parse(sender).ok())
|
||||
.map(|user| user.server_name().to_owned()),
|
||||
);
|
||||
|
||||
// shuffle additionals, append to base servers
|
||||
servers.append(&mut additional_servers);
|
||||
servers.sort_unstable();
|
||||
servers.dedup();
|
||||
shuffle(&mut servers);
|
||||
|
||||
// sort deprioritized servers last
|
||||
servers.sort_by(|a, b| {
|
||||
let a_matches = services
|
||||
.server
|
||||
.config
|
||||
.deprioritize_joins_through_servers
|
||||
.is_match(a.host());
|
||||
let b_matches = services
|
||||
.server
|
||||
.config
|
||||
.deprioritize_joins_through_servers
|
||||
.is_match(b.host());
|
||||
|
||||
if a_matches && !b_matches {
|
||||
Ordering::Greater
|
||||
} else if !a_matches && b_matches {
|
||||
Ordering::Less
|
||||
} else {
|
||||
Ordering::Equal
|
||||
}
|
||||
});
|
||||
|
||||
Ok((room_id, servers))
|
||||
}
|
||||
+17
-12
@@ -1,5 +1,9 @@
|
||||
use axum::extract::State;
|
||||
use futures::{FutureExt, StreamExt, TryFutureExt, future::OptionFuture, pin_mut};
|
||||
use futures::{
|
||||
FutureExt, StreamExt, TryFutureExt,
|
||||
future::{Either, OptionFuture},
|
||||
pin_mut,
|
||||
};
|
||||
use ruma::{
|
||||
RoomId, UserId,
|
||||
api::{
|
||||
@@ -105,17 +109,18 @@ pub(crate) async fn get_message_events_route(
|
||||
}
|
||||
|
||||
let it = match body.dir {
|
||||
| Direction::Forward => services
|
||||
.timeline
|
||||
.pdus(Some(sender_user), room_id, Some(from))
|
||||
.ignore_err()
|
||||
.boxed(),
|
||||
|
||||
| Direction::Backward => services
|
||||
.timeline
|
||||
.pdus_rev(Some(sender_user), room_id, Some(from))
|
||||
.ignore_err()
|
||||
.boxed(),
|
||||
| Direction::Forward => Either::Left(
|
||||
services
|
||||
.timeline
|
||||
.pdus(Some(sender_user), room_id, Some(from))
|
||||
.ignore_err(),
|
||||
),
|
||||
| Direction::Backward => Either::Right(
|
||||
services
|
||||
.timeline
|
||||
.pdus_rev(Some(sender_user), room_id, Some(from))
|
||||
.ignore_err(),
|
||||
),
|
||||
};
|
||||
|
||||
let events: Vec<_> = it
|
||||
|
||||
@@ -88,9 +88,6 @@ pub(super) use user_directory::*;
|
||||
pub(super) use voip::*;
|
||||
pub(super) use well_known::*;
|
||||
|
||||
/// generated device ID length
|
||||
const DEVICE_ID_LENGTH: usize = 10;
|
||||
|
||||
/// generated user access token length
|
||||
const TOKEN_LENGTH: usize = tuwunel_service::users::device::TOKEN_LENGTH;
|
||||
|
||||
|
||||
@@ -68,8 +68,8 @@ pub(crate) async fn get_displayname_route(
|
||||
if !services.globals.user_is_local(&body.user_id) {
|
||||
// Create and update our local copy of the user
|
||||
if let Ok(response) = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
.federation
|
||||
.execute(
|
||||
body.user_id.server_name(),
|
||||
federation::query::get_profile_information::v1::Request {
|
||||
user_id: body.user_id.clone(),
|
||||
@@ -169,8 +169,8 @@ pub(crate) async fn get_avatar_url_route(
|
||||
if !services.globals.user_is_local(&body.user_id) {
|
||||
// Create and update our local copy of the user
|
||||
if let Ok(response) = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
.federation
|
||||
.execute(
|
||||
body.user_id.server_name(),
|
||||
federation::query::get_profile_information::v1::Request {
|
||||
user_id: body.user_id.clone(),
|
||||
@@ -231,8 +231,8 @@ pub(crate) async fn get_profile_route(
|
||||
if !services.globals.user_is_local(&body.user_id) {
|
||||
// Create and update our local copy of the user
|
||||
if let Ok(response) = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
.federation
|
||||
.execute(
|
||||
body.user_id.server_name(),
|
||||
federation::query::get_profile_information::v1::Request {
|
||||
user_id: body.user_id.clone(),
|
||||
|
||||
@@ -589,7 +589,7 @@ pub(crate) async fn set_pushers_route(
|
||||
|
||||
services
|
||||
.pusher
|
||||
.set_pusher(sender_user, body.sender_device(), &body.action)
|
||||
.set_pusher(sender_user, body.sender_device()?, &body.action)
|
||||
.await?;
|
||||
|
||||
Ok(set_pusher::v3::Response::new())
|
||||
|
||||
+52
-240
@@ -2,7 +2,6 @@ use std::fmt::Write;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum_client_ip::InsecureClientIp;
|
||||
use futures::FutureExt;
|
||||
use register::RegistrationKind;
|
||||
use ruma::{
|
||||
UserId,
|
||||
@@ -13,15 +12,11 @@ use ruma::{
|
||||
},
|
||||
uiaa::{AuthFlow, AuthType, UiaaInfo},
|
||||
},
|
||||
events::GlobalAccountDataEventType,
|
||||
push,
|
||||
};
|
||||
use tuwunel_core::{
|
||||
Err, Error, Result, debug_info, debug_warn, error, info, is_equal_to, utils, warn,
|
||||
};
|
||||
use tuwunel_core::{Err, Error, Result, debug_info, debug_warn, info, utils};
|
||||
use tuwunel_service::users::device::generate_refresh_token;
|
||||
|
||||
use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH};
|
||||
use super::SESSION_ID_LENGTH;
|
||||
use crate::Ruma;
|
||||
|
||||
const RANDOM_USER_ID_LENGTH: usize = 10;
|
||||
@@ -48,15 +43,10 @@ pub(crate) async fn get_register_available_route(
|
||||
.appservice_info
|
||||
.as_ref()
|
||||
.is_some_and(|appservice| {
|
||||
appservice.registration.id == "irc"
|
||||
|| appservice
|
||||
.registration
|
||||
.id
|
||||
.contains("matrix-appservice-irc")
|
||||
|| appservice
|
||||
.registration
|
||||
.id
|
||||
.contains("matrix_appservice_irc")
|
||||
let id = &appservice.registration.id;
|
||||
id == "irc"
|
||||
|| id.contains("matrix-appservice-irc")
|
||||
|| id.contains("matrix_appservice_irc")
|
||||
});
|
||||
|
||||
if services
|
||||
@@ -148,71 +138,32 @@ pub(crate) async fn register_route(
|
||||
let is_guest = body.kind == RegistrationKind::Guest;
|
||||
let emergency_mode_enabled = services.config.emergency_password.is_some();
|
||||
|
||||
let user = body.username.as_deref().unwrap_or("");
|
||||
let device_name = body
|
||||
.initial_device_display_name
|
||||
.as_deref()
|
||||
.unwrap_or("");
|
||||
|
||||
if !services.config.allow_registration && body.appservice_info.is_none() {
|
||||
match (body.username.as_ref(), body.initial_device_display_name.as_ref()) {
|
||||
| (Some(username), Some(device_display_name)) => {
|
||||
info!(
|
||||
%is_guest,
|
||||
user = %username,
|
||||
device_name = %device_display_name,
|
||||
"Rejecting registration attempt as registration is disabled"
|
||||
);
|
||||
},
|
||||
| (Some(username), _) => {
|
||||
info!(
|
||||
%is_guest,
|
||||
user = %username,
|
||||
"Rejecting registration attempt as registration is disabled"
|
||||
);
|
||||
},
|
||||
| (_, Some(device_display_name)) => {
|
||||
info!(
|
||||
%is_guest,
|
||||
device_name = %device_display_name,
|
||||
"Rejecting registration attempt as registration is disabled"
|
||||
);
|
||||
},
|
||||
| (None, _) => {
|
||||
info!(
|
||||
%is_guest,
|
||||
"Rejecting registration attempt as registration is disabled"
|
||||
);
|
||||
},
|
||||
}
|
||||
info!(
|
||||
%is_guest,
|
||||
%user,
|
||||
%device_name,
|
||||
"Rejecting registration attempt as registration is disabled"
|
||||
);
|
||||
|
||||
return Err!(Request(Forbidden("Registration has been disabled.")));
|
||||
}
|
||||
|
||||
if is_guest && !services.config.allow_guest_registration {
|
||||
let display_name = body
|
||||
.initial_device_display_name
|
||||
.as_deref()
|
||||
.unwrap_or("");
|
||||
|
||||
debug_warn!(
|
||||
"Guest registration disabled / registration enabled with token configured, \
|
||||
rejecting guest registration attempt, initial device name: \"{display_name}\""
|
||||
%device_name,
|
||||
"Guest registration disabled, rejecting guest registration attempt"
|
||||
);
|
||||
|
||||
return Err!(Request(GuestAccessForbidden("Guest registration is disabled.")));
|
||||
}
|
||||
|
||||
// forbid guests from registering if there is not a real admin user yet. give
|
||||
// generic user error.
|
||||
if is_guest && services.users.count().await < 2 {
|
||||
let display_name = body
|
||||
.initial_device_display_name
|
||||
.as_deref()
|
||||
.unwrap_or("");
|
||||
|
||||
warn!(
|
||||
"Guest account attempted to register before a real admin user has been registered, \
|
||||
rejecting registration. Guest's initial device name: \"{display_name}\""
|
||||
);
|
||||
|
||||
return Err!(Request(Forbidden("Registration is temporarily disabled.")));
|
||||
}
|
||||
|
||||
let user_id = match (body.username.as_ref(), is_guest) {
|
||||
| (Some(username), false) => {
|
||||
// workaround for https://github.com/matrix-org/matrix-appservice-irc/issues/1780 due to inactivity of fixing the issue
|
||||
@@ -313,7 +264,13 @@ pub(crate) async fn register_route(
|
||||
|
||||
// UIAA
|
||||
let mut uiaainfo;
|
||||
let skip_auth = if services.globals.registration_token.is_some() && !is_guest {
|
||||
let skip_auth = if !services
|
||||
.globals
|
||||
.get_registration_tokens()
|
||||
.await
|
||||
.is_empty()
|
||||
&& !is_guest
|
||||
{
|
||||
// Registration token required
|
||||
uiaainfo = UiaaInfo {
|
||||
flows: vec![AuthFlow {
|
||||
@@ -378,45 +335,9 @@ pub(crate) async fn register_route(
|
||||
|
||||
let password = if is_guest { None } else { body.password.as_deref() };
|
||||
|
||||
// Create user
|
||||
services
|
||||
.users
|
||||
.create(&user_id, password, None)
|
||||
.await?;
|
||||
|
||||
// Default to pretty displayname
|
||||
let mut displayname = user_id.localpart().to_owned();
|
||||
|
||||
// If `new_user_displayname_suffix` is set, registration will push whatever
|
||||
// content is set to the user's display name with a space before it
|
||||
if !services
|
||||
.config
|
||||
.new_user_displayname_suffix
|
||||
.is_empty()
|
||||
&& body.appservice_info.is_none()
|
||||
{
|
||||
write!(displayname, " {}", services.server.config.new_user_displayname_suffix)?;
|
||||
}
|
||||
|
||||
services
|
||||
.users
|
||||
.set_displayname(&user_id, Some(displayname.clone()));
|
||||
|
||||
// Initial account data
|
||||
services
|
||||
.account_data
|
||||
.update(
|
||||
None,
|
||||
&user_id,
|
||||
GlobalAccountDataEventType::PushRules
|
||||
.to_string()
|
||||
.into(),
|
||||
&serde_json::to_value(ruma::events::push_rules::PushRulesEvent {
|
||||
content: ruma::events::push_rules::PushRulesEventContent {
|
||||
global: push::Ruleset::server_default(&user_id),
|
||||
},
|
||||
})?,
|
||||
)
|
||||
.full_register(&user_id, password, None, body.appservice_info.as_ref(), is_guest, true)
|
||||
.await?;
|
||||
|
||||
if (!is_guest && body.inhibit_login)
|
||||
@@ -426,169 +347,56 @@ pub(crate) async fn register_route(
|
||||
.is_some_and(|appservice| appservice.registration.device_management)
|
||||
{
|
||||
return Ok(register::v3::Response {
|
||||
access_token: None,
|
||||
user_id,
|
||||
device_id: None,
|
||||
access_token: None,
|
||||
refresh_token: None,
|
||||
expires_in: None,
|
||||
});
|
||||
}
|
||||
|
||||
// Generate new device id if the user didn't specify one
|
||||
let device_id = if is_guest { None } else { body.device_id.clone() }
|
||||
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
|
||||
let device_id = if is_guest { None } else { body.device_id.as_deref() };
|
||||
|
||||
// Generate new token for the device
|
||||
let (access_token, expires_in) = services
|
||||
.users
|
||||
.generate_access_token(body.body.refresh_token);
|
||||
.generate_access_token(body.refresh_token);
|
||||
|
||||
// Generate a new refresh_token if requested by client
|
||||
let refresh_token = expires_in.is_some().then(generate_refresh_token);
|
||||
|
||||
// Create device for this account
|
||||
services
|
||||
let device_id = services
|
||||
.users
|
||||
.create_device(
|
||||
&user_id,
|
||||
&device_id,
|
||||
device_id,
|
||||
(Some(&access_token), expires_in),
|
||||
refresh_token.as_deref(),
|
||||
body.initial_device_display_name.clone(),
|
||||
body.initial_device_display_name.as_deref(),
|
||||
Some(client.to_string()),
|
||||
)
|
||||
.await?;
|
||||
|
||||
debug_info!(%user_id, %device_id, "User account was created");
|
||||
|
||||
let device_display_name = body
|
||||
.initial_device_display_name
|
||||
.as_deref()
|
||||
.unwrap_or("");
|
||||
if body.appservice_info.is_none() && (!is_guest || services.config.log_guest_registrations) {
|
||||
let mut notice = String::from(if is_guest { "New guest user" } else { "New user" });
|
||||
|
||||
// log in conduit admin channel if a non-guest user registered
|
||||
if body.appservice_info.is_none() && !is_guest {
|
||||
if !device_display_name.is_empty() {
|
||||
let notice = format!(
|
||||
"New user \"{user_id}\" registered on this server from IP {client} and device \
|
||||
display name \"{device_display_name}\""
|
||||
);
|
||||
write!(notice, " registered on this server from IP {client}")?;
|
||||
|
||||
info!("{notice}");
|
||||
if services.server.config.admin_room_notices {
|
||||
services.admin.notice(¬ice).await;
|
||||
}
|
||||
} else {
|
||||
let notice = format!("New user \"{user_id}\" registered on this server.");
|
||||
|
||||
info!("{notice}");
|
||||
if services.server.config.admin_room_notices {
|
||||
services.admin.notice(¬ice).await;
|
||||
}
|
||||
if let Some(device_name) = body.initial_device_display_name.as_deref() {
|
||||
write!(notice, " with device name {device_name}")?;
|
||||
}
|
||||
}
|
||||
|
||||
// log in conduit admin channel if a guest registered
|
||||
if body.appservice_info.is_none() && is_guest && services.config.log_guest_registrations {
|
||||
debug_info!("New guest user \"{user_id}\" registered on this server.");
|
||||
|
||||
if !device_display_name.is_empty() {
|
||||
if services.server.config.admin_room_notices {
|
||||
services
|
||||
.admin
|
||||
.notice(&format!(
|
||||
"Guest user \"{user_id}\" with device display name \
|
||||
\"{device_display_name}\" registered on this server from IP {client}"
|
||||
))
|
||||
.await;
|
||||
}
|
||||
if !is_guest {
|
||||
info!("{notice}");
|
||||
} else {
|
||||
#[allow(clippy::collapsible_else_if)]
|
||||
if services.server.config.admin_room_notices {
|
||||
services
|
||||
.admin
|
||||
.notice(&format!(
|
||||
"Guest user \"{user_id}\" with no device display name registered on \
|
||||
this server from IP {client}",
|
||||
))
|
||||
.await;
|
||||
}
|
||||
debug_info!("{notice}");
|
||||
}
|
||||
}
|
||||
|
||||
// If this is the first real user, grant them admin privileges except for guest
|
||||
// users
|
||||
// Note: the server user is generated first
|
||||
if !is_guest
|
||||
&& services.config.grant_admin_to_first_user
|
||||
&& let Ok(admin_room) = services.admin.get_admin_room().await
|
||||
&& services
|
||||
.state_cache
|
||||
.room_joined_count(&admin_room)
|
||||
.await
|
||||
.is_ok_and(is_equal_to!(1))
|
||||
{
|
||||
services
|
||||
.admin
|
||||
.make_user_admin(&user_id)
|
||||
.boxed()
|
||||
.await?;
|
||||
warn!("Granting {user_id} admin privileges as the first user");
|
||||
}
|
||||
|
||||
if body.appservice_info.is_none()
|
||||
&& !services.server.config.auto_join_rooms.is_empty()
|
||||
&& (services.config.allow_guests_auto_join_rooms || !is_guest)
|
||||
{
|
||||
for room in &services.server.config.auto_join_rooms {
|
||||
let Ok(room_id) = services.alias.maybe_resolve(room).await else {
|
||||
error!(
|
||||
"Failed to resolve room alias to room ID when attempting to auto join \
|
||||
{room}, skipping"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
|
||||
if !services
|
||||
.state_cache
|
||||
.server_in_room(services.globals.server_name(), &room_id)
|
||||
.await
|
||||
{
|
||||
warn!(
|
||||
"Skipping room {room} to automatically join as we have never joined before."
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(room_server_name) = room.server_name() {
|
||||
let state_lock = services.state.mutex.lock(&room_id).await;
|
||||
|
||||
match services
|
||||
.membership
|
||||
.join(
|
||||
&user_id,
|
||||
&room_id,
|
||||
Some("Automatically joining this room upon registration".to_owned()),
|
||||
&[services.globals.server_name().to_owned(), room_server_name.to_owned()],
|
||||
&body.appservice_info,
|
||||
&state_lock,
|
||||
)
|
||||
.boxed()
|
||||
.await
|
||||
{
|
||||
| Err(e) => {
|
||||
// don't return this error so we don't fail registrations
|
||||
error!(
|
||||
"Failed to automatically join room {room} for user {user_id}: {e}"
|
||||
);
|
||||
},
|
||||
| _ => {
|
||||
info!("Automatically joined room {room} for user {user_id}");
|
||||
},
|
||||
}
|
||||
|
||||
drop(state_lock);
|
||||
}
|
||||
if services.server.config.admin_room_notices {
|
||||
services.admin.notice(¬ice).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -611,9 +419,13 @@ pub(crate) async fn check_registration_token_validity(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<check_registration_token_validity::v1::Request>,
|
||||
) -> Result<check_registration_token_validity::v1::Response> {
|
||||
let Some(reg_token) = services.globals.registration_token.clone() else {
|
||||
return Err!(Request(Forbidden("Server does not allow token registration")));
|
||||
};
|
||||
let tokens = services.globals.get_registration_tokens().await;
|
||||
|
||||
Ok(check_registration_token_validity::v1::Response { valid: reg_token == body.token })
|
||||
if tokens.is_empty() {
|
||||
return Err!(Request(Forbidden("Server does not allow token registration")));
|
||||
}
|
||||
|
||||
let valid = tokens.contains(&body.token);
|
||||
|
||||
Ok(check_registration_token_validity::v1::Response { valid })
|
||||
}
|
||||
+113
-58
@@ -1,5 +1,11 @@
|
||||
use std::iter::once;
|
||||
|
||||
use axum::extract::State;
|
||||
use futures::StreamExt;
|
||||
use futures::{
|
||||
FutureExt, StreamExt, TryFutureExt,
|
||||
future::try_join3,
|
||||
stream::{select_all, unfold},
|
||||
};
|
||||
use ruma::{
|
||||
EventId, RoomId, UInt, UserId,
|
||||
api::{
|
||||
@@ -12,12 +18,16 @@ use ruma::{
|
||||
events::{TimelineEventType, relation::RelationType},
|
||||
};
|
||||
use tuwunel_core::{
|
||||
Result, at,
|
||||
Err, Error, Result, at, err,
|
||||
matrix::{
|
||||
event::{Event, RelationTypeEqual},
|
||||
pdu::PduCount,
|
||||
pdu::{PduCount, PduId},
|
||||
},
|
||||
utils::{
|
||||
BoolExt,
|
||||
result::FlatOk,
|
||||
stream::{ReadyExt, WidebandExt},
|
||||
},
|
||||
utils::{IterStream, ReadyExt, result::FlatOk, stream::WidebandExt},
|
||||
};
|
||||
use tuwunel_service::Services;
|
||||
|
||||
@@ -99,6 +109,12 @@ pub(crate) async fn get_relating_events_route(
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[tracing::instrument(
|
||||
name = "relations",
|
||||
level = "debug",
|
||||
skip_all,
|
||||
fields(room_id, target, from, to, dir, limit, recurse)
|
||||
)]
|
||||
async fn paginate_relations_with_filter(
|
||||
services: &Services,
|
||||
sender_user: &UserId,
|
||||
@@ -112,76 +128,115 @@ async fn paginate_relations_with_filter(
|
||||
recurse: bool,
|
||||
dir: Direction,
|
||||
) -> Result<get_relating_events::v1::Response> {
|
||||
let start: PduCount = from
|
||||
.map(str::parse)
|
||||
.transpose()?
|
||||
.unwrap_or_else(|| match dir {
|
||||
| Direction::Forward => PduCount::min(),
|
||||
| Direction::Backward => PduCount::max(),
|
||||
});
|
||||
let from: Option<PduCount> = from.map(str::parse).transpose()?;
|
||||
|
||||
let to: Option<PduCount> = to.map(str::parse).flat_ok();
|
||||
|
||||
// Use limit or else 30, with maximum 100
|
||||
// Spec (v1.10) recommends depth of at least 3
|
||||
let max_depth: usize = if recurse { 3 } else { 0 };
|
||||
|
||||
let limit: usize = limit
|
||||
.map(TryInto::try_into)
|
||||
.flat_ok()
|
||||
.unwrap_or(30)
|
||||
.min(100);
|
||||
|
||||
// Spec (v1.10) recommends depth of at least 3
|
||||
let depth: u8 = if recurse { 3 } else { 1 };
|
||||
let target = services
|
||||
.timeline
|
||||
.get_pdu_id(target)
|
||||
.map_ok(PduId::from)
|
||||
.map_ok(Ok::<_, Error>);
|
||||
|
||||
let events: Vec<_> = services
|
||||
.pdu_metadata
|
||||
.get_relations(sender_user, room_id, target, start, limit, depth, dir)
|
||||
.await
|
||||
.into_iter()
|
||||
.filter(|(_, pdu)| {
|
||||
filter_event_type
|
||||
.as_ref()
|
||||
.is_none_or(|kind| kind == pdu.kind())
|
||||
})
|
||||
.filter(|(_, pdu)| {
|
||||
filter_rel_type
|
||||
.as_ref()
|
||||
.is_none_or(|rel_type| rel_type.relation_type_equal(pdu))
|
||||
})
|
||||
.stream()
|
||||
.ready_take_while(|(count, _)| Some(*count) != to)
|
||||
.wide_filter_map(|item| visibility_filter(services, sender_user, item))
|
||||
.take(limit)
|
||||
.collect()
|
||||
.await;
|
||||
let visible = services
|
||||
.state_accessor
|
||||
.user_can_see_state_events(sender_user, room_id)
|
||||
.map(|visible| {
|
||||
visible.ok_or_else(|| err!(Request(Forbidden("You cannot view this room."))))
|
||||
});
|
||||
|
||||
let next_batch = events
|
||||
.last()
|
||||
.map(at!(0))
|
||||
.as_ref()
|
||||
.map(ToString::to_string);
|
||||
let shortroomid = services.short.get_shortroomid(room_id);
|
||||
|
||||
let (shortroomid, target, ()) = try_join3(shortroomid, target, visible).await?;
|
||||
|
||||
let Ok(target) = target else {
|
||||
return Ok(get_relating_events::v1::Response::new(Vec::new()));
|
||||
};
|
||||
|
||||
if shortroomid != target.shortroomid {
|
||||
return Err!(Request(NotFound("Event not found in room.")));
|
||||
}
|
||||
|
||||
if let PduCount::Backfilled(_) = target.count {
|
||||
return Ok(get_relating_events::v1::Response::new(Vec::new()));
|
||||
}
|
||||
|
||||
let fetch = |depth: usize, count: PduCount| {
|
||||
services
|
||||
.pdu_metadata
|
||||
.get_relations(shortroomid, count, from, dir, Some(sender_user))
|
||||
.map(move |(count, pdu)| (depth, count, pdu))
|
||||
.ready_filter(|(_, count, _)| matches!(count, PduCount::Normal(_)))
|
||||
.boxed()
|
||||
};
|
||||
|
||||
let events = unfold(select_all(once(fetch(0, target.count))), async |mut relations| {
|
||||
let (depth, count, pdu) = relations.next().await?;
|
||||
|
||||
if depth < max_depth {
|
||||
relations.push(fetch(depth.saturating_add(1), count));
|
||||
}
|
||||
|
||||
Some(((depth, count, pdu), relations))
|
||||
})
|
||||
.ready_take_while(|&(_, count, _)| Some(count) != to)
|
||||
.ready_filter(|(_, _, pdu)| {
|
||||
filter_event_type
|
||||
.as_ref()
|
||||
.is_none_or(|kind| kind == pdu.kind())
|
||||
})
|
||||
.ready_filter(|(_, _, pdu)| {
|
||||
filter_rel_type
|
||||
.as_ref()
|
||||
.is_none_or(|rel_type| rel_type.relation_type_equal(pdu))
|
||||
})
|
||||
.wide_filter_map(async |(depth, count, pdu)| {
|
||||
services
|
||||
.state_accessor
|
||||
.user_can_see_event(sender_user, pdu.room_id(), pdu.event_id())
|
||||
.await
|
||||
.then_some((depth, count, pdu))
|
||||
})
|
||||
.take(limit)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
|
||||
Ok(get_relating_events::v1::Response {
|
||||
next_batch,
|
||||
prev_batch: from.map(Into::into),
|
||||
recursion_depth: recurse.then_some(depth.into()),
|
||||
recursion_depth: max_depth
|
||||
.gt(&0)
|
||||
.then(|| events.iter().map(at!(0)))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.max()
|
||||
.map(TryInto::try_into)
|
||||
.transpose()?,
|
||||
|
||||
next_batch: events
|
||||
.last()
|
||||
.map(at!(1))
|
||||
.as_ref()
|
||||
.map(ToString::to_string),
|
||||
|
||||
prev_batch: events
|
||||
.first()
|
||||
.map(at!(1))
|
||||
.or(from)
|
||||
.as_ref()
|
||||
.map(ToString::to_string),
|
||||
|
||||
chunk: events
|
||||
.into_iter()
|
||||
.map(at!(1))
|
||||
.map(at!(2))
|
||||
.map(Event::into_format)
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn visibility_filter<Pdu: Event>(
|
||||
services: &Services,
|
||||
sender_user: &UserId,
|
||||
item: (PduCount, Pdu),
|
||||
) -> Option<(PduCount, Pdu)> {
|
||||
let (_, pdu) = &item;
|
||||
|
||||
services
|
||||
.state_accessor
|
||||
.user_can_see_event(sender_user, pdu.room_id(), pdu.event_id())
|
||||
.await
|
||||
.then_some(item)
|
||||
}
|
||||
@@ -55,7 +55,7 @@ pub(crate) async fn get_room_summary(
|
||||
) -> Result<get_summary::v1::Response> {
|
||||
let (room_id, servers) = services
|
||||
.alias
|
||||
.maybe_resolve_with_servers(&body.room_id_or_alias, Some(body.via.clone()))
|
||||
.maybe_resolve_with_servers(&body.room_id_or_alias, Some(&body.via))
|
||||
.await?;
|
||||
|
||||
if services.metadata.is_banned(&room_id).await {
|
||||
@@ -232,8 +232,8 @@ async fn remote_room_summary_hierarchy_response(
|
||||
.iter()
|
||||
.map(|server| {
|
||||
services
|
||||
.sending
|
||||
.send_federation_request(server, request.clone())
|
||||
.federation
|
||||
.execute(server, request.clone())
|
||||
})
|
||||
.collect();
|
||||
|
||||
|
||||
+420
-185
@@ -1,42 +1,63 @@
|
||||
use std::cmp::max;
|
||||
|
||||
use axum::extract::State;
|
||||
use futures::StreamExt;
|
||||
use futures::{FutureExt, StreamExt, TryFutureExt, TryStreamExt};
|
||||
use ruma::{
|
||||
CanonicalJsonObject, RoomId, RoomVersionId,
|
||||
api::client::room::upgrade_room,
|
||||
CanonicalJsonObject, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId, RoomVersionId, UserId,
|
||||
api::client::room::upgrade_room::v3,
|
||||
events::{
|
||||
StateEventType, TimelineEventType,
|
||||
room::{
|
||||
create::PreviousRoom,
|
||||
member::{MembershipState, RoomMemberEventContent},
|
||||
power_levels::RoomPowerLevelsEventContent,
|
||||
tombstone::RoomTombstoneEventContent,
|
||||
},
|
||||
},
|
||||
int,
|
||||
room_version_rules::RoomIdFormatVersion,
|
||||
room_version_rules::{RoomIdFormatVersion, RoomVersionRules},
|
||||
};
|
||||
use serde_json::{
|
||||
Value as JsonValue, json,
|
||||
value::{to_raw_value, to_value},
|
||||
};
|
||||
use serde_json::{json, value::to_raw_value};
|
||||
use tuwunel_core::{
|
||||
Err, Result, err,
|
||||
Err, Result, debug_info, err, error, implement, info, is_equal_to, is_less_than,
|
||||
matrix::{Event, StateKey, pdu::PduBuilder, room_version},
|
||||
utils::{
|
||||
future::TryExtExt,
|
||||
stream::{IterStream, ReadyExt, WidebandExt},
|
||||
},
|
||||
};
|
||||
use tuwunel_service::{Services, rooms::timeline::RoomMutexGuard};
|
||||
|
||||
use crate::Ruma;
|
||||
|
||||
/// Recommended transferable state events list from the spec
|
||||
const TRANSFERABLE_STATE_EVENTS: &[StateEventType; 9] = &[
|
||||
StateEventType::RoomAvatar,
|
||||
//TODO: Upgrade Ruma
|
||||
const RECOMMENDED_TRANSFERABLE_STATE_EVENT_TYPES: &[StateEventType; 9] = &[
|
||||
StateEventType::RoomServerAcl,
|
||||
StateEventType::RoomEncryption,
|
||||
StateEventType::RoomName,
|
||||
StateEventType::RoomAvatar,
|
||||
StateEventType::RoomTopic,
|
||||
StateEventType::RoomGuestAccess,
|
||||
StateEventType::RoomHistoryVisibility,
|
||||
StateEventType::RoomJoinRules,
|
||||
StateEventType::RoomName,
|
||||
StateEventType::RoomPowerLevels,
|
||||
StateEventType::RoomServerAcl,
|
||||
StateEventType::RoomTopic,
|
||||
];
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RoomUpgradeContext<'a> {
|
||||
services: &'a Services,
|
||||
sender_user: &'a UserId,
|
||||
old_room_id: &'a RoomId,
|
||||
old_state_lock: &'a RoomMutexGuard,
|
||||
new_room_id: &'a RoomId,
|
||||
new_state_lock: &'a RoomMutexGuard,
|
||||
new_version_rules: &'a RoomVersionRules,
|
||||
additional_creators: &'a [OwnedUserId],
|
||||
}
|
||||
|
||||
/// # `POST /_matrix/client/r0/rooms/{roomId}/upgrade`
|
||||
///
|
||||
/// Upgrades the room.
|
||||
@@ -47,117 +68,227 @@ const TRANSFERABLE_STATE_EVENTS: &[StateEventType; 9] = &[
|
||||
/// - Transfers some state events
|
||||
/// - Moves local aliases
|
||||
/// - Modifies old room power levels to prevent users from speaking
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub(crate) async fn upgrade_room_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<upgrade_room::v3::Request>,
|
||||
) -> Result<upgrade_room::v3::Response> {
|
||||
debug_assert!(
|
||||
TRANSFERABLE_STATE_EVENTS.is_sorted(),
|
||||
"TRANSFERABLE_STATE_EVENTS is not sorted"
|
||||
);
|
||||
|
||||
body: Ruma<v3::Request>,
|
||||
) -> Result<v3::Response> {
|
||||
let sender_user = body.sender_user();
|
||||
let new_version = &body.new_version;
|
||||
let version_rules = room_version::rules(new_version)?;
|
||||
|
||||
if !services
|
||||
.server
|
||||
.supported_room_version(&body.new_version)
|
||||
.supported_room_version(new_version)
|
||||
{
|
||||
return Err!(Request(UnsupportedRoomVersion(
|
||||
"This server does not support that room version.",
|
||||
)));
|
||||
}
|
||||
|
||||
if matches!(body.new_version, RoomVersionId::V12) {
|
||||
return Err!(Request(UnsupportedRoomVersion(
|
||||
"Upgrading to version 12 is still under development.",
|
||||
)));
|
||||
let old_room_id = &body.room_id;
|
||||
let old_state_lock = services.state.mutex.lock(old_room_id).await;
|
||||
|
||||
if !services
|
||||
.state_accessor
|
||||
.user_can_tombstone(old_room_id, sender_user, &old_state_lock)
|
||||
.await
|
||||
{
|
||||
return Err!(Request(Forbidden("You are not permitted to upgrade the room.")));
|
||||
}
|
||||
|
||||
let room_version_rules = room_version::rules(&body.new_version)?;
|
||||
let room_id_format = &room_version_rules.room_id_format;
|
||||
assert!(*room_id_format == RoomIdFormatVersion::V1, "TODO");
|
||||
|
||||
// Create a replacement room
|
||||
let replacement_room = RoomId::new_v1(services.globals.server_name());
|
||||
|
||||
let _short_id = services
|
||||
.short
|
||||
.get_or_create_shortroomid(&replacement_room)
|
||||
.await;
|
||||
|
||||
let state_lock = services.state.mutex.lock(&body.room_id).await;
|
||||
|
||||
// Send a m.room.tombstone event to the old room to indicate that it is not
|
||||
// intended to be used any further Fail if the sender does not have the required
|
||||
// permissions
|
||||
let tombstone_event_id = services
|
||||
let latest_event = services
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PduBuilder::state(StateKey::new(), &RoomTombstoneEventContent {
|
||||
body: "This room has been replaced".to_owned(),
|
||||
replacement_room: replacement_room.clone(),
|
||||
}),
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&state_lock,
|
||||
)
|
||||
.await?;
|
||||
.latest_pdu_in_room(old_room_id)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
// Change lock to replacement room
|
||||
drop(state_lock);
|
||||
let state_lock = services.state.mutex.lock(&replacement_room).await;
|
||||
let predecessor = PreviousRoom {
|
||||
room_id: old_room_id.to_owned(),
|
||||
event_id: latest_event
|
||||
.as_ref()
|
||||
.map(Event::event_id)
|
||||
.map(ToOwned::to_owned),
|
||||
};
|
||||
|
||||
debug_info!(
|
||||
%sender_user,
|
||||
%old_room_id,
|
||||
last_event = ?predecessor.event_id,
|
||||
?new_version,
|
||||
"Attempting upgrade of room..."
|
||||
);
|
||||
|
||||
let id_format = version_rules.room_id_format;
|
||||
let (replacement_room, state_lock) = match id_format {
|
||||
| RoomIdFormatVersion::V2 =>
|
||||
upgrade_room_create(
|
||||
&services,
|
||||
sender_user,
|
||||
old_room_id,
|
||||
new_version,
|
||||
&version_rules,
|
||||
predecessor,
|
||||
body.additional_creators.clone(),
|
||||
)
|
||||
.await,
|
||||
|
||||
| RoomIdFormatVersion::V1 =>
|
||||
upgrade_room_create_legacy(
|
||||
&services,
|
||||
sender_user,
|
||||
old_room_id,
|
||||
new_version,
|
||||
&version_rules,
|
||||
predecessor,
|
||||
)
|
||||
.await,
|
||||
}
|
||||
.inspect_err(|e| error!(?body, "Upgrade m.room.create event failed: {e}"))?;
|
||||
|
||||
let context = RoomUpgradeContext {
|
||||
services: &services,
|
||||
sender_user,
|
||||
old_room_id: &body.room_id,
|
||||
old_state_lock: &old_state_lock,
|
||||
new_room_id: &replacement_room,
|
||||
new_state_lock: &state_lock,
|
||||
new_version_rules: &version_rules,
|
||||
additional_creators: &body.additional_creators,
|
||||
};
|
||||
|
||||
if let Err(e) = context.transfer_room().await {
|
||||
error!(?e, ?context, "Room upgrade failed. Cleaning up incomplete room...");
|
||||
|
||||
if let Err(e) = services
|
||||
.delete
|
||||
.delete_room(&replacement_room, false, state_lock)
|
||||
.await
|
||||
{
|
||||
error!("Additional errors while deleting incomplete room: {e}");
|
||||
}
|
||||
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
info!(
|
||||
old_room_id = %context.old_room_id,
|
||||
new_room_id = %context.new_room_id,
|
||||
upgraded_by = %sender_user,
|
||||
"Room upgraded",
|
||||
);
|
||||
|
||||
Ok(v3::Response { replacement_room })
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "info")]
|
||||
async fn upgrade_room_create(
|
||||
services: &Services,
|
||||
sender_user: &UserId,
|
||||
old_room_id: &RoomId,
|
||||
new_version: &RoomVersionId,
|
||||
version_rules: &RoomVersionRules,
|
||||
predecessor: PreviousRoom,
|
||||
mut additional_creators: Vec<OwnedUserId>,
|
||||
) -> Result<(OwnedRoomId, RoomMutexGuard)> {
|
||||
// Get the old room creation event
|
||||
let mut create_event_content: CanonicalJsonObject = services
|
||||
let mut content: CanonicalJsonObject = services
|
||||
.state_accessor
|
||||
.room_state_get_content(&body.room_id, &StateEventType::RoomCreate, "")
|
||||
.room_state_get_content(old_room_id, &StateEventType::RoomCreate, "")
|
||||
.await
|
||||
.map_err(|_| err!(Database("Found room without m.room.create event.")))?;
|
||||
|
||||
// Use the m.room.tombstone event as the predecessor
|
||||
let predecessor = Some(ruma::events::room::create::PreviousRoom::new(
|
||||
body.room_id.clone(),
|
||||
Some(tombstone_event_id),
|
||||
));
|
||||
content.remove("creator");
|
||||
content.insert("predecessor".into(), json!(predecessor).try_into()?);
|
||||
content.insert("room_version".into(), json!(new_version).try_into()?);
|
||||
|
||||
// Send a m.room.create event containing a predecessor field and the applicable
|
||||
// room_version
|
||||
if version_rules
|
||||
.authorization
|
||||
.additional_room_creators
|
||||
{
|
||||
use RoomVersionId::*;
|
||||
match body.new_version {
|
||||
| V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 => {
|
||||
create_event_content.insert(
|
||||
"creator".into(),
|
||||
json!(&sender_user).try_into().map_err(|e| {
|
||||
err!(Request(BadJson(error!("Error forming creation event: {e}"))))
|
||||
})?,
|
||||
);
|
||||
},
|
||||
| _ => {
|
||||
// "creator" key no longer exists in V11+ rooms
|
||||
create_event_content.remove("creator");
|
||||
},
|
||||
additional_creators.sort();
|
||||
additional_creators.dedup();
|
||||
content.remove("additional_creators");
|
||||
if !additional_creators.is_empty() {
|
||||
content.insert("additional_creators".into(), json!(additional_creators).try_into()?);
|
||||
}
|
||||
}
|
||||
|
||||
create_event_content.insert(
|
||||
"room_version".into(),
|
||||
json!(&body.new_version)
|
||||
.try_into()
|
||||
.map_err(|_| err!(Request(BadJson("Error forming creation event"))))?,
|
||||
);
|
||||
create_event_content.insert(
|
||||
"predecessor".into(),
|
||||
json!(predecessor)
|
||||
.try_into()
|
||||
.map_err(|_| err!(Request(BadJson("Error forming creation event"))))?,
|
||||
);
|
||||
// Validate creation event content
|
||||
let raw_content = to_raw_value(&content)?;
|
||||
if let Err(e) = serde_json::from_str::<CanonicalJsonObject>(raw_content.get()) {
|
||||
return Err!(Request(BadJson("Error forming creation event: {e}")));
|
||||
}
|
||||
|
||||
let room_id = ruma::room_id!("!thiswillbereplaced").to_owned();
|
||||
let state_lock = services.state.mutex.lock(&room_id).await;
|
||||
let create_event_id = services
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PduBuilder {
|
||||
event_type: TimelineEventType::RoomCreate,
|
||||
content: to_raw_value(&content)?,
|
||||
state_key: Some(StateKey::new()),
|
||||
..Default::default()
|
||||
},
|
||||
sender_user,
|
||||
&room_id,
|
||||
&state_lock,
|
||||
)
|
||||
.boxed()
|
||||
.await?;
|
||||
|
||||
drop(state_lock);
|
||||
|
||||
// The real room_id is now the event_id.
|
||||
let room_id = OwnedRoomId::from_parts('!', create_event_id.localpart(), None)?;
|
||||
let state_lock = services.state.mutex.lock(&room_id).await;
|
||||
|
||||
Ok((room_id, state_lock))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "info")]
|
||||
async fn upgrade_room_create_legacy(
|
||||
services: &Services,
|
||||
sender_user: &UserId,
|
||||
old_room_id: &RoomId,
|
||||
new_version: &RoomVersionId,
|
||||
version_rules: &RoomVersionRules,
|
||||
predecessor: PreviousRoom,
|
||||
) -> Result<(OwnedRoomId, RoomMutexGuard)> {
|
||||
// Create a replacement room
|
||||
let new_room_id = RoomId::new_v1(services.globals.server_name());
|
||||
let state_lock = services.state.mutex.lock(&new_room_id).await;
|
||||
let _short_id = services
|
||||
.short
|
||||
.get_or_create_shortroomid(&new_room_id)
|
||||
.await;
|
||||
|
||||
// Get the old room creation event
|
||||
let mut content: CanonicalJsonObject = services
|
||||
.state_accessor
|
||||
.room_state_get_content(old_room_id, &StateEventType::RoomCreate, "")
|
||||
.await
|
||||
.map_err(|_| err!(Database("Found room without m.room.create event.")))?;
|
||||
|
||||
// Send a m.room.create event containing a predecessor field and the applicable
|
||||
// room_version. "creator" key no longer exists in V11+ rooms.
|
||||
{
|
||||
use RoomVersionId::*;
|
||||
match new_version {
|
||||
| V1 | V2 | V3 | V4 | V5 | V6 | V7 | V8 | V9 | V10 =>
|
||||
content.insert("creator".into(), json!(&sender_user).try_into()?),
|
||||
| _ => content.remove("creator"),
|
||||
}
|
||||
};
|
||||
|
||||
content.insert("predecessor".into(), json!(predecessor).try_into()?);
|
||||
content.insert("room_version".into(), json!(new_version).try_into()?);
|
||||
|
||||
// Validate creation event content
|
||||
if serde_json::from_str::<CanonicalJsonObject>(to_raw_value(&create_event_content)?.get())
|
||||
.is_err()
|
||||
{
|
||||
return Err!(Request(BadJson("Error forming creation event")));
|
||||
let raw_content = to_raw_value(&content)?;
|
||||
if let Err(e) = serde_json::from_str::<CanonicalJsonObject>(raw_content.get()) {
|
||||
return Err!(Request(BadJson("Error forming creation event: {e}")));
|
||||
}
|
||||
|
||||
services
|
||||
@@ -165,125 +296,229 @@ pub(crate) async fn upgrade_room_route(
|
||||
.build_and_append_pdu(
|
||||
PduBuilder {
|
||||
event_type: TimelineEventType::RoomCreate,
|
||||
content: to_raw_value(&create_event_content)?,
|
||||
unsigned: None,
|
||||
content: to_raw_value(&content)?,
|
||||
state_key: Some(StateKey::new()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
..Default::default()
|
||||
},
|
||||
sender_user,
|
||||
&replacement_room,
|
||||
&new_room_id,
|
||||
&state_lock,
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Join the new room
|
||||
services
|
||||
Ok((new_room_id, state_lock))
|
||||
}
|
||||
|
||||
#[implement(RoomUpgradeContext, params = "<'_>")]
|
||||
#[tracing::instrument(level = "debug")]
|
||||
async fn transfer_room(&self) -> Result {
|
||||
self.move_joined_member().await?;
|
||||
|
||||
self.move_state_events().await?;
|
||||
|
||||
self.move_local_aliases().await?;
|
||||
|
||||
self.tombstone_old_room().await?;
|
||||
|
||||
// After commitment to the tombstone above no more errors can propagate.
|
||||
self.lockdown_old_room()
|
||||
.await
|
||||
.inspect_err(|e| error!(?self, "Failed to lockdown old room: {e}"))
|
||||
.ok();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Join the new room
|
||||
#[implement(RoomUpgradeContext, params = "<'_>")]
|
||||
#[tracing::instrument(level = "debug")]
|
||||
async fn move_joined_member(&self) -> Result<OwnedEventId> {
|
||||
let old_content: RoomMemberEventContent = self
|
||||
.services
|
||||
.state_accessor
|
||||
.room_state_get_content(
|
||||
self.old_room_id,
|
||||
&StateEventType::RoomMember,
|
||||
self.sender_user.as_str(),
|
||||
)
|
||||
.inspect_err(|e| error!(?self, "Missing room member event: {e}"))
|
||||
.await?;
|
||||
|
||||
self.services
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PduBuilder {
|
||||
event_type: TimelineEventType::RoomMember,
|
||||
content: to_raw_value(&RoomMemberEventContent {
|
||||
membership: MembershipState::Join,
|
||||
displayname: services.users.displayname(sender_user).await.ok(),
|
||||
avatar_url: services.users.avatar_url(sender_user).await.ok(),
|
||||
is_direct: None,
|
||||
third_party_invite: None,
|
||||
blurhash: services.users.blurhash(sender_user).await.ok(),
|
||||
reason: None,
|
||||
join_authorized_via_users_server: None,
|
||||
})?,
|
||||
unsigned: None,
|
||||
state_key: Some(sender_user.as_str().into()),
|
||||
redacts: None,
|
||||
timestamp: None,
|
||||
},
|
||||
sender_user,
|
||||
&replacement_room,
|
||||
&state_lock,
|
||||
PduBuilder::state(self.sender_user.as_str(), &RoomMemberEventContent {
|
||||
membership: MembershipState::Join,
|
||||
..old_content
|
||||
}),
|
||||
self.sender_user,
|
||||
self.new_room_id,
|
||||
self.new_state_lock,
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
}
|
||||
|
||||
// Replicate transferable state events to the new room
|
||||
for event_type in TRANSFERABLE_STATE_EVENTS {
|
||||
let event_content = match services
|
||||
.state_accessor
|
||||
.room_state_get(&body.room_id, event_type, "")
|
||||
.await
|
||||
// Replicate transferable state events to the new room
|
||||
#[implement(RoomUpgradeContext, params = "<'_>")]
|
||||
#[tracing::instrument(level = "debug")]
|
||||
async fn move_state_events(&self) -> Result {
|
||||
RECOMMENDED_TRANSFERABLE_STATE_EVENT_TYPES
|
||||
.iter()
|
||||
.rev()
|
||||
.stream()
|
||||
.wide_filter_map(|event_type| {
|
||||
self.services
|
||||
.state_accessor
|
||||
.room_state_get(self.old_room_id, event_type, "")
|
||||
.ok()
|
||||
})
|
||||
.map(Ok)
|
||||
.try_for_each(async |event| {
|
||||
self.services
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
self.rebuild_state_event(&event)?,
|
||||
self.sender_user,
|
||||
self.new_room_id,
|
||||
self.new_state_lock,
|
||||
)
|
||||
.inspect_err(|e| {
|
||||
error!(?event, ?self, "Failed to transfer state on upgrade: {e}");
|
||||
})
|
||||
.map_ok(|_| ())
|
||||
.await
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[implement(RoomUpgradeContext, params = "<'_>")]
|
||||
#[tracing::instrument(level = "debug")]
|
||||
fn rebuild_state_event<Pdu: Event>(&self, event: &Pdu) -> Result<PduBuilder> {
|
||||
let content = match event.kind() {
|
||||
| TimelineEventType::RoomPowerLevels
|
||||
if self
|
||||
.new_version_rules
|
||||
.authorization
|
||||
.explicitly_privilege_room_creators =>
|
||||
{
|
||||
| Ok(v) => v.content().to_owned(),
|
||||
| Err(_) => continue, // Skipping missing events.
|
||||
};
|
||||
let mut content = event.get_content_as_value();
|
||||
|
||||
services
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PduBuilder {
|
||||
event_type: event_type.to_string().into(),
|
||||
content: event_content,
|
||||
state_key: Some(StateKey::new()),
|
||||
..Default::default()
|
||||
},
|
||||
sender_user,
|
||||
&replacement_room,
|
||||
&state_lock,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
if let Some(users) = content
|
||||
.get_mut("users")
|
||||
.and_then(JsonValue::as_object_mut)
|
||||
{
|
||||
users.retain(|user_id, _pl| {
|
||||
!self
|
||||
.additional_creators
|
||||
.iter()
|
||||
.map(AsRef::as_ref)
|
||||
.map(UserId::as_str)
|
||||
.any(is_equal_to!(user_id.as_str()))
|
||||
&& self.sender_user.as_str() != user_id.as_str()
|
||||
});
|
||||
}
|
||||
|
||||
// Moves any local aliases to the new room
|
||||
let mut local_aliases = services
|
||||
if content["events"]["m.room.tombstone"]
|
||||
.as_i64()
|
||||
.is_none_or(is_less_than!(150))
|
||||
{
|
||||
content["events"]["m.room.tombstone"] = to_value(150)?;
|
||||
}
|
||||
|
||||
to_raw_value(&content)?
|
||||
},
|
||||
| _ => to_raw_value(event.content())?,
|
||||
};
|
||||
|
||||
Ok(PduBuilder {
|
||||
content,
|
||||
event_type: event.kind().clone(),
|
||||
state_key: event.state_key().map(Into::into),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
// Moves any local aliases to the new room
|
||||
#[implement(RoomUpgradeContext, params = "<'_>")]
|
||||
#[tracing::instrument(level = "debug")]
|
||||
async fn move_local_aliases(&self) -> Result {
|
||||
self.services
|
||||
.alias
|
||||
.local_aliases_for_room(&body.room_id)
|
||||
.boxed();
|
||||
.local_aliases_for_room(self.old_room_id)
|
||||
.filter_map(|alias| {
|
||||
self.services
|
||||
.alias
|
||||
.remove_alias(alias, self.sender_user)
|
||||
.inspect_err(move |e| error!(?alias, ?self, "Failed to remove alias: {e}"))
|
||||
.map_ok(move |()| alias)
|
||||
.ok()
|
||||
})
|
||||
.ready_for_each(|alias| {
|
||||
self.services
|
||||
.alias
|
||||
.set_alias(alias, self.new_room_id, self.sender_user)
|
||||
.inspect_err(|e| error!(?self, "Failed to add alias: {e}"))
|
||||
.ok();
|
||||
})
|
||||
.map(Ok)
|
||||
.await
|
||||
}
|
||||
|
||||
while let Some(alias) = local_aliases.next().await {
|
||||
services
|
||||
.alias
|
||||
.remove_alias(alias, sender_user)
|
||||
.await?;
|
||||
|
||||
services
|
||||
.alias
|
||||
.set_alias(alias, &replacement_room, sender_user)?;
|
||||
}
|
||||
// Send a m.room.tombstone event to the old room to indicate that it is not
|
||||
// intended to be used any further Fail if the sender does not have the required
|
||||
// permissions.
|
||||
#[implement(RoomUpgradeContext, params = "<'_>")]
|
||||
#[tracing::instrument(level = "debug")]
|
||||
async fn tombstone_old_room(&self) -> Result<OwnedEventId> {
|
||||
self.services
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PduBuilder::state(StateKey::new(), &RoomTombstoneEventContent {
|
||||
body: "This room has been upgraded.".to_owned(),
|
||||
replacement_room: self.new_room_id.to_owned(),
|
||||
}),
|
||||
self.sender_user,
|
||||
self.old_room_id,
|
||||
self.old_state_lock,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
// Modify the power levels in the old room to prevent sending of events and
|
||||
// inviting new users. Though a Result is returned, the callsite above treats it
|
||||
// as infallible because the tombstone represents the commitment.
|
||||
#[implement(RoomUpgradeContext, params = "<'_>")]
|
||||
#[tracing::instrument(level = "debug")]
|
||||
async fn lockdown_old_room(&self) -> Result<OwnedEventId> {
|
||||
// Get the old room power levels
|
||||
let power_levels_event_content: RoomPowerLevelsEventContent = services
|
||||
let old_content: RoomPowerLevelsEventContent = self
|
||||
.services
|
||||
.state_accessor
|
||||
.room_state_get_content(&body.room_id, &StateEventType::RoomPowerLevels, "")
|
||||
.room_state_get_content(self.old_room_id, &StateEventType::RoomPowerLevels, "")
|
||||
.await
|
||||
.map_err(|_| err!(Database("Found room without m.room.power_levels event.")))?;
|
||||
|
||||
// Setting events_default and invite to the greater of 50 and users_default + 1
|
||||
let new_level = max(
|
||||
int!(50),
|
||||
power_levels_event_content
|
||||
.users_default
|
||||
.checked_add(int!(1))
|
||||
.ok_or_else(|| {
|
||||
err!(Request(BadJson("users_default power levels event content is not valid")))
|
||||
})?,
|
||||
);
|
||||
let old_users_default = old_content
|
||||
.users_default
|
||||
.checked_add(int!(1))
|
||||
.ok_or_else(|| {
|
||||
err!(Request(BadJson("users_default power levels event content is not valid")))
|
||||
})?;
|
||||
|
||||
// Modify the power levels in the old room to prevent sending of events and
|
||||
// inviting new users
|
||||
services
|
||||
// Setting events_default and invite to the greater of 50 and users_default + 1
|
||||
let new_level = max(int!(50), old_users_default);
|
||||
|
||||
self.services
|
||||
.timeline
|
||||
.build_and_append_pdu(
|
||||
PduBuilder::state(StateKey::new(), &RoomPowerLevelsEventContent {
|
||||
events_default: new_level,
|
||||
invite: new_level,
|
||||
..power_levels_event_content
|
||||
..old_content
|
||||
}),
|
||||
sender_user,
|
||||
&body.room_id,
|
||||
&state_lock,
|
||||
self.sender_user,
|
||||
self.old_room_id,
|
||||
self.old_state_lock,
|
||||
)
|
||||
.await?;
|
||||
|
||||
drop(state_lock);
|
||||
|
||||
// Return the replacement room id
|
||||
Ok(upgrade_room::v3::Response { replacement_room })
|
||||
.await
|
||||
}
|
||||
@@ -51,7 +51,7 @@ pub(super) async fn ldap_login(
|
||||
if !services.users.exists(lowercased_user_id).await {
|
||||
services
|
||||
.users
|
||||
.create(lowercased_user_id, Some("*"), Some("ldap"))
|
||||
.full_register(lowercased_user_id, Some("*"), Some("ldap"), None, false, false)
|
||||
.await?;
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ pub(crate) async fn logout_route(
|
||||
) -> Result<logout::v3::Response> {
|
||||
services
|
||||
.users
|
||||
.remove_device(body.sender_user(), body.sender_device())
|
||||
.remove_device(body.sender_user(), body.sender_device()?)
|
||||
.await;
|
||||
|
||||
Ok(logout::v3::Response::new())
|
||||
|
||||
@@ -21,7 +21,7 @@ use ruma::api::client::session::{
|
||||
v3::{DiscoveryInfo, HomeserverInfo, LoginInfo},
|
||||
},
|
||||
};
|
||||
use tuwunel_core::{Err, Result, info, utils, utils::stream::ReadyExt};
|
||||
use tuwunel_core::{Err, Result, info, utils::stream::ReadyExt};
|
||||
use tuwunel_service::users::device::generate_refresh_token;
|
||||
|
||||
use self::{ldap::ldap_login, password::password_login};
|
||||
@@ -30,7 +30,7 @@ pub(crate) use self::{
|
||||
refresh::refresh_token_route,
|
||||
token::login_token_route,
|
||||
};
|
||||
use super::{DEVICE_ID_LENGTH, TOKEN_LENGTH};
|
||||
use super::TOKEN_LENGTH;
|
||||
use crate::Ruma;
|
||||
|
||||
/// # `GET /_matrix/client/v3/login`
|
||||
@@ -97,43 +97,39 @@ pub(crate) async fn login_route(
|
||||
// Generate a new refresh_token if requested by client
|
||||
let refresh_token = expires_in.is_some().then(generate_refresh_token);
|
||||
|
||||
// Generate new device id if the user didn't specify one
|
||||
let device_id = body
|
||||
.device_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
|
||||
|
||||
// Determine if device_id was provided and exists in the db for this user
|
||||
let device_exists = services
|
||||
.users
|
||||
.all_device_ids(&user_id)
|
||||
.ready_any(|v| v == device_id)
|
||||
.await;
|
||||
|
||||
if !device_exists {
|
||||
services
|
||||
let device_id = if let Some(device_id) = &body.device_id
|
||||
&& services
|
||||
.users
|
||||
.create_device(
|
||||
&user_id,
|
||||
&device_id,
|
||||
(Some(&access_token), expires_in),
|
||||
refresh_token.as_deref(),
|
||||
body.initial_device_display_name.clone(),
|
||||
Some(client.to_string()),
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
.all_device_ids(&user_id)
|
||||
.ready_any(|v| v == device_id)
|
||||
.await
|
||||
{
|
||||
services
|
||||
.users
|
||||
.set_access_token(
|
||||
&user_id,
|
||||
&device_id,
|
||||
device_id,
|
||||
&access_token,
|
||||
expires_in,
|
||||
refresh_token.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
device_id.clone()
|
||||
} else {
|
||||
services
|
||||
.users
|
||||
.create_device(
|
||||
&user_id,
|
||||
body.device_id.as_deref(),
|
||||
(Some(&access_token), expires_in),
|
||||
refresh_token.as_deref(),
|
||||
body.initial_device_display_name.as_deref(),
|
||||
Some(client.to_string()),
|
||||
)
|
||||
.await?
|
||||
};
|
||||
|
||||
info!("{user_id} logged in");
|
||||
|
||||
|
||||
@@ -50,7 +50,8 @@ pub(crate) async fn login_token_route(
|
||||
|
||||
// This route SHOULD have UIA
|
||||
// TODO: How do we make only UIA sessions that have not been used before valid?
|
||||
let (sender_user, sender_device) = body.sender();
|
||||
let sender_user = body.sender_user();
|
||||
let sender_device = body.sender_device()?;
|
||||
|
||||
let password_flow = uiaa::AuthFlow { stages: vec![uiaa::AuthType::Password] };
|
||||
|
||||
|
||||
+145
-85
@@ -35,11 +35,11 @@ use ruma::{
|
||||
};
|
||||
use tokio::time;
|
||||
use tuwunel_core::{
|
||||
Error, Result, at,
|
||||
Result, at,
|
||||
debug::INFO_SPAN_LEVEL,
|
||||
err,
|
||||
error::{inspect_debug_log, inspect_log},
|
||||
extract_variant, is_equal_to,
|
||||
extract_variant, is_equal_to, is_false, is_true,
|
||||
matrix::{
|
||||
Event,
|
||||
event::Matches,
|
||||
@@ -50,7 +50,7 @@ use tuwunel_core::{
|
||||
trace,
|
||||
utils::{
|
||||
self, BoolExt, FutureBoolExt, IterStream, ReadyExt, TryFutureExtExt,
|
||||
future::{OptionStream, ReadyEqExt},
|
||||
future::{OptionStream, ReadyBoolExt},
|
||||
math::ruma_from_u64,
|
||||
result::MapExpect,
|
||||
stream::{BroadbandExt, Tools, TryExpect, WidebandExt},
|
||||
@@ -120,13 +120,15 @@ type PresenceUpdates = HashMap<OwnedUserId, PresenceEventContent>;
|
||||
skip_all,
|
||||
fields(
|
||||
user_id = %body.sender_user(),
|
||||
device_id = %body.sender_device.as_deref().map_or("<no device>", |x| x.as_str()),
|
||||
)
|
||||
)]
|
||||
pub(crate) async fn sync_events_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<sync_events::v3::Request>,
|
||||
) -> Result<sync_events::v3::Response> {
|
||||
let (sender_user, sender_device) = body.sender();
|
||||
let sender_user = body.sender_user();
|
||||
let sender_device = body.sender_device.as_deref();
|
||||
|
||||
let filter: OptionFuture<_> = body
|
||||
.body
|
||||
@@ -195,7 +197,8 @@ pub(crate) async fn sync_events_route(
|
||||
if since < next_batch || full_state {
|
||||
let response = build_sync_events(
|
||||
&services,
|
||||
body.sender(),
|
||||
sender_user,
|
||||
sender_device,
|
||||
since,
|
||||
next_batch,
|
||||
full_state,
|
||||
@@ -216,7 +219,8 @@ pub(crate) async fn sync_events_route(
|
||||
|
||||
// Wait for activity
|
||||
if time::timeout_at(stop_at, watchers).await.is_err() || services.server.is_stopping() {
|
||||
let response = build_empty_response(&services, body.sender(), next_batch).await;
|
||||
let response =
|
||||
build_empty_response(&services, sender_user, sender_device, next_batch).await;
|
||||
trace!(since, next_batch, "empty response");
|
||||
return Ok(response);
|
||||
}
|
||||
@@ -235,14 +239,22 @@ pub(crate) async fn sync_events_route(
|
||||
|
||||
async fn build_empty_response(
|
||||
services: &Services,
|
||||
(sender_user, sender_device): (&UserId, &DeviceId),
|
||||
sender_user: &UserId,
|
||||
sender_device: Option<&DeviceId>,
|
||||
next_batch: u64,
|
||||
) -> sync_events::v3::Response {
|
||||
let device_one_time_keys_count: OptionFuture<_> = sender_device
|
||||
.map(|sender_device| {
|
||||
services
|
||||
.users
|
||||
.count_one_time_keys(sender_user, sender_device)
|
||||
})
|
||||
.into();
|
||||
|
||||
sync_events::v3::Response {
|
||||
device_one_time_keys_count: services
|
||||
.users
|
||||
.count_one_time_keys(sender_user, sender_device)
|
||||
.await,
|
||||
device_one_time_keys_count: device_one_time_keys_count
|
||||
.await
|
||||
.unwrap_or_default(),
|
||||
|
||||
..sync_events::v3::Response::new(to_small_string(next_batch))
|
||||
}
|
||||
@@ -251,7 +263,6 @@ async fn build_empty_response(
|
||||
#[tracing::instrument(
|
||||
name = "build",
|
||||
level = INFO_SPAN_LEVEL,
|
||||
ret(level = "trace"),
|
||||
skip_all,
|
||||
fields(
|
||||
%since,
|
||||
@@ -261,7 +272,8 @@ async fn build_empty_response(
|
||||
)]
|
||||
async fn build_sync_events(
|
||||
services: &Services,
|
||||
(sender_user, sender_device): (&UserId, &DeviceId),
|
||||
sender_user: &UserId,
|
||||
sender_device: Option<&DeviceId>,
|
||||
since: u64,
|
||||
next_batch: u64,
|
||||
full_state: bool,
|
||||
@@ -387,27 +399,38 @@ async fn build_sync_events(
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<HashSet<_>>();
|
||||
|
||||
let to_device_events = services
|
||||
.users
|
||||
.get_to_device_events(sender_user, sender_device, Some(since), Some(next_batch))
|
||||
.map(at!(1))
|
||||
.collect::<Vec<_>>();
|
||||
let to_device_events: OptionFuture<_> = sender_device
|
||||
.map(|sender_device| {
|
||||
services
|
||||
.users
|
||||
.get_to_device_events(sender_user, sender_device, Some(since), Some(next_batch))
|
||||
.map(at!(1))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.into();
|
||||
|
||||
let device_one_time_keys_count = services
|
||||
.users
|
||||
.count_one_time_keys(sender_user, sender_device);
|
||||
let device_one_time_keys_count: OptionFuture<_> = sender_device
|
||||
.map(|sender_device| {
|
||||
services
|
||||
.users
|
||||
.count_one_time_keys(sender_user, sender_device)
|
||||
})
|
||||
.into();
|
||||
|
||||
// Remove all to-device events the device received *last time*
|
||||
let remove_to_device_events =
|
||||
services
|
||||
.users
|
||||
.remove_to_device_events(sender_user, sender_device, since);
|
||||
let remove_to_device_events: OptionFuture<_> = sender_device
|
||||
.map(|sender_device| {
|
||||
services
|
||||
.users
|
||||
.remove_to_device_events(sender_user, sender_device, since)
|
||||
})
|
||||
.into();
|
||||
|
||||
let (
|
||||
account_data,
|
||||
keys_changed,
|
||||
device_one_time_keys_count,
|
||||
((), to_device_events, presence_updates),
|
||||
presence_updates,
|
||||
(_, to_device_events, device_one_time_keys_count),
|
||||
(
|
||||
(joined_rooms, mut device_list_updates, left_encrypted_users),
|
||||
left_rooms,
|
||||
@@ -417,8 +440,8 @@ async fn build_sync_events(
|
||||
) = join5(
|
||||
account_data,
|
||||
keys_changed,
|
||||
device_one_time_keys_count,
|
||||
join3(remove_to_device_events, to_device_events, presence_updates),
|
||||
presence_updates,
|
||||
join3(remove_to_device_events, to_device_events, device_one_time_keys_count),
|
||||
join4(joined_rooms, left_rooms, invited_rooms, knocked_rooms),
|
||||
)
|
||||
.boxed()
|
||||
@@ -454,7 +477,7 @@ async fn build_sync_events(
|
||||
left: device_list_left,
|
||||
changed: device_list_updates.into_iter().collect(),
|
||||
},
|
||||
device_one_time_keys_count,
|
||||
device_one_time_keys_count: device_one_time_keys_count.unwrap_or_default(),
|
||||
// Fallback keys are not yet supported
|
||||
device_unused_fallback_key_types: None,
|
||||
next_batch: to_small_string(next_batch),
|
||||
@@ -465,7 +488,9 @@ async fn build_sync_events(
|
||||
invite: invited_rooms,
|
||||
knock: knocked_rooms,
|
||||
},
|
||||
to_device: ToDevice { events: to_device_events },
|
||||
to_device: ToDevice {
|
||||
events: to_device_events.unwrap_or_default(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -539,7 +564,7 @@ async fn handle_left_room(
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let is_not_found = services.metadata.exists(room_id).eq(&false);
|
||||
let is_not_found = services.metadata.exists(room_id).is_false();
|
||||
|
||||
let is_disabled = services.metadata.is_disabled(room_id);
|
||||
|
||||
@@ -732,7 +757,7 @@ async fn load_left_room(
|
||||
async fn load_joined_room(
|
||||
services: &Services,
|
||||
sender_user: &UserId,
|
||||
sender_device: &DeviceId,
|
||||
sender_device: Option<&DeviceId>,
|
||||
ref room_id: OwnedRoomId,
|
||||
since: u64,
|
||||
next_batch: u64,
|
||||
@@ -744,8 +769,10 @@ async fn load_joined_room(
|
||||
.room
|
||||
.timeline
|
||||
.limit
|
||||
.unwrap_or_else(|| uint!(10))
|
||||
.try_into()?;
|
||||
.map(TryInto::try_into)
|
||||
.map_expect("UInt to usize")
|
||||
.unwrap_or(10)
|
||||
.min(100);
|
||||
|
||||
let (timeline_pdus, limited, last_timeline_count) = load_timeline(
|
||||
services,
|
||||
@@ -757,10 +784,20 @@ async fn load_joined_room(
|
||||
)
|
||||
.await?;
|
||||
|
||||
let since_shortstatehash = services
|
||||
.timeline
|
||||
.prev_shortstatehash(room_id, PduCount::Normal(since).saturating_add(1))
|
||||
.ok();
|
||||
let timeline_changed = last_timeline_count.into_unsigned() > since;
|
||||
debug_assert!(
|
||||
timeline_pdus.is_empty() || timeline_changed,
|
||||
"if timeline events, last_timeline_count must be in the since window."
|
||||
);
|
||||
|
||||
let since_shortstatehash: OptionFuture<_> = timeline_changed
|
||||
.then(|| {
|
||||
services
|
||||
.timeline
|
||||
.prev_shortstatehash(room_id, PduCount::Normal(since).saturating_add(1))
|
||||
.ok()
|
||||
})
|
||||
.into();
|
||||
|
||||
let horizon_shortstatehash: OptionFuture<_> = timeline_pdus
|
||||
.first()
|
||||
@@ -773,12 +810,20 @@ async fn load_joined_room(
|
||||
})
|
||||
.into();
|
||||
|
||||
let current_shortstatehash = services
|
||||
.timeline
|
||||
.get_shortstatehash(room_id, last_timeline_count)
|
||||
.inspect_err(inspect_debug_log)
|
||||
.or_else(|_| services.state.get_room_shortstatehash(room_id))
|
||||
.map_err(|_| err!(Database(error!("Room {room_id} has no state"))));
|
||||
let current_shortstatehash: OptionFuture<_> = timeline_changed
|
||||
.then(|| {
|
||||
services
|
||||
.timeline
|
||||
.get_shortstatehash(room_id, last_timeline_count)
|
||||
.inspect_err(inspect_debug_log)
|
||||
.or_else(|_| services.state.get_room_shortstatehash(room_id))
|
||||
.map_err(|_| err!(Database(error!("Room {room_id} has no state"))))
|
||||
})
|
||||
.into();
|
||||
|
||||
let encrypted_room: OptionFuture<_> = timeline_changed
|
||||
.then(|| services.state_accessor.is_encrypted_room(room_id))
|
||||
.into();
|
||||
|
||||
let receipt_events = services
|
||||
.read_receipt
|
||||
@@ -792,8 +837,6 @@ async fn load_joined_room(
|
||||
})
|
||||
.collect::<HashMap<OwnedUserId, Raw<AnySyncEphemeralRoomEvent>>>();
|
||||
|
||||
let encrypted_room = services.state_accessor.is_encrypted_room(room_id);
|
||||
|
||||
let (
|
||||
(since_shortstatehash, horizon_shortstatehash, current_shortstatehash),
|
||||
receipt_events,
|
||||
@@ -803,8 +846,12 @@ async fn load_joined_room(
|
||||
receipt_events,
|
||||
encrypted_room,
|
||||
)
|
||||
.map(|((since, horizon, current), receipt, encrypted_room)| {
|
||||
Ok::<_, Error>(((since, horizon.flat_ok(), current?), receipt, encrypted_room))
|
||||
.map(|((since, horizon, current), receipt, encrypted_room)| -> Result<_> {
|
||||
Ok((
|
||||
(since.flatten(), horizon.flat_ok(), current.transpose()?),
|
||||
receipt,
|
||||
encrypted_room,
|
||||
))
|
||||
})
|
||||
.boxed()
|
||||
.await?;
|
||||
@@ -812,14 +859,14 @@ async fn load_joined_room(
|
||||
let lazy_load_options =
|
||||
[&filter.room.state.lazy_load_options, &filter.room.timeline.lazy_load_options];
|
||||
|
||||
let lazy_loading_enabled = !encrypted_room
|
||||
let lazy_loading_enabled = encrypted_room.is_some_and(is_false!())
|
||||
&& lazy_load_options
|
||||
.iter()
|
||||
.any(|opts| opts.is_enabled());
|
||||
|
||||
let lazy_loading_context = &lazy_loading::Context {
|
||||
user_id: sender_user,
|
||||
device_id: Some(sender_device),
|
||||
device_id: sender_device,
|
||||
room_id,
|
||||
token: Some(since),
|
||||
options: Some(&filter.room.state.lazy_load_options),
|
||||
@@ -847,9 +894,14 @@ async fn load_joined_room(
|
||||
})
|
||||
.into();
|
||||
|
||||
let sender_joined_count = services
|
||||
.state_cache
|
||||
.get_joined_count(room_id, sender_user);
|
||||
let sender_joined_count: OptionFuture<_> = timeline_changed
|
||||
.then(|| {
|
||||
services
|
||||
.state_cache
|
||||
.get_joined_count(room_id, sender_user)
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.into();
|
||||
|
||||
let since_encryption: OptionFuture<_> = since_shortstatehash
|
||||
.map(|shortstatehash| {
|
||||
@@ -859,10 +911,6 @@ async fn load_joined_room(
|
||||
})
|
||||
.into();
|
||||
|
||||
let last_privateread_update = services
|
||||
.read_receipt
|
||||
.last_privateread_update(sender_user, room_id);
|
||||
|
||||
let last_notification_read: OptionFuture<_> = timeline_pdus
|
||||
.is_empty()
|
||||
.then(|| {
|
||||
@@ -873,6 +921,10 @@ async fn load_joined_room(
|
||||
})
|
||||
.into();
|
||||
|
||||
let last_privateread_update = services
|
||||
.read_receipt
|
||||
.last_privateread_update(sender_user, room_id);
|
||||
|
||||
let (
|
||||
(last_privateread_update, last_notification_read),
|
||||
(sender_joined_count, since_encryption),
|
||||
@@ -884,27 +936,36 @@ async fn load_joined_room(
|
||||
)
|
||||
.await;
|
||||
|
||||
let _encrypted_since_last_sync = !initial && encrypted_room && since_encryption.is_none();
|
||||
let _encrypted_since_last_sync =
|
||||
!initial && encrypted_room.is_some_and(is_true!()) && since_encryption.is_none();
|
||||
|
||||
let joined_since_last_sync = sender_joined_count.is_ok_and(|count| count > since);
|
||||
let joined_since_last_sync = sender_joined_count.unwrap_or(0) > since;
|
||||
|
||||
let state_changes: OptionFuture<_> = current_shortstatehash
|
||||
.map(|current_shortstatehash| {
|
||||
calculate_state_changes(
|
||||
services,
|
||||
sender_user,
|
||||
room_id,
|
||||
full_state || initial,
|
||||
since_shortstatehash,
|
||||
horizon_shortstatehash,
|
||||
current_shortstatehash,
|
||||
joined_since_last_sync,
|
||||
witness.as_ref(),
|
||||
)
|
||||
})
|
||||
.into();
|
||||
|
||||
let StateChanges {
|
||||
heroes,
|
||||
joined_member_count,
|
||||
invited_member_count,
|
||||
mut state_events,
|
||||
} = calculate_state_changes(
|
||||
services,
|
||||
sender_user,
|
||||
room_id,
|
||||
full_state || initial,
|
||||
since_shortstatehash,
|
||||
horizon_shortstatehash,
|
||||
current_shortstatehash,
|
||||
joined_since_last_sync,
|
||||
witness.as_ref(),
|
||||
)
|
||||
.await?;
|
||||
} = state_changes
|
||||
.await
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
|
||||
let is_sender_membership = |event: &PduEvent| {
|
||||
*event.event_type() == StateEventType::RoomMember.into()
|
||||
@@ -1182,6 +1243,7 @@ async fn calculate_state_changes<'a>(
|
||||
.state_accessor
|
||||
.state_full_shortids(horizon_shortstatehash)
|
||||
.expect_ok()
|
||||
.boxed()
|
||||
.into_future()
|
||||
})
|
||||
.into();
|
||||
@@ -1262,7 +1324,10 @@ async fn calculate_counts(
|
||||
|
||||
let small_room = joined_member_count.saturating_add(invited_member_count) <= 5;
|
||||
|
||||
let heroes: OptionFuture<_> = small_room
|
||||
let heroes: OptionFuture<_> = services
|
||||
.config
|
||||
.calculate_heroes
|
||||
.and_is(small_room)
|
||||
.then(|| calculate_heroes(services, room_id, sender_user))
|
||||
.into();
|
||||
|
||||
@@ -1275,28 +1340,23 @@ async fn calculate_heroes(
|
||||
sender_user: &UserId,
|
||||
) -> Vec<OwnedUserId> {
|
||||
services
|
||||
.timeline
|
||||
.all_pdus(sender_user, room_id)
|
||||
.ready_filter(|(_, pdu)| pdu.kind == RoomMember)
|
||||
.fold_default(|heroes: Vec<_>, (_, pdu)| {
|
||||
.state_accessor
|
||||
.room_state_type_pdus(room_id, &StateEventType::RoomMember)
|
||||
.ready_filter_map(Result::ok)
|
||||
.fold_default(|heroes: Vec<_>, pdu| {
|
||||
fold_hero(heroes, services, room_id, sender_user, pdu)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn fold_hero(
|
||||
async fn fold_hero<Pdu: Event>(
|
||||
mut heroes: Vec<OwnedUserId>,
|
||||
services: &Services,
|
||||
room_id: &RoomId,
|
||||
sender_user: &UserId,
|
||||
pdu: PduEvent,
|
||||
pdu: Pdu,
|
||||
) -> Vec<OwnedUserId> {
|
||||
let Some(user_id): Option<&UserId> = pdu
|
||||
.state_key
|
||||
.as_deref()
|
||||
.map(TryInto::try_into)
|
||||
.flat_ok()
|
||||
else {
|
||||
let Some(user_id): Option<&UserId> = pdu.state_key().map(TryInto::try_into).flat_ok() else {
|
||||
return heroes;
|
||||
};
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ use crate::Ruma;
|
||||
struct SyncInfo<'a> {
|
||||
services: &'a Services,
|
||||
sender_user: &'a UserId,
|
||||
sender_device: &'a DeviceId,
|
||||
sender_device: Option<&'a DeviceId>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -69,7 +69,7 @@ type ListIds = SmallVec<[ListId; 1]>;
|
||||
skip_all,
|
||||
fields(
|
||||
user_id = %body.sender_user().localpart(),
|
||||
device_id = %body.sender_device(),
|
||||
device_id = %body.sender_device.as_deref().map_or("<no device>", |x| x.as_str()),
|
||||
conn_id = ?body.body.conn_id.clone().unwrap_or_default(),
|
||||
since = ?body.body.pos.clone().unwrap_or_default(),
|
||||
)
|
||||
@@ -78,7 +78,8 @@ pub(crate) async fn sync_events_v5_route(
|
||||
State(ref services): State<crate::State>,
|
||||
body: Ruma<Request>,
|
||||
) -> Result<Response> {
|
||||
let (sender_user, sender_device) = body.sender();
|
||||
let sender_user = body.sender_user();
|
||||
let sender_device = body.sender_device.as_deref();
|
||||
let request = &body.body;
|
||||
let since = request
|
||||
.pos
|
||||
@@ -108,7 +109,7 @@ pub(crate) async fn sync_events_v5_route(
|
||||
let conn = conn_val.lock();
|
||||
let ping_presence = services
|
||||
.presence
|
||||
.maybe_ping_presence(sender_user, Some(sender_device), &request.set_presence)
|
||||
.maybe_ping_presence(sender_user, sender_device, &request.set_presence)
|
||||
.inspect_err(inspect_log)
|
||||
.ok();
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ pub(super) async fn collect(
|
||||
conn: &Connection,
|
||||
) -> Result<response::E2EE> {
|
||||
let SyncInfo { services, sender_user, sender_device, .. } = sync_info;
|
||||
let Some(sender_device) = sender_device else {
|
||||
return Ok(response::E2EE::default());
|
||||
};
|
||||
|
||||
let keys_changed = services
|
||||
.users
|
||||
@@ -170,6 +173,7 @@ async fn collect_room(
|
||||
.ready_filter(|&user_id| user_id != sender_user)
|
||||
.map(ToOwned::to_owned)
|
||||
.map(|user_id| (MembershipState::Join, user_id))
|
||||
.boxed()
|
||||
.into_future()
|
||||
})
|
||||
.into();
|
||||
|
||||
@@ -9,6 +9,10 @@ pub(super) async fn collect(
|
||||
SyncInfo { services, sender_user, sender_device, .. }: SyncInfo<'_>,
|
||||
conn: &Connection,
|
||||
) -> Result<Option<response::ToDevice>> {
|
||||
let Some(sender_device) = sender_device else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
services
|
||||
.users
|
||||
.remove_to_device_events(sender_user, sender_device, conn.globalsince)
|
||||
|
||||
@@ -7,7 +7,7 @@ use tuwunel_core::{
|
||||
is_equal_to, is_true,
|
||||
utils::{
|
||||
BoolExt, FutureBoolExt, IterStream, ReadyExt,
|
||||
future::{self, OptionExt, ReadyEqExt},
|
||||
future::{self, OptionExt, ReadyBoolExt},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -132,7 +132,7 @@ pub(super) async fn filter_room_meta(
|
||||
SyncInfo { services, sender_user, .. }: SyncInfo<'_>,
|
||||
room_id: &RoomId,
|
||||
) -> bool {
|
||||
let not_exists = services.metadata.exists(room_id).eq(&false);
|
||||
let not_exists = services.metadata.exists(room_id).is_false();
|
||||
|
||||
let is_disabled = services.metadata.is_disabled(room_id);
|
||||
|
||||
@@ -141,13 +141,13 @@ pub(super) async fn filter_room_meta(
|
||||
let not_visible = services
|
||||
.state_accessor
|
||||
.user_can_see_state_events(sender_user, room_id)
|
||||
.eq(&false);
|
||||
.is_false();
|
||||
|
||||
pin_mut!(not_visible, not_exists, is_disabled, is_banned);
|
||||
not_visible
|
||||
.or(not_exists)
|
||||
.or(is_disabled)
|
||||
.or(is_banned)
|
||||
.is_false()
|
||||
.await
|
||||
.eq(&false)
|
||||
}
|
||||
@@ -327,20 +327,27 @@ async fn handle_room(
|
||||
.boxed()
|
||||
.await;
|
||||
|
||||
let (heroes, hero_name, heroes_avatar) = calculate_heroes(
|
||||
services,
|
||||
sender_user,
|
||||
room_id,
|
||||
room_name.as_ref(),
|
||||
room_avatar.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
let heroes: OptionFuture<_> = services
|
||||
.config
|
||||
.calculate_heroes
|
||||
.then(|| {
|
||||
calculate_heroes(
|
||||
services,
|
||||
sender_user,
|
||||
room_id,
|
||||
room_name.as_ref(),
|
||||
room_avatar.as_deref(),
|
||||
)
|
||||
})
|
||||
.into();
|
||||
|
||||
let (heroes, heroes_name, heroes_avatar) = heroes.await.unwrap_or_default();
|
||||
|
||||
Ok(response::Room {
|
||||
initial: roomsince.eq(&0).then_some(true),
|
||||
lists: lists.clone(),
|
||||
membership: membership.clone(),
|
||||
name: room_name.or(hero_name),
|
||||
name: room_name.or(heroes_name),
|
||||
avatar: JsOption::from_option(room_avatar.or(heroes_avatar)),
|
||||
is_dm,
|
||||
heroes,
|
||||
@@ -365,8 +372,9 @@ async fn calculate_heroes(
|
||||
room_id: &RoomId,
|
||||
room_name: Option<&DisplayName>,
|
||||
room_avatar: Option<&MxcUri>,
|
||||
) -> Result<(Option<Heroes>, Option<DisplayName>, Option<OwnedMxcUri>)> {
|
||||
) -> (Option<Heroes>, Option<DisplayName>, Option<OwnedMxcUri>) {
|
||||
const MAX_HEROES: usize = 5;
|
||||
|
||||
let heroes: Heroes = services
|
||||
.state_cache
|
||||
.room_members(room_id)
|
||||
@@ -443,5 +451,5 @@ async fn calculate_heroes(
|
||||
})
|
||||
.flatten();
|
||||
|
||||
Ok((Some(heroes), hero_name, heroes_avatar))
|
||||
(Some(heroes), hero_name, heroes_avatar)
|
||||
}
|
||||
@@ -243,8 +243,8 @@ pub(crate) async fn get_timezone_key_route(
|
||||
if !services.globals.user_is_local(&body.user_id) {
|
||||
// Create and update our local copy of the user
|
||||
if let Ok(response) = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
.federation
|
||||
.execute(
|
||||
body.user_id.server_name(),
|
||||
federation::query::get_profile_information::v1::Request {
|
||||
user_id: body.user_id.clone(),
|
||||
@@ -304,8 +304,8 @@ pub(crate) async fn get_profile_field_route(
|
||||
if !services.globals.user_is_local(&body.user_id) {
|
||||
// Create and update our local copy of the user
|
||||
if let Ok(response) = services
|
||||
.sending
|
||||
.send_federation_request(
|
||||
.federation
|
||||
.execute(
|
||||
body.user_id.server_name(),
|
||||
federation::query::get_profile_information::v1::Request {
|
||||
user_id: body.user_id.clone(),
|
||||
|
||||
@@ -37,7 +37,8 @@ pub(crate) async fn get_supported_versions_route(
|
||||
"v1.3".to_owned(),
|
||||
"v1.4".to_owned(),
|
||||
"v1.5".to_owned(),
|
||||
"v1.11".to_owned(),
|
||||
"v1.10".to_owned(), // relations recursion
|
||||
"v1.11".to_owned(), // authenticated media
|
||||
],
|
||||
unstable_features: BTreeMap::from_iter([
|
||||
("org.matrix.e2e_cross_signing".to_owned(), true),
|
||||
|
||||
@@ -34,7 +34,7 @@ pub(crate) async fn search_users_route(
|
||||
.min(LIMIT_MAX);
|
||||
|
||||
let search_term = body.search_term.to_lowercase();
|
||||
let mut users = services
|
||||
let users = services
|
||||
.users
|
||||
.stream()
|
||||
.ready_filter(|&user_id| user_id != sender_user)
|
||||
@@ -83,6 +83,7 @@ pub(crate) async fn search_users_route(
|
||||
})
|
||||
});
|
||||
|
||||
pin_mut!(users);
|
||||
let results = users.by_ref().take(limit).collect().await;
|
||||
let limited = users.next().await.is_some();
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ pub(crate) async fn turn_server_route(
|
||||
|
||||
let turn_secret = &services.globals.turn_secret;
|
||||
|
||||
let (username, password) = if !turn_secret.is_empty() {
|
||||
let (username, password) = if let Some(turn_secret) = turn_secret {
|
||||
let expiry = SecondsSinceUnixEpoch::from_system_time(
|
||||
SystemTime::now()
|
||||
.checked_add(Duration::from_secs(services.config.turn_ttl))
|
||||
|
||||
+3
-1
@@ -195,6 +195,9 @@ pub fn build(router: Router<State>, server: &Server) -> Router<State> {
|
||||
.ruma_route(&client::room_initial_sync_route)
|
||||
.route("/client/server.json", get(client::syncv3_client_server_json));
|
||||
|
||||
// SS endpoint not related to federation
|
||||
router = router.ruma_route(&server::get_openid_userinfo_route);
|
||||
|
||||
if config.allow_federation {
|
||||
router = router
|
||||
.ruma_route(&server::get_server_version_route)
|
||||
@@ -226,7 +229,6 @@ pub fn build(router: Router<State>, server: &Server) -> Router<State> {
|
||||
.ruma_route(&server::get_profile_information_route)
|
||||
.ruma_route(&server::get_keys_route)
|
||||
.ruma_route(&server::claim_keys_route)
|
||||
.ruma_route(&server::get_openid_userinfo_route)
|
||||
.ruma_route(&server::get_hierarchy_route)
|
||||
.ruma_route(&server::well_known_server)
|
||||
.ruma_route(&server::get_content_route)
|
||||
|
||||
+8
-13
@@ -40,11 +40,6 @@ pub(crate) struct Args<T> {
|
||||
}
|
||||
|
||||
impl<T> Args<T> {
|
||||
#[inline]
|
||||
pub(crate) fn sender(&self) -> (&UserId, &DeviceId) {
|
||||
(self.sender_user(), self.sender_device())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn sender_user(&self) -> &UserId {
|
||||
self.sender_user
|
||||
@@ -52,19 +47,19 @@ impl<T> Args<T> {
|
||||
.expect("user must be authenticated for this handler")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn sender_device(&self) -> &DeviceId {
|
||||
self.sender_device
|
||||
.as_deref()
|
||||
.expect("user must be authenticated and device identified")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn origin(&self) -> &ServerName {
|
||||
self.origin
|
||||
.as_deref()
|
||||
.expect("server must be authenticated for this handler")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn sender_device(&self) -> Result<&DeviceId> {
|
||||
self.sender_device
|
||||
.as_deref()
|
||||
.ok_or(err!(Request(Forbidden("user must be authenticated and device identified"))))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for Args<T>
|
||||
@@ -87,7 +82,7 @@ where
|
||||
level = "debug",
|
||||
skip(services),
|
||||
err(level = "debug")
|
||||
ret,
|
||||
ret(level = "trace"),
|
||||
)]
|
||||
async fn from_request(
|
||||
request: hyper::Request<Body>,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use axum::RequestPartsExt;
|
||||
use axum_extra::{TypedHeader, headers::Authorization, typed_header::TypedHeaderRejectionReason};
|
||||
use http::uri::PathAndQuery;
|
||||
use ruma::{
|
||||
CanonicalJsonName, CanonicalJsonObject, CanonicalJsonValue,
|
||||
api::federation::authentication::XMatrix,
|
||||
@@ -30,8 +31,8 @@ pub(super) async fn auth_server(
|
||||
.parts
|
||||
.uri
|
||||
.path_and_query()
|
||||
.expect("all requests have a path")
|
||||
.to_string();
|
||||
.map(PathAndQuery::as_str)
|
||||
.unwrap_or("/");
|
||||
|
||||
let signature: [Member; 1] =
|
||||
[(x_matrix.key.as_str().into(), Value::String(x_matrix.sig.to_string()))];
|
||||
@@ -45,7 +46,7 @@ pub(super) async fn auth_server(
|
||||
("method".into(), Value::String(request.parts.method.as_str().into())),
|
||||
("origin".into(), Value::String(origin.as_str().into())),
|
||||
("signatures".into(), Value::Object(signatures.into())),
|
||||
("uri".into(), Value::String(signature_uri)),
|
||||
("uri".into(), Value::String(signature_uri.into())),
|
||||
];
|
||||
|
||||
authorization.into()
|
||||
@@ -55,7 +56,7 @@ pub(super) async fn auth_server(
|
||||
("method".into(), Value::String(request.parts.method.as_str().into())),
|
||||
("origin".into(), Value::String(origin.as_str().into())),
|
||||
("signatures".into(), Value::Object(signatures.into())),
|
||||
("uri".into(), Value::String(signature_uri)),
|
||||
("uri".into(), Value::String(signature_uri.into())),
|
||||
];
|
||||
|
||||
authorization.into()
|
||||
|
||||
@@ -14,6 +14,8 @@ pub(crate) async fn auth_uiaa<T>(services: &Services, body: &Ruma<T>) -> Result<
|
||||
where
|
||||
T: IncomingRequest + Send + Sync,
|
||||
{
|
||||
let sender_device = body.sender_device()?;
|
||||
|
||||
let flows = [
|
||||
AuthFlow::new([AuthType::Password].into()),
|
||||
AuthFlow::new([AuthType::Jwt].into()),
|
||||
@@ -51,7 +53,7 @@ where
|
||||
|
||||
let (worked, uiaainfo) = services
|
||||
.uiaa
|
||||
.try_auth(sender_user, body.sender_device(), auth, &uiaainfo)
|
||||
.try_auth(sender_user, sender_device, auth, &uiaainfo)
|
||||
.await?;
|
||||
|
||||
if !worked {
|
||||
@@ -71,7 +73,7 @@ where
|
||||
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
|
||||
services
|
||||
.uiaa
|
||||
.create(sender_user, body.sender_device(), &uiaainfo, json);
|
||||
.create(sender_user, sender_device, &uiaainfo, json);
|
||||
|
||||
Err(Error::Uiaa(uiaainfo))
|
||||
},
|
||||
|
||||
@@ -9,7 +9,7 @@ use axum::{
|
||||
use futures::{Future, TryFutureExt};
|
||||
use http::Method;
|
||||
use ruma::api::IncomingRequest;
|
||||
use tuwunel_core::Result;
|
||||
use tuwunel_core::{Result, trace};
|
||||
|
||||
use super::{Ruma, RumaResponse, State};
|
||||
|
||||
@@ -42,7 +42,7 @@ macro_rules! ruma_handler {
|
||||
Fut: Future<Output = Result<Req::OutgoingResponse, Err>> + Send,
|
||||
Req: IncomingRequest + Debug + Send + Sync + 'static,
|
||||
Err: IntoResponse + Debug + Send,
|
||||
<Req as IncomingRequest>::OutgoingResponse: Send,
|
||||
<Req as IncomingRequest>::OutgoingResponse: Debug + Send,
|
||||
$( $tx: FromRequestParts<State> + Send + Sync + 'static, )*
|
||||
{
|
||||
fn add_routes(&'static self, router: Router<State>) -> Router<State> {
|
||||
@@ -53,8 +53,13 @@ macro_rules! ruma_handler {
|
||||
}
|
||||
|
||||
fn add_route(&'static self, router: Router<State>, path: &str) -> Router<State> {
|
||||
let action = |$($tx,)* req| self($($tx,)* req).map_ok(RumaResponse);
|
||||
let method = method_to_filter(&Req::METADATA.method);
|
||||
let action = |$($tx,)* req| {
|
||||
self($($tx,)* req)
|
||||
.inspect_ok(|result| trace!(?result))
|
||||
.map_ok(RumaResponse)
|
||||
};
|
||||
|
||||
router.route(path, on(method, action))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::{ops::Deref, sync::Arc};
|
||||
|
||||
use tuwunel_service::Services;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct State {
|
||||
services: *const Services,
|
||||
}
|
||||
|
||||
@@ -3,13 +3,13 @@ use axum_client_ip::InsecureClientIp;
|
||||
use base64::{Engine as _, engine::general_purpose};
|
||||
use futures::StreamExt;
|
||||
use ruma::{
|
||||
CanonicalJsonValue, OwnedUserId, UserId,
|
||||
CanonicalJsonValue, OwnedRoomId, OwnedUserId, RoomId, UserId,
|
||||
api::{
|
||||
client::error::ErrorKind,
|
||||
federation::membership::{RawStrippedState, create_invite},
|
||||
},
|
||||
events::{
|
||||
GlobalAccountDataEventType,
|
||||
GlobalAccountDataEventType, StateEventType,
|
||||
push_rules::PushRulesEvent,
|
||||
room::member::{MembershipState, RoomMemberEventContent},
|
||||
},
|
||||
@@ -78,6 +78,26 @@ pub(crate) async fn create_invite_route(
|
||||
let mut signed_event = utils::to_canonical_object(&body.event)
|
||||
.map_err(|_| err!(Request(InvalidParam("Invite event is invalid."))))?;
|
||||
|
||||
let room_id: OwnedRoomId = signed_event
|
||||
.get("room_id")
|
||||
.try_into()
|
||||
.map(RoomId::to_owned)
|
||||
.map_err(|e| err!(Request(InvalidParam("Invalid room_id property: {e}"))))?;
|
||||
|
||||
if body.room_id != room_id {
|
||||
return Err!(Request(InvalidParam("Event room_id does not match the request path.")));
|
||||
}
|
||||
|
||||
let kind: StateEventType = signed_event
|
||||
.get("type")
|
||||
.and_then(CanonicalJsonValue::as_str)
|
||||
.ok_or_else(|| err!(Request(BadJson("Missing type in event."))))?
|
||||
.into();
|
||||
|
||||
if kind != StateEventType::RoomMember {
|
||||
return Err!(Request(InvalidParam("Event must be m.room.member type.")));
|
||||
}
|
||||
|
||||
let invited_user: OwnedUserId = signed_event
|
||||
.get("state_key")
|
||||
.try_into()
|
||||
@@ -91,6 +111,19 @@ pub(crate) async fn create_invite_route(
|
||||
return Err!(Request(InvalidParam("User does not belong to this homeserver.")));
|
||||
}
|
||||
|
||||
let content: RoomMemberEventContent = signed_event
|
||||
.get("content")
|
||||
.cloned()
|
||||
.map(Into::into)
|
||||
.map(serde_json::from_value)
|
||||
.transpose()
|
||||
.map_err(|e| err!(Request(InvalidParam("Invalid content object in event: {e}"))))?
|
||||
.ok_or_else(|| err!(Request(BadJson("Missing content in event."))))?;
|
||||
|
||||
if content.membership != MembershipState::Invite {
|
||||
return Err!(Request(InvalidParam("Event membership must be invite.")));
|
||||
}
|
||||
|
||||
// Make sure we're not ACL'ed from their room.
|
||||
services
|
||||
.event_handler
|
||||
@@ -108,11 +141,27 @@ pub(crate) async fn create_invite_route(
|
||||
// Add event_id back
|
||||
signed_event.insert("event_id".into(), CanonicalJsonValue::String(event_id.to_string()));
|
||||
|
||||
let origin: Option<&str> = signed_event
|
||||
.get("origin")
|
||||
.and_then(CanonicalJsonValue::as_str);
|
||||
|
||||
let sender: &UserId = signed_event
|
||||
.get("sender")
|
||||
.try_into()
|
||||
.map_err(|e| err!(Request(InvalidParam("Invalid sender property: {e}"))))?;
|
||||
|
||||
if sender.server_name() != body.origin() {
|
||||
return Err!(Request(Forbidden("Can only send invites on behalf of your users.")));
|
||||
}
|
||||
|
||||
if origin.is_some_and(|origin| origin != sender.server_name()) {
|
||||
return Err!(Request(Forbidden("Your users can only be from your origin.")));
|
||||
}
|
||||
|
||||
if origin.is_some_and(|origin| origin != body.origin()) {
|
||||
return Err!(Request(Forbidden("Can only send events from your origin.")));
|
||||
}
|
||||
|
||||
if services.metadata.is_banned(&body.room_id).await
|
||||
&& !services.users.is_admin(&invited_user).await
|
||||
{
|
||||
@@ -198,8 +247,8 @@ pub(crate) async fn create_invite_route(
|
||||
for appservice in services.appservice.read().await.values() {
|
||||
if appservice.is_user_match(&invited_user) {
|
||||
services
|
||||
.sending
|
||||
.send_appservice_request(
|
||||
.appservice
|
||||
.send_request(
|
||||
appservice.registration.clone(),
|
||||
ruma::api::appservice::event::push_events::v1::Request {
|
||||
events: vec![pdu.to_format()],
|
||||
|
||||
@@ -208,6 +208,7 @@ async fn create_join_event(
|
||||
.handle_incoming_pdu(&origin, room_id, &event_id, value.clone(), true)
|
||||
.boxed()
|
||||
.await?
|
||||
.map(at!(0))
|
||||
.ok_or_else(|| err!(Request(InvalidParam("Could not accept as timeline event."))))?;
|
||||
|
||||
drop(mutex_lock);
|
||||
|
||||
@@ -11,7 +11,7 @@ use ruma::{
|
||||
serde::JsonObject,
|
||||
};
|
||||
use tuwunel_core::{
|
||||
Err, Result, err,
|
||||
Err, Result, at, err,
|
||||
matrix::{event::gen_event_id_canonical_json, pdu::PduEvent},
|
||||
warn,
|
||||
};
|
||||
@@ -170,6 +170,7 @@ pub(crate) async fn create_knock_event_v1_route(
|
||||
.handle_incoming_pdu(&origin, &body.room_id, &event_id, value.clone(), true)
|
||||
.boxed()
|
||||
.await?
|
||||
.map(at!(0))
|
||||
.ok_or_else(|| err!(Request(InvalidParam("Could not accept as timeline event."))))?;
|
||||
|
||||
drop(mutex_lock);
|
||||
|
||||
@@ -11,7 +11,7 @@ use ruma::{
|
||||
},
|
||||
};
|
||||
use serde_json::value::RawValue as RawJsonValue;
|
||||
use tuwunel_core::{Err, Result, err, matrix::event::gen_event_id_canonical_json};
|
||||
use tuwunel_core::{Err, Result, at, err, matrix::event::gen_event_id_canonical_json};
|
||||
use tuwunel_service::Services;
|
||||
|
||||
use crate::Ruma;
|
||||
@@ -151,6 +151,7 @@ async fn create_leave_event(
|
||||
.handle_incoming_pdu(origin, room_id, &event_id, value, true)
|
||||
.boxed()
|
||||
.await?
|
||||
.map(at!(0))
|
||||
.ok_or_else(|| err!(Request(InvalidParam("Could not accept as timeline event."))))?;
|
||||
|
||||
drop(mutex_lock);
|
||||
|
||||
+5
-13
@@ -26,18 +26,14 @@ gzip_compression = [
|
||||
"reqwest/gzip",
|
||||
]
|
||||
jemalloc = [
|
||||
"dep:tikv-jemalloc-sys",
|
||||
"dep:tikv-jemalloc-ctl",
|
||||
"dep:tikv-jemallocator",
|
||||
"dep:jevmalloc",
|
||||
]
|
||||
jemalloc_conf = []
|
||||
jemalloc_prof = [
|
||||
"tikv-jemalloc-sys/profiling",
|
||||
#"jevmalloc/profiling",
|
||||
]
|
||||
jemalloc_stats = [
|
||||
"tikv-jemalloc-sys/stats",
|
||||
"tikv-jemalloc-ctl/stats",
|
||||
"tikv-jemallocator/stats",
|
||||
#"jevmalloc/stats",
|
||||
]
|
||||
perf_measurements = []
|
||||
release_max_log_level = [
|
||||
@@ -96,12 +92,8 @@ serde.workspace = true
|
||||
smallvec.workspace = true
|
||||
smallstr.workspace = true
|
||||
thiserror.workspace = true
|
||||
tikv-jemallocator.optional = true
|
||||
tikv-jemallocator.workspace = true
|
||||
tikv-jemalloc-ctl.optional = true
|
||||
tikv-jemalloc-ctl.workspace = true
|
||||
tikv-jemalloc-sys.optional = true
|
||||
tikv-jemalloc-sys.workspace = true
|
||||
jevmalloc.optional = true
|
||||
jevmalloc.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio-metrics.workspace = true
|
||||
toml.workspace = true
|
||||
|
||||
+78
-23
@@ -1,20 +1,26 @@
|
||||
//! jemalloc allocator
|
||||
|
||||
use std::{
|
||||
alloc::Layout,
|
||||
cell::OnceCell,
|
||||
ffi::{CStr, c_char, c_void},
|
||||
fmt::Debug,
|
||||
sync::RwLock,
|
||||
panic::catch_unwind,
|
||||
process::abort,
|
||||
sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
use tikv_jemalloc_ctl as mallctl;
|
||||
use tikv_jemalloc_sys as ffi;
|
||||
use tikv_jemallocator as jemalloc;
|
||||
use jevmalloc as jemalloc;
|
||||
use jevmalloc::{ctl as mallctl, ffi};
|
||||
|
||||
use crate::{
|
||||
Result, err, is_equal_to, is_nonzero,
|
||||
utils::{math, math::Tried},
|
||||
Result,
|
||||
arrayvec::ArrayVec,
|
||||
err, is_equal_to, is_nonzero,
|
||||
utils::{BoolExt, math, math::Tried},
|
||||
};
|
||||
|
||||
#[cfg(feature = "jemalloc_conf")]
|
||||
@@ -29,7 +35,7 @@ pub static malloc_conf: &[u8] = const_str::concat_bytes!(
|
||||
",metadata_thp:always",
|
||||
",background_thread:true",
|
||||
",max_background_threads:-1",
|
||||
MALLOC_CONF_PROF,
|
||||
//MALLOC_CONF_PROF,
|
||||
0
|
||||
);
|
||||
|
||||
@@ -38,16 +44,12 @@ pub static malloc_conf: &[u8] = const_str::concat_bytes!(
|
||||
feature = "jemalloc_prof",
|
||||
target_arch = "x86_64",
|
||||
))]
|
||||
const MALLOC_CONF_PROF: &str = ",prof_active:false";
|
||||
const _MALLOC_CONF_PROF: &str = ",prof_active:false";
|
||||
#[cfg(all(
|
||||
feature = "jemalloc_conf",
|
||||
any(not(feature = "jemalloc_prof"), not(target_arch = "x86_64")),
|
||||
))]
|
||||
const MALLOC_CONF_PROF: &str = "";
|
||||
|
||||
#[global_allocator]
|
||||
static JEMALLOC: jemalloc::Jemalloc = jemalloc::Jemalloc;
|
||||
static CONTROL: RwLock<()> = RwLock::new(());
|
||||
const _MALLOC_CONF_PROF: &str = "";
|
||||
|
||||
type Name = ArrayVec<u8, NAME_MAX>;
|
||||
type Key = ArrayVec<usize, KEY_SEGS>;
|
||||
@@ -55,14 +57,27 @@ type Key = ArrayVec<usize, KEY_SEGS>;
|
||||
const NAME_MAX: usize = 128;
|
||||
const KEY_SEGS: usize = 8;
|
||||
|
||||
#[global_allocator]
|
||||
static JEMALLOC: jemalloc::Jemalloc = jemalloc::Jemalloc;
|
||||
static CONTROL: Mutex<()> = Mutex::new(());
|
||||
|
||||
static GLOBAL_ALLOCS: AtomicU64 = AtomicU64::new(0);
|
||||
static COUNT_GLOBAL_ALLOCS: AtomicBool = AtomicBool::new(false);
|
||||
static TRACE_GLOBAL_ALLOCS: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
#[crate::ctor]
|
||||
fn _static_initialization() {
|
||||
acq_epoch().expect("pre-initialization of jemalloc failed");
|
||||
acq_epoch().expect("pre-initialization of jemalloc failed");
|
||||
// SAFETY: Mutable static globals in jemalloc crate; must be initialized
|
||||
// properly and uniquely.
|
||||
unsafe {
|
||||
jemalloc::hook::ALLOC = Some(global_alloc_hook);
|
||||
jemalloc::hook::ALLOC_ZEROED = Some(global_alloc_zeroed_hook);
|
||||
};
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[cfg(feature = "jemalloc_stats")]
|
||||
#[cfg(disable)]
|
||||
//#[cfg(feature = "jemalloc_stats")]
|
||||
pub fn memory_usage() -> Option<String> {
|
||||
use mallctl::stats;
|
||||
|
||||
@@ -91,7 +106,7 @@ pub fn memory_usage() -> Option<String> {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[cfg(not(feature = "jemalloc_stats"))]
|
||||
//#[cfg(not(feature = "jemalloc_stats"))]
|
||||
pub fn memory_usage() -> Option<String> { None }
|
||||
|
||||
pub fn memory_stats(opts: &str) -> Option<String> {
|
||||
@@ -117,6 +132,12 @@ pub fn memory_stats(opts: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
unsafe extern "C" fn malloc_stats_cb(opaque: *mut c_void, msg: *const c_char) {
|
||||
catch_unwind(move || handle_malloc_stats(opaque, msg))
|
||||
.map_err(|_| abort())
|
||||
.ok();
|
||||
}
|
||||
|
||||
fn handle_malloc_stats(opaque: *mut c_void, msg: *const c_char) {
|
||||
// SAFETY: we have to trust the opaque points to our String
|
||||
let res: &mut String = unsafe {
|
||||
opaque
|
||||
@@ -132,6 +153,43 @@ unsafe extern "C" fn malloc_stats_cb(opaque: *mut c_void, msg: *const c_char) {
|
||||
res.push_str(msg.as_ref());
|
||||
}
|
||||
|
||||
fn global_alloc_hook(layout: Layout) {
|
||||
catch_unwind(move || handle_global_alloc(layout))
|
||||
.map_err(|_| abort())
|
||||
.ok();
|
||||
}
|
||||
|
||||
fn global_alloc_zeroed_hook(layout: Layout) {
|
||||
catch_unwind(move || handle_global_alloc(layout))
|
||||
.map_err(|_| abort())
|
||||
.ok();
|
||||
}
|
||||
|
||||
fn handle_global_alloc(layout: Layout) {
|
||||
use std::io::Write;
|
||||
|
||||
use libc::{STDOUT_FILENO, write};
|
||||
|
||||
let do_count = COUNT_GLOBAL_ALLOCS.load(Ordering::Relaxed);
|
||||
let count = GLOBAL_ALLOCS.fetch_add(do_count.into(), Ordering::Relaxed);
|
||||
|
||||
if TRACE_GLOBAL_ALLOCS.load(Ordering::Relaxed) {
|
||||
let mut buf = ArrayVec::<u8, 128>::new();
|
||||
writeln!(&mut buf, "{count} align={} size={}", layout.align(), layout.size())
|
||||
.expect("writeln! to buffer failed");
|
||||
|
||||
// SAFETY: Valid ptr and len from buf for writing to stdout.
|
||||
unsafe { write(STDOUT_FILENO, buf.as_ptr().cast::<c_void>(), buf.len()) }
|
||||
.ge(&0)
|
||||
.into_result()
|
||||
.expect("write(2) error");
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[must_use]
|
||||
pub fn global_alloc_count() -> u64 { GLOBAL_ALLOCS.load(Ordering::Relaxed) }
|
||||
|
||||
macro_rules! mallctl {
|
||||
($name:expr_2021) => {{
|
||||
thread_local! {
|
||||
@@ -339,7 +397,7 @@ fn set<T>(key: &Key, val: T) -> Result<T>
|
||||
where
|
||||
T: Copy + Debug,
|
||||
{
|
||||
let _lock = CONTROL.write()?;
|
||||
let _lock = CONTROL.lock()?;
|
||||
let res = xchg(key, val)?;
|
||||
inc_epoch()?;
|
||||
|
||||
@@ -357,7 +415,6 @@ where
|
||||
T: Copy + Debug,
|
||||
{
|
||||
acq_epoch()?;
|
||||
acq_epoch()?;
|
||||
|
||||
// SAFETY: T must be perfectly valid to receive value.
|
||||
unsafe { mallctl::raw::read_mib(key.as_slice()) }.map_err(map_err)
|
||||
@@ -401,6 +458,4 @@ fn name(name: &str) -> Result<Name> {
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
fn map_err(error: tikv_jemalloc_ctl::Error) -> crate::Error {
|
||||
err!("mallctl: {}", error.to_string())
|
||||
}
|
||||
fn map_err(error: jemalloc::ctl::Error) -> crate::Error { err!("mallctl: {}", error.to_string()) }
|
||||
+67
-6
@@ -912,6 +912,26 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub log_to_stderr: bool,
|
||||
|
||||
/// Setting to false disables the logging/tracing system at a lower level.
|
||||
/// In contrast to configuring an empty `log` string where the system is
|
||||
/// still operating but muted, when this option is false the system was not
|
||||
/// initialized and is not operating. Changing this option has no effect
|
||||
/// after startup. This option is intended for developers and expert use
|
||||
/// only: configuring an empty log string is preferred over using this.
|
||||
///
|
||||
/// default: true
|
||||
#[serde(default = "true_fn")]
|
||||
pub log_enable: bool,
|
||||
|
||||
/// Setting to false disables the logging/tracing system at a lower level
|
||||
/// similar to `log_enable`. In this case the system is configured normally,
|
||||
/// but not registered as the global handler in the final steps. This option
|
||||
/// is for developers and expert use only.
|
||||
///
|
||||
/// default: true
|
||||
#[serde(default = "true_fn")]
|
||||
pub log_global_default: bool,
|
||||
|
||||
/// OpenID token expiration/TTL in seconds.
|
||||
///
|
||||
/// These are the OpenID tokens that are primarily used for Matrix account
|
||||
@@ -986,7 +1006,7 @@ pub struct Config {
|
||||
///
|
||||
/// display: sensitive
|
||||
#[serde(default)]
|
||||
pub turn_secret: String,
|
||||
pub turn_secret: Option<String>,
|
||||
|
||||
/// TURN secret to use that's read from the file path specified.
|
||||
///
|
||||
@@ -1336,6 +1356,17 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub push_everything: bool,
|
||||
|
||||
/// Setting to false disables the heroes calculation made by sliding and
|
||||
/// legacy client sync. The heroes calculation is mandated by the Matrix
|
||||
/// specification and your client may not operate properly unless this
|
||||
/// option is set to true.
|
||||
///
|
||||
/// This option is intended for custom software deployments seeking purely
|
||||
/// to minimize unused resources; the overall savings are otherwise
|
||||
/// negligible.
|
||||
#[serde(default = "true_fn")]
|
||||
pub calculate_heroes: bool,
|
||||
|
||||
/// Allow local (your server only) presence updates/requests.
|
||||
///
|
||||
/// Note that presence on tuwunel is very fast unlike Synapse's. If using
|
||||
@@ -1726,6 +1757,26 @@ pub struct Config {
|
||||
)]
|
||||
pub deprioritize_joins_through_servers: RegexSet,
|
||||
|
||||
/// Maximum make_join requests to attempt within each join attempt. Each
|
||||
/// attempt tries a different server, as each server is only tried once;
|
||||
/// though retries can occur when the join request as a whole is retried.
|
||||
///
|
||||
/// default: 48
|
||||
#[serde(default = "default_max_make_join_attempts_per_join_attempt")]
|
||||
pub max_make_join_attempts_per_join_attempt: usize,
|
||||
|
||||
/// Maximum join attempts to conduct per client join request. Each join
|
||||
/// attempt consists of one or more make_join requests limited above, and a
|
||||
/// single send_join request. This value allows for additional servers to
|
||||
/// act as the join-server prior to reporting the last error back to the
|
||||
/// client, which can be frustrating for users. Therefor the default value
|
||||
/// is greater than one, but less than excessively exceeding the client's
|
||||
/// request timeout, though that may not be avoidable in some cases.
|
||||
///
|
||||
/// default: 3
|
||||
#[serde(default = "default_max_join_attempts_per_join_request")]
|
||||
pub max_join_attempts_per_join_request: usize,
|
||||
|
||||
/// Retry failed and incomplete messages to remote servers immediately upon
|
||||
/// startup. This is called bursting. If this is disabled, said messages may
|
||||
/// not be delivered until more messages are queued for that server. Do not
|
||||
@@ -2033,6 +2084,17 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub allow_invalid_tls_certificates: bool,
|
||||
|
||||
/// Sets the `Access-Control-Allow-Origin` header included by this server in
|
||||
/// all responses. A list of multiple values can be specified. The default
|
||||
/// is an empty list. The actual header defaults to `*` upon an empty list.
|
||||
///
|
||||
/// There is no reason to configure this without specific intent. Incorrect
|
||||
/// values may degrade or disrupt clients.
|
||||
///
|
||||
/// default: []
|
||||
#[serde(default)]
|
||||
pub access_control_allow_origin: BTreeSet<String>,
|
||||
|
||||
/// Backport state-reset security fixes to all room versions.
|
||||
///
|
||||
/// This option applies the State Resolution 2.1 mitigation developed during
|
||||
@@ -2049,11 +2111,6 @@ pub struct Config {
|
||||
///
|
||||
/// This option exists for developer and debug use, and as a failsafe in
|
||||
/// lieu of hardcoding it.
|
||||
///
|
||||
/// This currently defaults to false as a matter of development until
|
||||
/// real-world testing can shake out any implementation issues rather than
|
||||
/// jeopardize existing rooms, but otherwise will default to true at the
|
||||
/// next point release or patch.
|
||||
#[serde(default = "true_fn")]
|
||||
pub hydra_backports: bool,
|
||||
|
||||
@@ -2955,3 +3012,7 @@ fn default_deprioritize_joins_through_servers() -> RegexSet {
|
||||
}
|
||||
|
||||
fn default_one_time_key_limit() -> usize { 256 }
|
||||
|
||||
fn default_max_make_join_attempts_per_join_attempt() -> usize { 48 }
|
||||
|
||||
fn default_max_join_attempts_per_join_request() -> usize { 3 }
|
||||
+1
-1
@@ -95,7 +95,7 @@ pub fn trap() {
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn panic_str(p: &Box<dyn Any + Send>) -> &'static str {
|
||||
pub fn panic_str(p: &Box<dyn Any + Send + 'static>) -> &'static str {
|
||||
(**p)
|
||||
.downcast_ref::<&str>()
|
||||
.copied()
|
||||
|
||||
+27
-11
@@ -4,16 +4,22 @@ mod panic;
|
||||
mod response;
|
||||
mod serde;
|
||||
|
||||
use std::{any::Any, borrow::Cow, convert::Infallible, sync::PoisonError};
|
||||
use std::{
|
||||
any::Any,
|
||||
borrow::Cow,
|
||||
convert::Infallible,
|
||||
sync::{Mutex, PoisonError},
|
||||
};
|
||||
|
||||
pub use self::{err::visit, log::*};
|
||||
use crate::utils::{assert_ref_unwind_safe, assert_send, assert_sync, assert_unwind_safe};
|
||||
|
||||
#[derive(thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("PANIC!")]
|
||||
PanicAny(Box<dyn Any + Send>),
|
||||
PanicAny(Mutex<Box<dyn Any + Send>>),
|
||||
#[error("PANIC! {0}")]
|
||||
Panic(&'static str, Box<dyn Any + Send + 'static>),
|
||||
Panic(&'static str, Mutex<Box<dyn Any + Send + 'static>>),
|
||||
|
||||
// std
|
||||
#[error(transparent)]
|
||||
@@ -27,7 +33,7 @@ pub enum Error {
|
||||
#[error(transparent)]
|
||||
ParseInt(#[from] std::num::ParseIntError),
|
||||
#[error(transparent)]
|
||||
Std(#[from] Box<dyn std::error::Error + Send>),
|
||||
Std(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),
|
||||
#[error(transparent)]
|
||||
SystemTime(#[from] std::time::SystemTimeError),
|
||||
#[error(transparent)]
|
||||
@@ -136,6 +142,11 @@ pub enum Error {
|
||||
Err(Cow<'static, str>),
|
||||
}
|
||||
|
||||
static _IS_SEND: () = assert_send::<Error>();
|
||||
static _IS_SYNC: () = assert_sync::<Error>();
|
||||
static _IS_UNWIND_SAFE: () = assert_unwind_safe::<Error>();
|
||||
static _IS_REF_UNWIND_SAFE: () = assert_ref_unwind_safe::<Error>();
|
||||
|
||||
impl Error {
|
||||
#[inline]
|
||||
#[must_use]
|
||||
@@ -167,13 +178,14 @@ impl Error {
|
||||
/// Returns the Matrix error code / error kind
|
||||
#[inline]
|
||||
pub fn kind(&self) -> ruma::api::client::error::ErrorKind {
|
||||
use ruma::api::client::error::ErrorKind::{FeatureDisabled, Unknown};
|
||||
use ruma::api::client::error::ErrorKind::{FeatureDisabled, NotJson, Unknown};
|
||||
|
||||
match self {
|
||||
| Self::FeatureDisabled(..) => FeatureDisabled,
|
||||
| Self::CanonicalJson(..) | Self::Json(..) => NotJson,
|
||||
| Self::BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
|
||||
| Self::Federation(_, error) | Self::Ruma(error) =>
|
||||
response::ruma_error_kind(error).clone(),
|
||||
| Self::BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
|
||||
| Self::FeatureDisabled(..) => FeatureDisabled,
|
||||
| _ => Unknown,
|
||||
}
|
||||
}
|
||||
@@ -184,15 +196,19 @@ impl Error {
|
||||
use http::StatusCode;
|
||||
|
||||
match self {
|
||||
| Self::Conflict(_) => StatusCode::CONFLICT, // room alias exists
|
||||
| Self::Federation(_, error) | Self::Ruma(error) => error.status_code,
|
||||
| Self::Request(kind, _, code) => response::status_code(kind, *code),
|
||||
| Self::FeatureDisabled(..)
|
||||
| Self::CanonicalJson(..)
|
||||
| Self::Json(..)
|
||||
| Self::JsParseInt(..)
|
||||
| Self::JsTryFromInt(..) => response::bad_request_code(&self.kind()),
|
||||
| Self::BadRequest(kind, ..) => response::bad_request_code(kind),
|
||||
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
|
||||
| Self::Request(kind, _, code) => response::status_code(kind, *code),
|
||||
| Self::Io(error) => response::io_error_code(error.kind()),
|
||||
| Self::Reqwest(error) => error
|
||||
.status()
|
||||
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
| Self::Conflict(_) => StatusCode::CONFLICT,
|
||||
| Self::Io(error) => response::io_error_code(error.kind()),
|
||||
| _ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
+11
-6
@@ -15,13 +15,16 @@ impl Error {
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn from_panic(e: Box<dyn Any + Send>) -> Self { Self::Panic(debug::panic_str(&e), e) }
|
||||
pub fn from_panic(e: Box<dyn Any + Send + 'static>) -> Self {
|
||||
Self::Panic(debug::panic_str(&e), e.into())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn into_panic(self) -> Box<dyn Any + Send + 'static> {
|
||||
pub fn into_panic(self) -> Box<dyn Any + Send> {
|
||||
match self {
|
||||
| Self::Panic(_, e) | Self::PanicAny(e) => e,
|
||||
| Self::JoinError(e) => e.into_panic(),
|
||||
| Self::Panic(_, e) | Self::PanicAny(e) =>
|
||||
e.into_inner().expect("Error contained panic"),
|
||||
| _ => Box::new(self),
|
||||
}
|
||||
}
|
||||
@@ -29,16 +32,18 @@ impl Error {
|
||||
/// Get the panic message string.
|
||||
#[inline]
|
||||
pub fn panic_str(self) -> Option<&'static str> {
|
||||
self.is_panic()
|
||||
.then_some(debug::panic_str(&self.into_panic()))
|
||||
self.is_panic().then(|| {
|
||||
let panic = self.into_panic();
|
||||
debug::panic_str(&panic)
|
||||
})
|
||||
}
|
||||
|
||||
/// Check if the Error is trafficking a panic object.
|
||||
#[inline]
|
||||
pub fn is_panic(&self) -> bool {
|
||||
match &self {
|
||||
| Self::Panic(..) | Self::PanicAny(..) => true,
|
||||
| Self::JoinError(e) => e.is_panic(),
|
||||
| Self::Panic(..) | Self::PanicAny(..) => true,
|
||||
| _ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,11 +5,10 @@
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
mem::replace,
|
||||
sync::{Mutex, OnceLock},
|
||||
};
|
||||
|
||||
use crate::utils::exchange;
|
||||
|
||||
// Capture rustc version during compilation.
|
||||
tuwunel_macros::rustc_version! {}
|
||||
|
||||
@@ -54,7 +53,7 @@ fn append_features(features: &mut Vec<&'static str>, flags: &[&'static str]) {
|
||||
for flag in flags {
|
||||
let is_cfg = *flag == "--cfg";
|
||||
let is_feature = flag.starts_with("feature=");
|
||||
if exchange(&mut next_is_cfg, is_cfg) && is_feature {
|
||||
if replace(&mut next_is_cfg, is_cfg) && is_feature {
|
||||
if let Some(feature) = flag
|
||||
.split_once('=')
|
||||
.map(|(_, feature)| feature.trim_matches('"'))
|
||||
|
||||
+15
-7
@@ -8,23 +8,31 @@ pub mod fmt_span;
|
||||
mod reload;
|
||||
mod suppress;
|
||||
|
||||
pub use capture::Capture;
|
||||
pub use console::{ConsoleFormat, ConsoleWriter, is_systemd_mode};
|
||||
pub use reload::{LogLevelReloadHandles, ReloadHandle};
|
||||
pub use suppress::Suppress;
|
||||
pub use tracing::Level;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use tracing::{Level, subscriber::Subscriber};
|
||||
pub use tracing_core::{Event, Metadata};
|
||||
pub use tracing_subscriber::EnvFilter;
|
||||
|
||||
pub use self::{
|
||||
capture::Capture,
|
||||
console::{ConsoleFormat, ConsoleWriter, is_systemd_mode},
|
||||
reload::{LogLevelReloadHandles, ReloadHandle},
|
||||
suppress::Suppress,
|
||||
};
|
||||
|
||||
/// Logging subsystem. This is a singleton member of super::Server which holds
|
||||
/// all logging and tracing related state rather than shoving it all in
|
||||
/// super::Server directly.
|
||||
pub struct Log {
|
||||
pub struct Logging {
|
||||
/// Subscriber assigned to globals and defaults; may also be NoSubscriber.
|
||||
pub subscriber: Arc<dyn Subscriber + Send + Sync>,
|
||||
|
||||
/// General log level reload handles.
|
||||
pub reload: LogLevelReloadHandles,
|
||||
|
||||
/// Tracing capture state for ephemeral/oneshot uses.
|
||||
pub capture: std::sync::Arc<capture::State>,
|
||||
pub capture: Arc<capture::State>,
|
||||
}
|
||||
|
||||
// Wraps for logging macros. Use these macros rather than extern tracing:: or
|
||||
|
||||
+114
-132
@@ -1,4 +1,5 @@
|
||||
use ruma::{
|
||||
CanonicalJsonMemberOptional as JsonMember, CanonicalJsonMembersOptional as JsonMembers,
|
||||
events::{
|
||||
AnyMessageLikeEvent, AnyStateEvent, AnyStrippedStateEvent, AnySyncMessageLikeEvent,
|
||||
AnySyncStateEvent, AnySyncTimelineEvent, AnyTimelineEvent, StateEvent,
|
||||
@@ -6,7 +7,7 @@ use ruma::{
|
||||
},
|
||||
serde::Raw,
|
||||
};
|
||||
use serde_json::json;
|
||||
use serde_json::value::to_raw_value;
|
||||
|
||||
use super::{Event, redact};
|
||||
|
||||
@@ -22,25 +23,20 @@ impl<'a, E: Event> From<Ref<'a, E>> for Raw<AnySyncTimelineEvent> {
|
||||
fn from(event: Ref<'a, E>) -> Self {
|
||||
let event = event.0;
|
||||
let (redacts, content) = redact::copy(event);
|
||||
let mut json = json!({
|
||||
"content": content,
|
||||
"event_id": event.event_id(),
|
||||
"origin_server_ts": event.origin_server_ts(),
|
||||
"sender": event.sender(),
|
||||
"type": event.event_type(),
|
||||
});
|
||||
let members: [JsonMember<_>; _] = [
|
||||
("content", Some(content.into())),
|
||||
("event_id", Some(event.event_id().as_str().into())),
|
||||
("origin_server_ts", Some(event.origin_server_ts().get().into())),
|
||||
("redacts", redacts.map(|e| e.as_str().into())),
|
||||
("sender", Some(event.sender().as_str().into())),
|
||||
("state_key", event.state_key().map(Into::into)),
|
||||
("type", Some(event.event_type().to_string().into())),
|
||||
("unsigned", event.unsigned().map(Into::into)),
|
||||
];
|
||||
|
||||
if let Some(redacts) = redacts {
|
||||
json["redacts"] = json!(redacts);
|
||||
}
|
||||
if let Some(state_key) = event.state_key() {
|
||||
json["state_key"] = json!(state_key);
|
||||
}
|
||||
if let Some(unsigned) = event.unsigned() {
|
||||
json["unsigned"] = json!(unsigned);
|
||||
}
|
||||
|
||||
serde_json::from_value(json).expect("Failed to serialize Event value")
|
||||
to_raw_value(&JsonMembers(&members))
|
||||
.map(Self::from_json)
|
||||
.expect("Failed to serialize Event value")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,26 +48,21 @@ impl<'a, E: Event> From<Ref<'a, E>> for Raw<AnyTimelineEvent> {
|
||||
fn from(event: Ref<'a, E>) -> Self {
|
||||
let event = event.0;
|
||||
let (redacts, content) = redact::copy(event);
|
||||
let mut json = json!({
|
||||
"content": content,
|
||||
"event_id": event.event_id(),
|
||||
"origin_server_ts": event.origin_server_ts(),
|
||||
"room_id": event.room_id(),
|
||||
"sender": event.sender(),
|
||||
"type": event.kind(),
|
||||
});
|
||||
let members: [JsonMember<_>; _] = [
|
||||
("content", Some(content.into())),
|
||||
("event_id", Some(event.event_id().as_str().into())),
|
||||
("origin_server_ts", Some(event.origin_server_ts().get().into())),
|
||||
("redacts", redacts.map(|e| e.as_str().into())),
|
||||
("room_id", Some(event.room_id().as_str().into())),
|
||||
("sender", Some(event.sender().as_str().into())),
|
||||
("state_key", event.state_key().map(Into::into)),
|
||||
("type", Some(event.event_type().to_string().into())),
|
||||
("unsigned", event.unsigned().map(Into::into)),
|
||||
];
|
||||
|
||||
if let Some(redacts) = redacts {
|
||||
json["redacts"] = json!(redacts);
|
||||
}
|
||||
if let Some(state_key) = event.state_key() {
|
||||
json["state_key"] = json!(state_key);
|
||||
}
|
||||
if let Some(unsigned) = event.unsigned() {
|
||||
json["unsigned"] = json!(unsigned);
|
||||
}
|
||||
|
||||
serde_json::from_value(json).expect("Failed to serialize Event value")
|
||||
to_raw_value(&JsonMembers(&members))
|
||||
.map(Self::from_json)
|
||||
.expect("Failed to serialize Event value")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,26 +74,21 @@ impl<'a, E: Event> From<Ref<'a, E>> for Raw<AnyMessageLikeEvent> {
|
||||
fn from(event: Ref<'a, E>) -> Self {
|
||||
let event = event.0;
|
||||
let (redacts, content) = redact::copy(event);
|
||||
let mut json = json!({
|
||||
"content": content,
|
||||
"event_id": event.event_id(),
|
||||
"origin_server_ts": event.origin_server_ts(),
|
||||
"room_id": event.room_id(),
|
||||
"sender": event.sender(),
|
||||
"type": event.kind(),
|
||||
});
|
||||
let members: [JsonMember<_>; _] = [
|
||||
("content", Some(content.into())),
|
||||
("event_id", Some(event.event_id().as_str().into())),
|
||||
("origin_server_ts", Some(event.origin_server_ts().get().into())),
|
||||
("redacts", redacts.map(|e| e.as_str().into())),
|
||||
("room_id", Some(event.room_id().as_str().into())),
|
||||
("sender", Some(event.sender().as_str().into())),
|
||||
("state_key", event.state_key().map(Into::into)),
|
||||
("type", Some(event.event_type().to_string().into())),
|
||||
("unsigned", event.unsigned().map(Into::into)),
|
||||
];
|
||||
|
||||
if let Some(redacts) = &redacts {
|
||||
json["redacts"] = json!(redacts);
|
||||
}
|
||||
if let Some(state_key) = event.state_key() {
|
||||
json["state_key"] = json!(state_key);
|
||||
}
|
||||
if let Some(unsigned) = event.unsigned() {
|
||||
json["unsigned"] = json!(unsigned);
|
||||
}
|
||||
|
||||
serde_json::from_value(json).expect("Failed to serialize Event value")
|
||||
to_raw_value(&JsonMembers(&members))
|
||||
.map(Self::from_json)
|
||||
.expect("Failed to serialize Event value")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,25 +100,20 @@ impl<'a, E: Event> From<Ref<'a, E>> for Raw<AnySyncMessageLikeEvent> {
|
||||
fn from(event: Ref<'a, E>) -> Self {
|
||||
let event = event.0;
|
||||
let (redacts, content) = redact::copy(event);
|
||||
let mut json = json!({
|
||||
"content": content,
|
||||
"event_id": event.event_id(),
|
||||
"origin_server_ts": event.origin_server_ts(),
|
||||
"sender": event.sender(),
|
||||
"type": event.kind(),
|
||||
});
|
||||
let members: [JsonMember<_>; _] = [
|
||||
("content", Some(content.into())),
|
||||
("event_id", Some(event.event_id().as_str().into())),
|
||||
("origin_server_ts", Some(event.origin_server_ts().get().into())),
|
||||
("redacts", redacts.map(|e| e.as_str().into())),
|
||||
("sender", Some(event.sender().as_str().into())),
|
||||
("state_key", event.state_key().map(Into::into)),
|
||||
("type", Some(event.event_type().to_string().into())),
|
||||
("unsigned", event.unsigned().map(Into::into)),
|
||||
];
|
||||
|
||||
if let Some(redacts) = &redacts {
|
||||
json["redacts"] = json!(redacts);
|
||||
}
|
||||
if let Some(state_key) = event.state_key() {
|
||||
json["state_key"] = json!(state_key);
|
||||
}
|
||||
if let Some(unsigned) = event.unsigned() {
|
||||
json["unsigned"] = json!(unsigned);
|
||||
}
|
||||
|
||||
serde_json::from_value(json).expect("Failed to serialize Event value")
|
||||
to_raw_value(&JsonMembers(&members))
|
||||
.map(Self::from_json)
|
||||
.expect("Failed to serialize Event value")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,21 +124,20 @@ impl<E: Event> From<Owned<E>> for Raw<AnyStateEvent> {
|
||||
impl<'a, E: Event> From<Ref<'a, E>> for Raw<AnyStateEvent> {
|
||||
fn from(event: Ref<'a, E>) -> Self {
|
||||
let event = event.0;
|
||||
let mut json = json!({
|
||||
"content": event.content(),
|
||||
"event_id": event.event_id(),
|
||||
"origin_server_ts": event.origin_server_ts(),
|
||||
"room_id": event.room_id(),
|
||||
"sender": event.sender(),
|
||||
"state_key": event.state_key(),
|
||||
"type": event.kind(),
|
||||
});
|
||||
let members: [JsonMember<_>; _] = [
|
||||
("content", Some(event.content().into())),
|
||||
("event_id", Some(event.event_id().as_str().into())),
|
||||
("origin_server_ts", Some(event.origin_server_ts().get().into())),
|
||||
("room_id", Some(event.room_id().as_str().into())),
|
||||
("sender", Some(event.sender().as_str().into())),
|
||||
("state_key", event.state_key().map(Into::into)),
|
||||
("type", Some(event.event_type().to_string().into())),
|
||||
("unsigned", event.unsigned().map(Into::into)),
|
||||
];
|
||||
|
||||
if let Some(unsigned) = event.unsigned() {
|
||||
json["unsigned"] = json!(unsigned);
|
||||
}
|
||||
|
||||
serde_json::from_value(json).expect("Failed to serialize Event value")
|
||||
to_raw_value(&JsonMembers(&members))
|
||||
.map(Self::from_json)
|
||||
.expect("Failed to serialize Event value")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,20 +148,19 @@ impl<E: Event> From<Owned<E>> for Raw<AnySyncStateEvent> {
|
||||
impl<'a, E: Event> From<Ref<'a, E>> for Raw<AnySyncStateEvent> {
|
||||
fn from(event: Ref<'a, E>) -> Self {
|
||||
let event = event.0;
|
||||
let mut json = json!({
|
||||
"content": event.content(),
|
||||
"event_id": event.event_id(),
|
||||
"origin_server_ts": event.origin_server_ts(),
|
||||
"sender": event.sender(),
|
||||
"state_key": event.state_key(),
|
||||
"type": event.kind(),
|
||||
});
|
||||
let members: [JsonMember<_>; _] = [
|
||||
("content", Some(event.content().into())),
|
||||
("event_id", Some(event.event_id().as_str().into())),
|
||||
("origin_server_ts", Some(event.origin_server_ts().get().into())),
|
||||
("sender", Some(event.sender().as_str().into())),
|
||||
("state_key", event.state_key().map(Into::into)),
|
||||
("type", Some(event.event_type().to_string().into())),
|
||||
("unsigned", event.unsigned().map(Into::into)),
|
||||
];
|
||||
|
||||
if let Some(unsigned) = event.unsigned() {
|
||||
json["unsigned"] = json!(unsigned);
|
||||
}
|
||||
|
||||
serde_json::from_value(json).expect("Failed to serialize Event value")
|
||||
to_raw_value(&JsonMembers(&members))
|
||||
.map(Self::from_json)
|
||||
.expect("Failed to serialize Event value")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,14 +171,16 @@ impl<E: Event> From<Owned<E>> for Raw<AnyStrippedStateEvent> {
|
||||
impl<'a, E: Event> From<Ref<'a, E>> for Raw<AnyStrippedStateEvent> {
|
||||
fn from(event: Ref<'a, E>) -> Self {
|
||||
let event = event.0;
|
||||
let json = json!({
|
||||
"content": event.content(),
|
||||
"sender": event.sender(),
|
||||
"state_key": event.state_key(),
|
||||
"type": event.kind(),
|
||||
});
|
||||
let members: [JsonMember<_>; _] = [
|
||||
("content", Some(event.content().into())),
|
||||
("sender", Some(event.sender().as_str().into())),
|
||||
("state_key", event.state_key().map(Into::into)),
|
||||
("type", Some(event.event_type().to_string().into())),
|
||||
];
|
||||
|
||||
serde_json::from_value(json).expect("Failed to serialize Event value")
|
||||
to_raw_value(&JsonMembers(&members))
|
||||
.map(Self::from_json)
|
||||
.expect("Failed to serialize Event value")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,15 +191,17 @@ impl<E: Event> From<Owned<E>> for Raw<HierarchySpaceChildEvent> {
|
||||
impl<'a, E: Event> From<Ref<'a, E>> for Raw<HierarchySpaceChildEvent> {
|
||||
fn from(event: Ref<'a, E>) -> Self {
|
||||
let event = event.0;
|
||||
let json = json!({
|
||||
"content": event.content(),
|
||||
"origin_server_ts": event.origin_server_ts(),
|
||||
"sender": event.sender(),
|
||||
"state_key": event.state_key(),
|
||||
"type": event.kind(),
|
||||
});
|
||||
let members: [JsonMember<_>; _] = [
|
||||
("content", Some(event.content().into())),
|
||||
("origin_server_ts", Some(event.origin_server_ts().get().into())),
|
||||
("sender", Some(event.sender().as_str().into())),
|
||||
("state_key", event.state_key().map(Into::into)),
|
||||
("type", Some(event.event_type().to_string().into())),
|
||||
];
|
||||
|
||||
serde_json::from_value(json).expect("Failed to serialize Event value")
|
||||
to_raw_value(&JsonMembers(&members))
|
||||
.map(Self::from_json)
|
||||
.expect("Failed to serialize Event value")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,21 +212,20 @@ impl<E: Event> From<Owned<E>> for Raw<StateEvent<RoomMemberEventContent>> {
|
||||
impl<'a, E: Event> From<Ref<'a, E>> for Raw<StateEvent<RoomMemberEventContent>> {
|
||||
fn from(event: Ref<'a, E>) -> Self {
|
||||
let event = event.0;
|
||||
let mut json = json!({
|
||||
"content": event.content(),
|
||||
"event_id": event.event_id(),
|
||||
"origin_server_ts": event.origin_server_ts(),
|
||||
"redacts": event.redacts(),
|
||||
"room_id": event.room_id(),
|
||||
"sender": event.sender(),
|
||||
"state_key": event.state_key(),
|
||||
"type": event.kind(),
|
||||
});
|
||||
let members: [JsonMember<_>; _] = [
|
||||
("content", Some(event.content().into())),
|
||||
("event_id", Some(event.event_id().as_str().into())),
|
||||
("origin_server_ts", Some(event.origin_server_ts().get().into())),
|
||||
("redacts", event.redacts().map(|e| e.as_str().into())),
|
||||
("room_id", Some(event.room_id().as_str().into())),
|
||||
("sender", Some(event.sender().as_str().into())),
|
||||
("state_key", event.state_key().map(Into::into)),
|
||||
("type", Some(event.event_type().to_string().into())),
|
||||
("unsigned", event.unsigned().map(Into::into)),
|
||||
];
|
||||
|
||||
if let Some(unsigned) = event.unsigned() {
|
||||
json["unsigned"] = json!(unsigned);
|
||||
}
|
||||
|
||||
serde_json::from_value(json).expect("Failed to serialize Event value")
|
||||
to_raw_value(&JsonMembers(&members))
|
||||
.map(Self::from_json)
|
||||
.expect("Failed to serialize Event value")
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use ruma::{
|
||||
use crate::{
|
||||
Result, extract_variant, is_equal_to,
|
||||
matrix::{PduEvent, room_version},
|
||||
state_res::{self},
|
||||
};
|
||||
|
||||
pub fn into_outgoing_federation(
|
||||
@@ -95,6 +96,8 @@ pub fn from_incoming_federation(
|
||||
pdu_json.insert("event_id".into(), CanonicalJsonValue::String(event_id.into()));
|
||||
}
|
||||
|
||||
state_res::check_pdu_format(pdu_json, &room_rules.event_format)?;
|
||||
|
||||
PduEvent::from_val(pdu_json)
|
||||
}
|
||||
|
||||
|
||||
@@ -37,9 +37,7 @@ pub fn check_pdu_format(pdu: &CanonicalJsonObject, rules: &EventFormatRules) ->
|
||||
.map_err(|e| err!(Request(BadJson("Failed to serialize canonical JSON: {e}"))))?;
|
||||
|
||||
if json.len() > MAX_PDU_BYTES {
|
||||
return Err!(Request(InvalidParam(
|
||||
"PDU is larger than maximum of {MAX_PDU_BYTES} bytes"
|
||||
)));
|
||||
return Err!(Request(TooLarge("PDU is larger than maximum of {MAX_PDU_BYTES} bytes")));
|
||||
}
|
||||
|
||||
// Check the presence, type and length of the `type` field.
|
||||
@@ -133,7 +131,7 @@ fn extract_optional_string_field<'a>(
|
||||
match object.get(field) {
|
||||
| Some(CanonicalJsonValue::String(value)) =>
|
||||
if value.len() > ID_MAX_BYTES {
|
||||
Err!(Request(InvalidParam(
|
||||
Err!(Request(TooLarge(
|
||||
"invalid `{field}` field in PDU: string length is larger than maximum of \
|
||||
{ID_MAX_BYTES} bytes"
|
||||
)))
|
||||
@@ -177,7 +175,7 @@ fn extract_required_array_field<'a>(
|
||||
match object.get(field) {
|
||||
| Some(CanonicalJsonValue::Array(value)) =>
|
||||
if value.len() > max_len {
|
||||
Err!(Request(InvalidParam(
|
||||
Err!(Request(TooLarge(
|
||||
"invalid `{field}` field in PDU: array length is larger than maximum of \
|
||||
{max_len}"
|
||||
)))
|
||||
|
||||
+3
-3
@@ -9,7 +9,7 @@ use std::{
|
||||
use ruma::OwnedServerName;
|
||||
use tokio::{runtime, sync::broadcast};
|
||||
|
||||
use crate::{Err, Result, config, config::Config, log::Log, metrics::Metrics};
|
||||
use crate::{Err, Result, config, config::Config, log::Logging, metrics::Metrics};
|
||||
|
||||
/// Server runtime state; public portion
|
||||
pub struct Server {
|
||||
@@ -41,7 +41,7 @@ pub struct Server {
|
||||
pub signal: broadcast::Sender<&'static str>,
|
||||
|
||||
/// Logging subsystem state
|
||||
pub log: Log,
|
||||
pub log: Logging,
|
||||
|
||||
/// Metrics subsystem state
|
||||
pub metrics: Metrics,
|
||||
@@ -49,7 +49,7 @@ pub struct Server {
|
||||
|
||||
impl Server {
|
||||
#[must_use]
|
||||
pub fn new(config: Config, runtime: Option<runtime::Handle>, log: Log) -> Self {
|
||||
pub fn new(config: Config, runtime: Option<runtime::Handle>, log: Logging) -> Self {
|
||||
Self {
|
||||
name: config.server_name.clone(),
|
||||
config: config::Manager::new(config),
|
||||
|
||||
@@ -2,12 +2,16 @@ mod bool_ext;
|
||||
mod ext_ext;
|
||||
mod option_ext;
|
||||
mod option_stream;
|
||||
mod ready_bool_ext;
|
||||
mod ready_eq_ext;
|
||||
mod try_ext_ext;
|
||||
|
||||
pub use bool_ext::{BoolExt, and, and4, and5, and6, and7, or};
|
||||
pub use ext_ext::ExtExt;
|
||||
pub use option_ext::OptionExt;
|
||||
pub use option_stream::OptionStream;
|
||||
pub use ready_eq_ext::ReadyEqExt;
|
||||
pub use try_ext_ext::TryExtExt;
|
||||
pub use self::{
|
||||
bool_ext::{BoolExt, and, and4, and5, and6, and7, or},
|
||||
ext_ext::ExtExt,
|
||||
option_ext::OptionExt,
|
||||
option_stream::OptionStream,
|
||||
ready_bool_ext::ReadyBoolExt,
|
||||
ready_eq_ext::ReadyEqExt,
|
||||
try_ext_ext::TryExtExt,
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
#![allow(clippy::wrong_self_convention)]
|
||||
|
||||
use futures::Future;
|
||||
|
||||
use super::ReadyEqExt;
|
||||
|
||||
pub trait ReadyBoolExt
|
||||
where
|
||||
Self: Future<Output = bool> + ReadyEqExt<bool> + Send,
|
||||
{
|
||||
#[inline]
|
||||
fn is_false(self) -> impl Future<Output = bool> + Send { self.eq(&false) }
|
||||
|
||||
#[inline]
|
||||
fn is_true(self) -> impl Future<Output = bool> + Send { self.eq(&true) }
|
||||
}
|
||||
|
||||
impl<Fut> ReadyBoolExt for Fut where Fut: Future<Output = bool> + Send {}
|
||||
@@ -42,8 +42,13 @@ pub use self::{
|
||||
},
|
||||
};
|
||||
|
||||
#[inline]
|
||||
pub fn exchange<T>(state: &mut T, source: T) -> T { std::mem::replace(state, source) }
|
||||
pub const fn assert_send<T: Send>() {}
|
||||
pub const fn assert_sync<T: Sync>() {}
|
||||
pub const fn assert_dst<T: ?Sized>() {}
|
||||
pub const fn assert_sized<T: Sized>() {}
|
||||
pub const fn assert_unpin<T: Unpin>() {}
|
||||
pub const fn assert_unwind_safe<T: std::panic::UnwindSafe>() {}
|
||||
pub const fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! extract_variant {
|
||||
|
||||
@@ -9,10 +9,12 @@ use tokio::sync::OwnedMutexGuard as Omg;
|
||||
use crate::{Result, err};
|
||||
|
||||
/// Map of Mutexes
|
||||
#[derive(Debug)]
|
||||
pub struct MutexMap<Key, Val> {
|
||||
map: Map<Key, Val>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Guard<Key, Val> {
|
||||
map: Map<Key, Val>,
|
||||
val: Omg<Val>,
|
||||
|
||||
@@ -57,9 +57,10 @@ where
|
||||
/// Intersection of sets
|
||||
///
|
||||
/// Outputs the set of elements common to both streams. Streams must be sorted.
|
||||
pub fn intersection_sorted_stream2<Item, S>(a: S, b: S) -> impl Stream<Item = Item> + Send
|
||||
pub fn intersection_sorted_stream2<Item, A, B>(a: A, b: B) -> impl Stream<Item = Item> + Send
|
||||
where
|
||||
S: Stream<Item = Item> + Send + Unpin,
|
||||
A: Stream<Item = Item> + Send,
|
||||
B: Stream<Item = Item> + Send + Unpin,
|
||||
Item: Eq + PartialOrd + Send + Sync,
|
||||
{
|
||||
use tokio::sync::Mutex;
|
||||
@@ -86,9 +87,10 @@ where
|
||||
///
|
||||
/// Outputs the set of elements found in `a` which are not found in `b`. Streams
|
||||
/// must be sorted.
|
||||
pub fn difference_sorted_stream2<Item, S>(a: S, b: S) -> impl Stream<Item = Item> + Send
|
||||
pub fn difference_sorted_stream2<Item, A, B>(a: A, b: B) -> impl Stream<Item = Item> + Send
|
||||
where
|
||||
S: Stream<Item = Item> + Send + Unpin,
|
||||
A: Stream<Item = Item> + Send,
|
||||
B: Stream<Item = Item> + Send + Unpin,
|
||||
Item: Eq + PartialOrd + Send + Sync,
|
||||
{
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
@@ -2,25 +2,30 @@ use futures::{Stream, StreamExt, TryStream};
|
||||
|
||||
use crate::Result;
|
||||
|
||||
pub trait TryExpect<'a, Item> {
|
||||
fn expect_ok(self) -> impl Stream<Item = Item> + Send + 'a;
|
||||
pub trait TryExpect<Item>
|
||||
where
|
||||
Item: Send,
|
||||
Self: Send + Sized,
|
||||
{
|
||||
fn expect_ok(self) -> impl Stream<Item = Item> + Send;
|
||||
|
||||
fn map_expect(self, msg: &'a str) -> impl Stream<Item = Item> + Send + 'a;
|
||||
fn map_expect(self, msg: &str) -> impl Stream<Item = Item> + Send;
|
||||
}
|
||||
|
||||
impl<'a, T, Item> TryExpect<'a, Item> for T
|
||||
impl<Item, S> TryExpect<Item> for S
|
||||
where
|
||||
T: Stream<Item = Result<Item>> + Send + TryStream + 'a,
|
||||
Item: 'a,
|
||||
S: Stream<Item = Result<Item>> + Send + TryStream,
|
||||
Item: Send,
|
||||
Self: Send + Sized,
|
||||
{
|
||||
#[inline]
|
||||
fn expect_ok(self: T) -> impl Stream<Item = Item> + Send + 'a {
|
||||
fn expect_ok(self: S) -> impl Stream<Item = Item> + Send {
|
||||
self.map_expect("stream expectation failure")
|
||||
}
|
||||
|
||||
//TODO: move to impl MapExpect
|
||||
#[inline]
|
||||
fn map_expect(self, msg: &'a str) -> impl Stream<Item = Item> + Send + 'a {
|
||||
fn map_expect(self, msg: &str) -> impl Stream<Item = Item> + Send {
|
||||
self.map(|res| res.expect(msg))
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,35 @@
|
||||
use futures::{Stream, StreamExt, TryStream, future::ready};
|
||||
|
||||
use crate::{Error, Result};
|
||||
use crate::{Error, Result, utils::stream::TryExpect};
|
||||
|
||||
pub trait TryIgnore<'a, Item> {
|
||||
fn ignore_err(self) -> impl Stream<Item = Item> + Send + 'a;
|
||||
pub trait TryIgnore<Item>
|
||||
where
|
||||
Item: Send,
|
||||
Self: Send + Sized,
|
||||
{
|
||||
fn ignore_err(self) -> impl Stream<Item = Item> + Send;
|
||||
|
||||
fn ignore_ok(self) -> impl Stream<Item = Error> + Send + 'a;
|
||||
fn ignore_ok(self) -> impl Stream<Item = Error> + Send;
|
||||
}
|
||||
|
||||
impl<'a, T, Item> TryIgnore<'a, Item> for T
|
||||
impl<Item, S> TryIgnore<Item> for S
|
||||
where
|
||||
T: Stream<Item = Result<Item>> + TryStream + Send + 'a,
|
||||
Item: Send + 'a,
|
||||
S: Stream<Item = Result<Item>> + Send + TryStream + TryExpect<Item>,
|
||||
Item: Send,
|
||||
Self: Send + Sized,
|
||||
{
|
||||
#[cfg(debug_assertions)]
|
||||
#[inline]
|
||||
fn ignore_err(self: T) -> impl Stream<Item = Item> + Send + 'a {
|
||||
use super::TryExpect;
|
||||
|
||||
self.expect_ok()
|
||||
}
|
||||
fn ignore_err(self: S) -> impl Stream<Item = Item> + Send { self.expect_ok() }
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[inline]
|
||||
fn ignore_err(self: T) -> impl Stream<Item = Item> + Send + 'a {
|
||||
fn ignore_err(self: S) -> impl Stream<Item = Item> + Send {
|
||||
self.filter_map(|res| ready(res.ok()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn ignore_ok(self: T) -> impl Stream<Item = Error> + Send + 'a {
|
||||
fn ignore_ok(self: S) -> impl Stream<Item = Error> + Send {
|
||||
self.filter_map(|res| ready(res.err()))
|
||||
}
|
||||
}
|
||||
@@ -13,20 +13,22 @@ mod try_tools;
|
||||
mod try_wideband;
|
||||
mod wideband;
|
||||
|
||||
pub use band::{
|
||||
AMPLIFICATION_LIMIT, WIDTH_LIMIT, automatic_amplification, automatic_width,
|
||||
set_amplification, set_width,
|
||||
pub use self::{
|
||||
band::{
|
||||
AMPLIFICATION_LIMIT, WIDTH_LIMIT, automatic_amplification, automatic_width,
|
||||
set_amplification, set_width,
|
||||
},
|
||||
broadband::BroadbandExt,
|
||||
cloned::Cloned,
|
||||
expect::TryExpect,
|
||||
ignore::TryIgnore,
|
||||
iter_stream::IterStream,
|
||||
ready::ReadyExt,
|
||||
tools::Tools,
|
||||
try_broadband::TryBroadbandExt,
|
||||
try_parallel::TryParallelExt,
|
||||
try_ready::TryReadyExt,
|
||||
try_tools::TryTools,
|
||||
try_wideband::TryWidebandExt,
|
||||
wideband::WidebandExt,
|
||||
};
|
||||
pub use broadband::BroadbandExt;
|
||||
pub use cloned::Cloned;
|
||||
pub use expect::TryExpect;
|
||||
pub use ignore::TryIgnore;
|
||||
pub use iter_stream::IterStream;
|
||||
pub use ready::ReadyExt;
|
||||
pub use tools::Tools;
|
||||
pub use try_broadband::TryBroadbandExt;
|
||||
pub use try_parallel::TryParallelExt;
|
||||
pub use try_ready::TryReadyExt;
|
||||
pub use try_tools::TryTools;
|
||||
pub use try_wideband::TryWidebandExt;
|
||||
pub use wideband::WidebandExt;
|
||||
@@ -4,8 +4,10 @@ mod tests;
|
||||
mod unquote;
|
||||
mod unquoted;
|
||||
|
||||
use std::mem::replace;
|
||||
|
||||
pub use self::{between::Between, split::SplitInfallible, unquote::Unquote, unquoted::Unquoted};
|
||||
use crate::{Result, smallstr::SmallString, utils::exchange};
|
||||
use crate::{Result, smallstr::SmallString};
|
||||
|
||||
pub const EMPTY: &str = "";
|
||||
|
||||
@@ -76,7 +78,7 @@ where
|
||||
.map(char::from)
|
||||
.try_for_each(|ch| {
|
||||
let m = ch.is_ascii_uppercase();
|
||||
let s = exchange(&mut state, !m);
|
||||
let s = replace(&mut state, !m);
|
||||
if m && s {
|
||||
output.write_char('_')?;
|
||||
}
|
||||
|
||||
@@ -37,11 +37,10 @@ pub(crate) fn db_options(config: &Config, env: &Env, row_cache: &Cache) -> Resul
|
||||
opts.set_use_direct_io_for_flush_and_compaction(true);
|
||||
}
|
||||
if config.rocksdb_optimize_for_spinning_disks {
|
||||
// speeds up opening DB on hard drives
|
||||
opts.set_skip_checking_sst_file_sizes_on_db_open(true);
|
||||
opts.set_skip_stats_update_on_db_open(true);
|
||||
//opts.set_max_file_opening_threads(threads.try_into().unwrap());
|
||||
} else {
|
||||
opts.set_max_file_opening_threads(num_threads(config)?);
|
||||
opts.set_compaction_readahead_size(1024 * 512);
|
||||
}
|
||||
|
||||
@@ -123,7 +122,7 @@ fn set_logging_defaults(opts: &mut Options, config: &Config) {
|
||||
if config.rocksdb_log_stderr {
|
||||
opts.set_stderr_logger(rocksdb_log_level, "rocksdb");
|
||||
} else {
|
||||
opts.set_callback_logger(rocksdb_log_level, &handle_log);
|
||||
opts.set_callback_logger(rocksdb_log_level, handle_log);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-9
@@ -1,6 +1,9 @@
|
||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||
|
||||
use futures::{Future, FutureExt, TryFutureExt, future::ready};
|
||||
use futures::{
|
||||
Future, FutureExt, TryFutureExt,
|
||||
future::{Either, ready},
|
||||
};
|
||||
use rocksdb::{DBPinnableSlice, ReadOptions};
|
||||
use tokio::task;
|
||||
use tuwunel_core::{Err, Result, err, implement, utils::result::MapExpect};
|
||||
@@ -25,9 +28,9 @@ where
|
||||
|
||||
let cached = self.get_cached(key);
|
||||
if matches!(cached, Err(_) | Ok(Some(_))) {
|
||||
return task::consume_budget()
|
||||
.map(move |()| cached.map_expect("data found in cache"))
|
||||
.boxed();
|
||||
return Either::Left(
|
||||
task::consume_budget().map(move |()| cached.map_expect("data found in cache")),
|
||||
);
|
||||
}
|
||||
|
||||
debug_assert!(matches!(cached, Ok(None)), "expected status Incomplete");
|
||||
@@ -37,11 +40,12 @@ where
|
||||
res: None,
|
||||
};
|
||||
|
||||
self.engine
|
||||
.pool
|
||||
.execute_get(cmd)
|
||||
.and_then(|mut res| ready(res.remove(0)))
|
||||
.boxed()
|
||||
Either::Right(
|
||||
self.engine
|
||||
.pool
|
||||
.execute_get(cmd)
|
||||
.and_then(|mut res| ready(res.remove(0))),
|
||||
)
|
||||
}
|
||||
|
||||
/// Fetch a value from the cache without I/O.
|
||||
|
||||
@@ -50,12 +50,12 @@ where
|
||||
.widen_then(automatic_width(), |chunk| {
|
||||
self.engine.pool.execute_get(Get {
|
||||
map: self.clone(),
|
||||
res: None,
|
||||
key: chunk
|
||||
.iter()
|
||||
.map(AsRef::as_ref)
|
||||
.map(Into::into)
|
||||
.collect(),
|
||||
res: None,
|
||||
})
|
||||
})
|
||||
.map_ok(|results| results.into_iter().stream())
|
||||
|
||||
@@ -51,7 +51,7 @@ where
|
||||
let write_options = &self.write_options;
|
||||
self.engine
|
||||
.db
|
||||
.write_opt(batch, write_options)
|
||||
.write_opt(&batch, write_options)
|
||||
.or_else(or_else)
|
||||
.expect("database insert batch error");
|
||||
|
||||
|
||||
+15
-13
@@ -1,6 +1,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future::Either};
|
||||
use rocksdb::Direction;
|
||||
use serde::Deserialize;
|
||||
use tokio::task;
|
||||
@@ -27,11 +27,12 @@ pub fn raw_keys(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + Send
|
||||
let state = stream::State::new(self, opts);
|
||||
if is_cached(self) {
|
||||
let state = state.init_fwd(None);
|
||||
return task::consume_budget()
|
||||
.map(move |()| stream::Keys::<'_>::from(state))
|
||||
.into_stream()
|
||||
.flatten()
|
||||
.boxed();
|
||||
return Either::Left(
|
||||
task::consume_budget()
|
||||
.map(move |()| stream::Keys::<'_>::from(state))
|
||||
.into_stream()
|
||||
.flatten(),
|
||||
);
|
||||
}
|
||||
|
||||
let seek = Seek {
|
||||
@@ -42,11 +43,12 @@ pub fn raw_keys(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + Send
|
||||
res: None,
|
||||
};
|
||||
|
||||
self.engine
|
||||
.pool
|
||||
.execute_iter(seek)
|
||||
.ok_into::<stream::Keys<'_>>()
|
||||
.into_stream()
|
||||
.try_flatten()
|
||||
.boxed()
|
||||
Either::Right(
|
||||
self.engine
|
||||
.pool
|
||||
.execute_iter(seek)
|
||||
.ok_into::<stream::Keys<'_>>()
|
||||
.into_stream()
|
||||
.try_flatten(),
|
||||
)
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
use std::{convert::AsRef, fmt::Debug, sync::Arc};
|
||||
|
||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future::Either};
|
||||
use rocksdb::Direction;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::task;
|
||||
use tuwunel_core::{Result, implement};
|
||||
|
||||
use super::stream_from::is_cached;
|
||||
@@ -64,7 +65,13 @@ where
|
||||
let opts = super::iter_options_default(&self.engine);
|
||||
let state = stream::State::new(self, opts);
|
||||
if is_cached(self, from) {
|
||||
return stream::Keys::<'_>::from(state.init_fwd(from.as_ref().into())).boxed();
|
||||
let state = state.init_fwd(from.as_ref().into());
|
||||
return Either::Left(
|
||||
task::consume_budget()
|
||||
.map(move |()| stream::Keys::<'_>::from(state))
|
||||
.into_stream()
|
||||
.flatten(),
|
||||
);
|
||||
}
|
||||
|
||||
let seek = Seek {
|
||||
@@ -75,11 +82,12 @@ where
|
||||
res: None,
|
||||
};
|
||||
|
||||
self.engine
|
||||
.pool
|
||||
.execute_iter(seek)
|
||||
.ok_into::<stream::Keys<'_>>()
|
||||
.into_stream()
|
||||
.try_flatten()
|
||||
.boxed()
|
||||
Either::Right(
|
||||
self.engine
|
||||
.pool
|
||||
.execute_iter(seek)
|
||||
.ok_into::<stream::Keys<'_>>()
|
||||
.into_stream()
|
||||
.try_flatten(),
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt};
|
||||
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future::Either};
|
||||
use rocksdb::Direction;
|
||||
use serde::Deserialize;
|
||||
use tokio::task;
|
||||
@@ -27,11 +27,12 @@ pub fn rev_raw_keys(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + S
|
||||
let state = stream::State::new(self, opts);
|
||||
if is_cached(self) {
|
||||
let state = state.init_rev(None);
|
||||
return task::consume_budget()
|
||||
.map(move |()| stream::KeysRev::<'_>::from(state))
|
||||
.into_stream()
|
||||
.flatten()
|
||||
.boxed();
|
||||
return Either::Left(
|
||||
task::consume_budget()
|
||||
.map(move |()| stream::KeysRev::<'_>::from(state))
|
||||
.into_stream()
|
||||
.flatten(),
|
||||
);
|
||||
}
|
||||
|
||||
let seek = Seek {
|
||||
@@ -42,11 +43,12 @@ pub fn rev_raw_keys(self: &Arc<Self>) -> impl Stream<Item = Result<Key<'_>>> + S
|
||||
res: None,
|
||||
};
|
||||
|
||||
self.engine
|
||||
.pool
|
||||
.execute_iter(seek)
|
||||
.ok_into::<stream::KeysRev<'_>>()
|
||||
.into_stream()
|
||||
.try_flatten()
|
||||
.boxed()
|
||||
Either::Right(
|
||||
self.engine
|
||||
.pool
|
||||
.execute_iter(seek)
|
||||
.ok_into::<stream::KeysRev<'_>>()
|
||||
.into_stream()
|
||||
.try_flatten(),
|
||||
)
|
||||
}
|
||||
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user