Compare commits

..
Author SHA1 Message Date
Jacob Taylor 8ebf0a11fa feat: Rendezvous-y 2026-11-23 15:03:06 -08:00
Jacob Taylor 45cefde919 feat: Continuwuity Notarizes the Notary 2026-11-23 15:02:41 -08:00
Erwan Leboucher 17b05974e2 fix(federation): Send a read receipt for each thread 2026-11-23 14:44:44 -08:00
Jacob Taylor 38ac8f5e13 fix: Complete ripping hardened malloc out 2026-11-23 14:44:44 -08:00
Jacob Taylor b5a4f85ef6 chore: No Auth Media, No UnAuth Profiles 2026-11-23 14:44:44 -08:00
Jacob Taylor 84037431b9 Chore: Revert "chore(deps): Upgrade rocksdb and jemalloc", and add cargo.lock changes clippy discovered
This reverts commit 1af92add88.
This reverts commit 779374bb54.

chore(deps): update rust crate syn to v3.0.10

chore: Fix Clippy
2026-11-23 14:44:44 -08:00
Jacob Taylor 0930738140 feat: Enable converged 6g at the edge in continuwuity 2026-11-23 14:43:30 -08:00
Jacob Taylor 40fba31500 chore: Commit basic QoDana config for local QA usage 2026-11-23 14:43:30 -08:00
Jacob Taylor dde062d857 fix: Delete silly 2026-11-23 14:43:30 -08:00
Jacob Taylor 0c50835932 chore: Fix some clippy lints 2026-11-23 14:43:30 -08:00
Jacob Taylor de844be77f bump the number of allowed immutable memtables by 1, to allow for greater flood protection
this should probably not be applied if you have rocksdb_atomic_flush = false (the default)
2026-11-23 14:43:30 -08:00
Jade Ellis 2c79a67130 feat: Warn when the system allocator is used 2026-11-23 22:32:35 +00:00
Jade Ellis 8b9000cdf4 chore: Add changelog fragment 2026-11-23 22:32:35 +00:00
Jade Ellis 370fa43b5a chore: Reshuffle allocator features 2026-11-23 22:32:35 +00:00
Jade Ellis bf5f77a94a fix(knock): Align knock state handling with Matrix spec
Updates state_cache on MembershipState::Knock, avoids stale local state
checks and holding state_lock across federation, drops invalid
knock_room_state entries without failing post-send_knock, allows
re-knocking, and honours via servers.
2026-11-23 21:54:33 +00:00
Jade Ellis 506c4a0376 fix(leave): Rescind remote knocks over federation
Remote knocks no longer populate local room state, so leaving a room
we are not in must go through remote_leave_room even when knocked.
2026-11-23 21:54:33 +00:00
Jade Ellis d9b94b98ad refactor(invite): Extract per-event partial membership validation
Allows callers like remote knocking to filter invalid stripped state
events individually per MSC4311 instead of failing the entire request.
2026-11-23 21:54:33 +00:00
timedout 26cdaeec99 fix: Re-use validate_partial_membership_state 2026-11-23 21:54:32 +00:00
timedout 73fbdd6056 style: Improve logging for knocking 2026-11-23 21:54:32 +00:00
timedout d591385bed fix: Stop blowing up in send_knock 2026-11-23 21:54:32 +00:00
timedout cbb1b70c99 fix: Invert server identity check 2026-11-23 21:54:32 +00:00
timedout 748603549c chore: Add news fragment 2026-11-23 21:54:32 +00:00
timedout 6115693193 fix: Modernise knocking helpers 2026-11-23 21:54:31 +00:00
Jade Ellis e9974043f2 ci: Add towncrier to pre-commit checks 2026-11-23 21:10:20 +00:00
timedout 415b3dd671 chore: Add changelog fragment 2026-11-23 19:23:24 +00:00
Jade Ellis 3774f3e7e4 chore: Advertise client-server v1.6 support 2026-11-23 19:20:02 +00:00
Henry-Hiles 2408ded7b4 feat: Support stable MSC4143 RTC transports endpoint 2026-11-23 13:14:39 -05:00
Henry-Hiles a3cc73bc08 fix(nix): Add libclang to devshell 2026-11-23 17:27:55 +00:00
Ginger 20bc28cd2f chore: News fragment 2026-11-23 15:30:36 +00:00
Ginger 9877464857 feat: Request profile scope from OIDC providers by default 2026-11-23 15:30:36 +00:00
Ginger a6e051fa3b chore: News fragment 2026-11-23 10:10:19 -05:00
Ginger cdda575d4a fix: Return 403 instead of 404 when UIAA is disabled 2026-11-23 10:09:08 -05:00
Renovate Bot c82aba6f5a chore(deps): update ghcr.io/renovatebot/renovate docker tag to v44.257.9 2026-11-23 05:05:22 +00:00
Jade Ellis 14739ffaf7 chore: Remove redundant Mxc import in download_image 2026-11-22 17:57:49 +00:00
Jade Ellis 733c25ce5a chore: Update Cargo.lock 2026-11-22 17:57:49 +00:00
Jade Ellis 8c4a2d0ce9 chore: Downgrade per-request URL preview route logs to debug 2026-11-22 17:57:49 +00:00
Jade Ellis c0f69f23dd fix: Resolve relative OpenGraph asset URLs and avoid cloning HTML body 2026-11-22 17:57:49 +00:00
Jade Ellis c6b87fb033 fix: Check CIDR range and HTTP status when downloading preview media 2026-11-22 17:57:49 +00:00
Jade Ellis 635fccf11f fix: Populate image_size when downloading URL preview images 2026-11-22 17:57:49 +00:00
Jade Ellis def987f935 fix: Gate webpage usage and update disabled url_preview stubs 2026-11-22 17:57:49 +00:00
Jade Ellis 137805693e refactor: Use mime::Mime instead of lettre ContentType for URL previews 2026-11-22 17:57:49 +00:00
timedout bd7450f52a fix: Remove attachment metadata when the attachment has no URL 2026-11-22 17:57:49 +00:00
timedout 66be5efeec fix: Properly select correct properties, fixup unit test 2026-11-22 17:57:49 +00:00
timedout 33ed0a2e75 feat: Automatically populate UrlPreviewData, correctly populate media fields 2026-11-22 17:57:49 +00:00
timedout 16f18f8516 feat: Make url preview logs more informative 2026-11-22 17:57:49 +00:00
timedout 4710c227db chore: Add @silversys to refactor TODO 2026-11-22 17:57:49 +00:00
timedout f5bd8d0a7c chore: Add newsfrag 2026-11-22 17:57:49 +00:00
timedout 5ad6c35f0b fix: Default to asset type when not at top-level 2026-11-22 17:57:49 +00:00
timedout 17af942cbf feat: Support most other specified opengraph tags 2026-11-22 17:57:49 +00:00
timedout 9f7fb54bd4 fix: Don't fail entire preview requests when auxiliary requests fail 2026-11-22 17:57:49 +00:00
Jade Ellis 21f3f0c1eb perf(service/sending): Seek past destination prefixes in queued_destinations 2026-11-22 17:21:50 +00:00
Jade Ellis 613bb1b2a8 fix(service/sending): Avoid spawning restarted workers during shutdown 2026-11-22 17:21:50 +00:00
Jade Ellis a0d9e71eac fix(service/sending): Use Flush to wake queued destinations 2026-11-22 17:21:50 +00:00
Jade Ellis d477417909 fix(service/sending): Preserve sticky events during restarted worker netburst 2026-11-22 17:21:50 +00:00
Jade Ellis cd7910009a fix(service/sending): Apply local backoff to panicked federation transactions 2026-11-22 17:21:50 +00:00
Erwan Leboucher 793c06c17b fix(service/sending): Address review feedback on sender supervision
Signed-off-by: Erwan Leboucher <erwanleboucher@gmail.com>
2026-11-22 17:21:50 +00:00
Erwan Leboucher cf45dcffbb fix(service/sending): Restart crashed sender workers and resend queued backlogs
Signed-off-by: Erwan Leboucher <erwanleboucher@gmail.com>
2026-11-22 17:21:50 +00:00
Erwan Leboucher 919fea9b97 fix: Index remote events by origin_server_ts 2026-11-22 02:02:37 +00:00
Erwan Leboucher 5687847fe3 style: Address review nits on timestamp index 2026-11-22 02:02:37 +00:00
Erwan Leboucher 251086670f feat: Add timestamp to event endpoint backed by a timestamp index 2026-11-22 02:02:37 +00:00
Jade Ellis 3379badbd4 fix(service): Prevent potential corruption in state diffs
This fixes a non-atomicity issue. Also fixes incorrect
calculation of a buffer size that would result in
reallocation.
2026-11-22 01:02:59 +00:00
Jade Ellis cc28a01e49 fix(core): Fix BoolExt::or short-circuiting
This would mean that or would return false when one of the
inputs was true.

Also fix double futures in type signatures
2026-11-21 21:38:55 +00:00
Renovate Bot 95392ccc46 chore(deps): update rust-non-major 2026-11-21 20:14:56 +00:00
Julian Anderson f3289f150c ci(docs): Set Rspress config values based on prod/preview status 2026-11-21 14:15:26 -05:00
Julian Anderson cbc089df1b ci(docs): Expire preview doc deployments after 14 days 2026-11-21 13:27:50 -05:00
Julian Anderson 0b738e835b ci(docs): Replace preview docs workflow with Grebedoc 2026-11-21 13:27:47 -05:00
Jade Ellis 5ad36c0914 refactor(core): Drop hot reload support
This was unused and a hotbed of potential issues
2026-11-21 18:04:50 +00:00
Jade Ellis 7e678869ec refactor(core): Remove unneeded unsafe in UnwrapInfallible and Unquoted 2026-11-21 18:04:50 +00:00
Jade Ellis 9744a6e332 fix(core): Reject non-ELF targets in mod_init! and mod_fini! macros 2026-11-21 18:04:50 +00:00
Jade Ellis 306be392ba fix(core): Mark dlopen/dlsym wrappers unsafe in core::mods 2026-11-21 18:04:50 +00:00
Jade Ellis 66dd3e8e3e fix(service): Mark state::create unsafe and document lifetime invariants 2026-11-21 18:04:49 +00:00
Jade Ellis 1dd572416b docs(database): Document borrowed-item soundness flaw on iterator streams 2026-11-21 18:04:49 +00:00
Jade Ellis d74275bda1 refactor(database): Remove disabled unsound cfg(disable) blocks 2026-11-21 18:04:49 +00:00
Jade Ellis 65d25c77e8 fix(database): Assert ColumnFamily layout and document Map drop order 2026-11-21 18:04:48 +00:00
Jade Ellis 95f925eaee fix(database): Fix Seek drop order and remove no-op transmute in pool 2026-11-21 18:04:48 +00:00
Jade Ellis becfc2454f fix(core): Fix UAF race and aliasing UB in config::Manager 2026-11-21 18:04:48 +00:00
Jade Ellis b617e9fd5c fix(core): Remove unsound assert_unchecked in compute::getcpu 2026-11-21 18:04:48 +00:00
Jade Ellis ece207286a fix(core): Fix UB in usize_from_f64 on non-finite and out-of-range floats 2026-11-21 18:04:47 +00:00
Renovate Bot fda99bcda2 chore(deps): update dependency cargo-bins/cargo-binstall to v1.28.0 2026-11-21 16:08:11 +00:00
Erwan Leboucher 5d66476126 fix(metrics): Fix in-flight requests, PDU lag, latency buckets and thumbnail accounting 2026-11-21 16:06:51 +00:00
Renovate Bot 798bef5bc7 chore(deps): update node-patch-updates to v2.1.4 2026-11-21 16:03:41 +00:00
Ginger 7408d53977 chore: News fragment 2026-11-21 16:03:31 +00:00
Ginger 973cfd5746 fix: Log OIDC registrations in the admin room 2026-11-21 16:03:31 +00:00
timedout cb9b3e65d0 chore: Add newsfrag 2026-11-21 15:21:56 +00:00
Jade Ellis d4aec6ca5c fix: Use mimalloc for c/c++ code by default 2026-11-21 15:21:56 +00:00
Jade Ellis 43cf8cccdf refactor: Unify memory stats and create feature parity 2026-11-21 15:21:56 +00:00
Jade Ellis c6b9854c49 docs(main): Clarify mimalloc feature scope and jemalloc precedence 2026-11-21 15:21:55 +00:00
Jade Ellis 6df7dda329 feat(alloc): Implement trim, memory_usage, and memory_stats for mimalloc 2026-11-21 15:21:55 +00:00
Jade Ellis 8a20a5c349 fix(config): Warn in release builds when both mimalloc and jemalloc are enabled 2026-11-21 15:21:55 +00:00
Jade Ellis a27a5bed29 fix(alloc): Restore not(target_env = "msvc") cfg gates and gate default module 2026-11-21 15:21:54 +00:00
timedout d4ac77a023 feat: Add mimalloc support, drop hardened_malloc 2026-11-21 15:21:54 +00:00
timedout 68068574d3 fix(service/admin): Gate IsTerminal and warn imports on console feature 2026-11-21 15:21:54 +00:00
Jade Ellis 61d77278f6 chore: Add changelog 2026-11-21 15:21:53 +00:00
Jade Ellis 094d24f82e docs(alloc): Fix interrupted doc comments in je.rs 2026-11-21 15:21:53 +00:00
Jade Ellis 8375eb5a36 chore(deps): Upgrade jemalloc with soundness fixes 2026-11-21 15:21:53 +00:00
Jade Ellis f2a9e1f993 test(alloc): add unit tests for jemalloc wrapper fixes 2026-11-21 15:21:52 +00:00
Jade Ellis 318a0205b0 perf(alloc): return &'static Key from mallctl! macro 2026-11-21 15:21:52 +00:00
Jade Ellis f46c87a40d fix(alloc): avoid unnecessary global epoch refreshes in mallctl get and memory_stats 2026-11-21 15:21:52 +00:00
Jade Ellis e0b9bfdb73 fix(alloc): mark raw mallctl helpers unsafe and check null in percpu_arenas 2026-11-21 15:21:52 +00:00
Jade Ellis 180869ecff fix(alloc): validate arena index bounds before arena.<i>.* mallctls 2026-11-21 15:21:51 +00:00
Jade Ellis b9ceb008ba fix(alloc): pass NULL pointers in jemalloc notify ctls 2026-11-21 15:21:51 +00:00
Jade Ellis 3118183bd8 fix(alloc): fix UB and MIB aliasing in thread::allocated/deallocated 2026-11-21 15:21:51 +00:00
Jade Ellis 45b0a30155 fix(alloc): prevent leak, panic, and FFI unwind in memory_stats 2026-11-21 15:21:50 +00:00
Jade Ellis 5169496cb6 fix(alloc): avoid TLS and panics in jemalloc ctor and key lookup 2026-11-21 15:21:50 +00:00
Jade Ellis c1b3c15034 fix(alloc): export malloc_conf as thin pointer and fix options 2026-11-21 15:21:50 +00:00
Julian Anderson bd26b2d596 chore(config): Deprecate request_ip_source 2026-11-20 18:09:40 -05:00
Julian Anderson 6cd38e4278 chore(config): Alphabetize deprecated keys 2026-11-20 18:09:40 -05:00
Julian Anderson aa077b4bec chore(config): Deprecate allow_check_for_updates
Fixes #2555
2026-11-20 18:09:36 -05:00
130 changed files with 3427 additions and 2381 deletions

No files matched your search

+14 -6
View File
@@ -49,6 +49,8 @@ jobs:
run: npm ci
- name: Build Rspress documentation
env:
SITE_PATH: ${{ github.ref != 'refs/heads/main' && format('/pr/{0}/', '${{ forgejo.event.number }}') || '/' }}
run: npm run docs:build
- name: Install Wrangler
@@ -62,10 +64,16 @@ jobs:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
command: pages deploy ./doc_build --branch="main" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}"
- name: Deploy to Cloudflare Pages (Preview)
if: github.ref != 'refs/heads/main' && vars.CLOUDFLARE_PROJECT_NAME != ''
uses: https://github.com/cloudflare/wrangler-action@953926a2e2182532811c01a25e53647d93bf07c0 # v4
- name: Deploy to Grebedoc (Preview)
if: github.ref != 'refs/heads/main'
uses: actions/git-pages@v2
with:
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
command: pages deploy ./doc_build --branch="${{ github.head_ref || github.ref_name }}" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}"
site: https://preview.continuwuity.org
path: "pr/${{ forgejo.event.number }}"
server: grebedoc.dev
token: ${{ forgejo.token }}
source: doc_build/
strict: true
pretty-urls: true
expires: 14
comment: ${{ forgejo.sha }}
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
name: Renovate
runs-on: ubuntu-latest
container:
image: ghcr.io/renovatebot/renovate:44.241.0@sha256:22d22b4ca7d768b5b469309d34379783bf91cd94a58faecf1cd0f4528a65d21c
image: ghcr.io/renovatebot/renovate:44.257.9@sha256:578179439fceea89646662dd583b27efdad8d1429e0cbd90681c40dde068589e
options: --tmpfs /tmp:exec
steps:
- name: Checkout
+6 -1
View File
@@ -36,6 +36,11 @@ repos:
hooks:
- id: committed
- repo: https://github.com/twisted/towncrier
rev: 26.9.0
hooks:
- id: towncrier-check
- repo: local
hooks:
- id: cargo-fmt
@@ -51,7 +56,7 @@ repos:
hooks:
- id: cargo-clippy
name: cargo clippy
entry: cargo clippy -- -D warnings
entry: cargo clippy --
language: system
pass_filenames: false
types: [ rust ]
Generated
+100 -78
View File
@@ -485,19 +485,20 @@ dependencies = [
[[package]]
name = "bindgen"
version = "0.73.2"
version = "0.72.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
dependencies = [
"bitflags",
"cexpr",
"clang-sys",
"itertools 0.13.0",
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"shlex",
"syn 3.0.10",
"shlex 1.3.0",
"syn 2.0.119",
]
[[package]]
@@ -671,7 +672,7 @@ checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
dependencies = [
"semver",
"serde",
"toml 1.2.1+spec-1.1.0",
"toml 1.2.2+spec-1.1.0",
]
[[package]]
@@ -683,7 +684,7 @@ dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
"shlex 2.0.1",
]
[[package]]
@@ -759,14 +760,14 @@ checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
dependencies = [
"glob",
"libc",
"libloading 0.8.9",
"libloading",
]
[[package]]
name = "clap"
version = "4.6.8"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a"
checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c"
dependencies = [
"clap_builder",
"clap_derive",
@@ -784,9 +785,9 @@ dependencies = [
[[package]]
name = "clap_derive"
version = "4.6.8"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a"
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
dependencies = [
"heck",
"proc-macro2",
@@ -873,9 +874,13 @@ dependencies = [
name = "conduwuit"
version = "26.11.0-alpha.2"
dependencies = [
"aws-lc-rs",
"clap",
"conduwuit_admin",
"conduwuit_api",
"conduwuit_build_metadata",
"conduwuit_core",
"conduwuit_database",
"conduwuit_macros",
"conduwuit_router",
"conduwuit_service",
@@ -883,6 +888,7 @@ dependencies = [
"const-str",
"ctor",
"dtor",
"log",
"opentelemetry",
"opentelemetry-otlp",
"opentelemetry-prometheus",
@@ -890,10 +896,13 @@ dependencies = [
"opentelemetry_sdk",
"parking_lot",
"prometheus",
"reqwest 0.13.5",
"rustls",
"sentry",
"sentry-tower",
"sentry-tracing",
"tokio",
"tokio-metrics",
"tracing",
"tracing-flame",
"tracing-journald",
@@ -997,7 +1006,6 @@ dependencies = [
"ipaddress",
"lettre",
"libc",
"libloading 0.9.1",
"libmimalloc-sys",
"lock_api 0.5.0",
"maplit",
@@ -1030,7 +1038,7 @@ dependencies = [
"tikv-jemallocator",
"tokio",
"tokio-metrics",
"toml 1.2.1+spec-1.1.0",
"toml 1.2.2+spec-1.1.0",
"tracing",
"tracing-core",
"tracing-subscriber",
@@ -1128,13 +1136,13 @@ dependencies = [
"log",
"loole",
"lru-cache",
"mime",
"nonzero_ext",
"openidconnect",
"opentelemetry",
"p256 0.14.0",
"rand 0.10.4",
"regex",
"reqwest 0.12.28",
"reqwest 0.13.5",
"resolvematrix",
"ruma",
@@ -2105,9 +2113,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -2712,10 +2720,10 @@ dependencies = [
"hyper",
"hyper-util",
"rustls",
"rustls-native-certs",
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots",
]
[[package]]
@@ -2989,6 +2997,15 @@ dependencies = [
"serde",
]
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.14.0"
@@ -3241,16 +3258,6 @@ dependencies = [
"windows-link",
]
[[package]]
name = "libloading"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10"
dependencies = [
"cfg-if",
"windows-link",
]
[[package]]
name = "libm"
version = "0.2.16"
@@ -3269,9 +3276,9 @@ dependencies = [
[[package]]
name = "libz-sys"
version = "1.1.32"
version = "1.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69965d2409bff8c8cea3829009fff66a86f05a0570656552ef70f616e8e4bd85"
checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9"
dependencies = [
"cc",
"pkg-config",
@@ -4002,8 +4009,7 @@ dependencies = [
[[package]]
name = "opentelemetry-instrumentation-tower"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7006f3b1853d315462a7237c81eec3d7adfa5b70975a02b19e92d045bc22d7"
source = "git+https://github.com/open-telemetry/opentelemetry-rust-contrib?rev=6bbbc337aab0bcf10d7799c3e5b5ced75920491a#6bbbc337aab0bcf10d7799c3e5b5ced75920491a"
dependencies = [
"axum",
"http",
@@ -4191,6 +4197,12 @@ dependencies = [
"phc",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pear"
version = "0.2.9"
@@ -4854,8 +4866,8 @@ dependencies = [
"log",
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"serde",
"serde_json",
@@ -4870,6 +4882,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webpki-roots",
]
[[package]]
@@ -4997,8 +5010,8 @@ dependencies = [
[[package]]
name = "ruma"
version = "0.17.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.18.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"assign",
"js_int",
@@ -5016,8 +5029,8 @@ dependencies = [
[[package]]
name = "ruma-appservice-api"
version = "0.17.1"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.18.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"http",
"js_int",
@@ -5029,8 +5042,8 @@ dependencies = [
[[package]]
name = "ruma-client-api"
version = "0.25.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.26.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"as_variant",
"assign",
@@ -5051,8 +5064,8 @@ dependencies = [
[[package]]
name = "ruma-common"
version = "0.20.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.21.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"as_variant",
"base64 0.23.1",
@@ -5084,8 +5097,8 @@ dependencies = [
[[package]]
name = "ruma-events"
version = "0.35.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.36.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"as_variant",
"indexmap 2.14.2",
@@ -5105,8 +5118,8 @@ dependencies = [
[[package]]
name = "ruma-federation-api"
version = "0.16.1"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.17.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"bytes",
"http",
@@ -5127,8 +5140,8 @@ dependencies = [
[[package]]
name = "ruma-identifiers-validation"
version = "0.14.0"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.14.1"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"js_int",
"thiserror 2.0.21",
@@ -5136,8 +5149,8 @@ dependencies = [
[[package]]
name = "ruma-macros"
version = "0.20.2"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.20.3"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"as_variant",
"cfg-if",
@@ -5147,13 +5160,13 @@ dependencies = [
"ruma-identifiers-validation",
"serde",
"syn 3.0.10",
"toml 1.2.1+spec-1.1.0",
"toml 1.2.2+spec-1.1.0",
]
[[package]]
name = "ruma-push-gateway-api"
version = "0.16.0"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.17.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"js_int",
"ruma-common",
@@ -5164,8 +5177,8 @@ dependencies = [
[[package]]
name = "ruma-signatures"
version = "0.22.1"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.23.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"base64 0.23.1",
"ed25519-dalek",
@@ -5181,8 +5194,8 @@ dependencies = [
[[package]]
name = "ruma-state-res"
version = "0.18.0"
source = "git+https://github.com/ruma/ruma.git?rev=472a23ef86bc0bb40a22d856fc0af539eb9d71b7#472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
version = "0.19.0"
source = "git+https://github.com/ruma/ruma.git?rev=decdf3f6c5160e1db595d4edb4d65d5de935e13c#decdf3f6c5160e1db595d4edb4d65d5de935e13c"
dependencies = [
"js_int",
"ruma-common",
@@ -5208,8 +5221,8 @@ dependencies = [
[[package]]
name = "rust-librocksdb-sys"
version = "0.49.0+11.12.0"
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b"
version = "0.45.1+11.1.1"
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8"
dependencies = [
"bindgen",
"bzip2-sys",
@@ -5219,15 +5232,14 @@ dependencies = [
"libz-sys",
"lz4-sys",
"pkg-config",
"rustflags",
"tikv-jemalloc-sys",
"zstd-sys",
]
[[package]]
name = "rust-rocksdb"
version = "0.54.0"
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=85ded20348e3dab902c239967075795e9c6d101b#85ded20348e3dab902c239967075795e9c6d101b"
version = "0.49.1"
source = "git+https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1?rev=0a25ff92f7c09b55eec496b9c192c7d5136ab2b8#0a25ff92f7c09b55eec496b9c192c7d5136ab2b8"
dependencies = [
"libc",
"parking_lot",
@@ -5255,12 +5267,6 @@ dependencies = [
"semver",
]
[[package]]
name = "rustflags"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a39e0e9135d7a7208ee80aa4e3e4b88f0f5ad7be92153ed70686c38a03db2e63"
[[package]]
name = "rustix"
version = "1.1.6"
@@ -5888,6 +5894,12 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "shlex"
version = "2.0.1"
@@ -6247,17 +6259,18 @@ dependencies = [
[[package]]
name = "tikv-jemalloc-ctl"
version = "0.7.0"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92"
version = "0.6.1"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
dependencies = [
"libc",
"paste",
"tikv-jemalloc-sys",
]
[[package]]
name = "tikv-jemalloc-sys"
version = "0.7.0+5.4.0-0-g7a34f18502e7b222724097cdcd499b437d189acc"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92"
version = "0.6.1+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
dependencies = [
"cc",
"libc",
@@ -6265,8 +6278,8 @@ dependencies = [
[[package]]
name = "tikv-jemallocator"
version = "0.7.0"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=46e7821917b06636cdb5b203d312799970eaea92#46e7821917b06636cdb5b203d312799970eaea92"
version = "0.6.1"
source = "git+https://forgejo.ellis.link/continuwuation/jemallocator?rev=df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554#df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
dependencies = [
"libc",
"tikv-jemalloc-sys",
@@ -6407,9 +6420,9 @@ dependencies = [
[[package]]
name = "toml"
version = "1.2.1+spec-1.1.0"
version = "1.2.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b"
dependencies = [
"indexmap 2.14.2",
"serde_core",
@@ -6466,9 +6479,9 @@ dependencies = [
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31"
dependencies = [
"winnow 1.0.5",
]
@@ -6865,9 +6878,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
@@ -7124,6 +7137,15 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webpki-roots"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "weezl"
version = "0.1.12"
+10 -72
View File
@@ -166,15 +166,6 @@ features = [
"form",
]
# Needed for as long as openidconnect is on an outdated reqwest
[workspace.dependencies.reqwest_0_12]
package = "reqwest"
version = "0.12"
default-features = false
features = [
"rustls-tls-native-roots-no-provider",
]
[workspace.dependencies.serde]
version = "1.0.229"
default-features = false
@@ -269,9 +260,6 @@ features = [
[workspace.dependencies.tokio-metrics]
version = "0.5.2"
[workspace.dependencies.libloading]
version = "0.9.0"
[workspace.dependencies.wildmatch]
version = "2.7.0"
@@ -360,7 +348,7 @@ version = "1.1.1"
# Used for matrix spec type definitions and helpers
[workspace.dependencies.ruma]
git = "https://github.com/ruma/ruma.git"
rev = "472a23ef86bc0bb40a22d856fc0af539eb9d71b7"
rev = "decdf3f6c5160e1db595d4edb4d65d5de935e13c"
features = [
"appservice-api-c",
"client-api",
@@ -373,7 +361,6 @@ features = [
"compat-upload-signatures",
"compat-optional-txn-pdus",
"compat-get-3pids",
"unstable-msc2867",
"unstable-msc2870",
"unstable-msc3814",
"unstable-msc3245",
@@ -407,7 +394,7 @@ features = [
[workspace.dependencies.rust-rocksdb]
git = "https://forgejo.ellis.link/continuwuation/rust-rocksdb-zaidoon1"
rev = "85ded20348e3dab902c239967075795e9c6d101b"
rev = "0a25ff92f7c09b55eec496b9c192c7d5136ab2b8"
default-features = false
features = [
"multi-threaded-cf",
@@ -427,15 +414,14 @@ default-features = false
[workspace.dependencies.openidconnect]
version = "4.1.0"
default-features = false
features = ["reqwest"]
# optional opentelemetry, performance measurements, flamegraphs, etc for performance measurements and monitoring
[workspace.dependencies.opentelemetry]
version = "0.33.1"
[workspace.dependencies.opentelemetry-instrumentation-tower]
version = "0.19.0"
git = "https://github.com/open-telemetry/opentelemetry-rust-contrib"
rev = "6bbbc337aab0bcf10d7799c3e5b5ced75920491a"
default-features = false
features = ["axum"]
@@ -490,7 +476,7 @@ version = "0.49.5"
# jemalloc usage
[workspace.dependencies.tikv-jemalloc-sys]
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
rev = "46e7821917b06636cdb5b203d312799970eaea92"
rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
default-features = false
features = [
"background_threads_runtime_support",
@@ -498,7 +484,7 @@ features = [
]
[workspace.dependencies.tikv-jemallocator]
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
rev = "46e7821917b06636cdb5b203d312799970eaea92"
rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
default-features = false
features = [
"background_threads_runtime_support",
@@ -506,7 +492,7 @@ features = [
]
[workspace.dependencies.tikv-jemalloc-ctl]
git = "https://forgejo.ellis.link/continuwuation/jemallocator"
rev = "46e7821917b06636cdb5b203d312799970eaea92"
rev = "df86ff89d4b1e223b9f7d2dd2fbb7f202da7f554"
default-features = false
features = ["use_std"]
@@ -591,6 +577,9 @@ version = "0.10.4"
default-features = false
features = ["std"]
[workspace.dependencies.mime]
version = "0.3.18"
[workspace.dependencies.nonzero_ext]
version = "0.3.0"
@@ -752,74 +741,23 @@ inherits = "release"
# Developer profile
#
# To enable hot-reloading:
# 1. Uncomment all of the rustflags here.
# 2. Uncomment crate-type=dylib in src/*/Cargo.toml
#
# opt-level, mir-opt-level, validate-mir are not known to interfere with reloading
# and can be raised if build times are tolerable.
[profile.dev]
debug = "full"
opt-level = 0
panic = "unwind"
debug-assertions = true
incremental = true
#rustflags = [
# '--cfg', 'conduwuit_mods',
# '-Ztime-passes',
# '-Zmir-opt-level=0',
# '-Zvalidate-mir=false',
# '-Ztls-model=global-dynamic',
# '-Cprefer-dynamic=true',
# '-Zstaticlib-prefer-dynamic=true',
# '-Zstaticlib-allow-rdylib-deps=true',
# '-Zpacked-bundled-libs=false',
# '-Zplt=true',
# '-Crpath=true',
# '-Clink-arg=-Wl,--as-needed',
# '-Clink-arg=-Wl,--allow-shlib-undefined',
# '-Clink-arg=-Wl,-z,keep-text-section-prefix',
# '-Clink-arg=-Wl,-z,lazy',
#]
[profile.dev.package.conduwuit_core]
inherits = "dev"
[profile.dev.package.conduwuit]
inherits = "dev"
#rustflags = [
# '--cfg', 'conduwuit_mods',
# '-Ztime-passes',
# '-Zmir-opt-level=0',
# '-Zvalidate-mir=false',
# '-Ztls-model=global-dynamic',
# '-Cprefer-dynamic=true',
# '-Zexport-executable-symbols=true',
# '-Zplt=true',
# '-Crpath=true',
# '-Clink-arg=-Wl,--as-needed',
# '-Clink-arg=-Wl,--allow-shlib-undefined',
# '-Clink-arg=-Wl,--export-dynamic',
# '-Clink-arg=-Wl,-z,lazy',
#]
[profile.dev.package.'*']
inherits = "dev"
debug = 'limited'
codegen-units = 1
opt-level = 'z'
#rustflags = [
# '--cfg', 'conduwuit_mods',
# '-Ztls-model=global-dynamic',
# '-Cprefer-dynamic=true',
# '-Zstaticlib-prefer-dynamic=true',
# '-Zstaticlib-allow-rdylib-deps=true',
# '-Zpacked-bundled-libs=true',
# '-Zplt=true',
# '-Clink-arg=-Wl,--as-needed',
# '-Clink-arg=-Wl,-z,lazy',
# '-Clink-arg=-Wl,-z,nodelete',
#]
# primarily used for CI
[profile.test]
@@ -0,0 +1 @@
Fixed read receipts for all but one of a user's threads not being sent over federation. Contributed by @eleboucher.
@@ -0,0 +1 @@
Added support for the stable MatrixRTC transports discovery endpoint (`GET /_matrix/client/v1/rtc/transports`) from the accepted MSC4143, advertised via the `org.matrix.msc4143.stable` unstable feature. The unstable endpoint remains available. Contributed by @Henry-Hiles (QuadRadical).
@@ -0,0 +1 @@
Added the `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event` endpoint as per MSC3030, letting clients find the event closest to a given timestamp. Contributed by @eleboucher.
+1
View File
@@ -0,0 +1 @@
Added support for acting as a trusted server, meaning the `trusted_servers` list can consist of servers that are either Synapse OR continuwuity.
+1
View File
@@ -0,0 +1 @@
Fixed Prometheus accounting for in-flight requests, federation PDU lag, latency buckets, and thumbnail sizes. Contributed by @eleboucher.
+1
View File
@@ -0,0 +1 @@
URL previews no longer completely fail if downloading auxiliary content (images/videos/audio) fails. Contributed by @nex.
+1
View File
@@ -0,0 +1 @@
The former configuration alias `allow_check_for_updates` is now explicitly deprecated in favor of `allow_announcements_check`. Additionally, `request_ip_source` is now deprecated in favor of `accepted_ip_sources`.
+1
View File
@@ -0,0 +1 @@
A message is now sent to the admin room when a user logs in for the first time through an OIDC provider, if admin room notices are enabled. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Modernised the room knocking helper functions to make them match the behaviour of our room join helpers, which are safer and more efficient. This also fixes a bug that caused an error when knocking on rooms not local to the server. Contributed by @nex.
+1
View File
@@ -0,0 +1 @@
Continuwuity will now request the `profile` OIDC scope from identity providers by default to improve compatibility with identity providers that require it to access users' profile claims, as recommended by the OIDC specification. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Attempting to start a UIAA session on a homeserver with UIAA disabled will now return `403 M_UNAUTHORIZED` instead of `404 M_UNSUPPORTED`. Contributed by @ginger.
+1
View File
@@ -0,0 +1 @@
Advertise support for Matrix v1.6. Contributed by @jade
+1
View File
@@ -0,0 +1 @@
Moved the `jemalloc` feature out of `standard` (and `full`) into `default` so builders can more easily swap allocators. Builders using `--no-default-features` with the `full` or `standard` feature should now explicitly select an allocator (either `jemalloc` or `mimalloc`). Contributed by @Jade
+1
View File
@@ -0,0 +1 @@
Fix outgoing federation stalling after a sender worker panics. Contributed by @eleboucher.
+26 -22
View File
@@ -412,7 +412,7 @@
# env: CONTINUWUITY_IP_LOOKUP_STRATEGY
#ip_lookup_strategy = 5
# The preferred source to use for getting the real client IP.
# DEPRECATED: The preferred source to use for getting the real client IP.
#
# Takes any of the following options:
#
@@ -431,9 +431,10 @@
# to set this header" check; if the header selected is present, it is
# used.
#
# Ignored if `accepted_ip_sources` is set.
# Ignored if `accepted_ip_sources` is set. `accepted_ip_sources` is
# the preferred alternative.
#
# If not set set, `direct` is used. Additionally, `direct` is used
# If not set, `direct` is used. Additionally, `direct` is used
# as a fallback if the chosen header is not found.
#
# env: CONTINUWUITY_REQUEST_IP_SOURCE
@@ -812,18 +813,6 @@
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
#forget_forced_upon_leave = false
# Set this to true to require authentication when looking up user profiles
# through this server.
#
# By default this is false, allowing tools such as matrix.to to access
# profiles of users on this server and on other servers.
# Setting this to true will block those tools, and may block automated
# crawlers from scraping users' profiles, although it will not block
# other homeservers from accessing users' profiles.
#
# env: CONTINUWUITY_REQUIRE_AUTH_FOR_PROFILE_REQUESTS
#require_auth_for_profile_requests = false
# Set this to true to require authentication to create a rendezvous
# session. Rendezvous sessions are used for QR code login.
#
@@ -1042,10 +1031,7 @@
# (trusted key notary servers), as well as serve as trusted servers for
# other operations like backfill and event fetching.
#
# Currently, continuwuity doesn't support inbound key requests, so
# this list should only contain other Synapse servers.
#
# example: ["matrix.org", "starstruck.systems"]
# example: ["continuwuity.org", "matrix.org"]
#
# It is possible to restrict which signing keys trusted servers are
# allowed to sign responses with. Without configuring this, all responses
@@ -1083,7 +1069,7 @@
# is discouraged for performance and reliability reasons.
#
# env: CONTINUWUITY_TRUSTED_SERVERS
#trusted_servers = ["matrix.org"]
#trusted_servers = ["continuwuity.org", "continuwuity.rocks", "matrix.org"]
# Whether to prioritise trusted server lookups over origin server lookups.
#
@@ -2581,10 +2567,12 @@
# Additional scopes Continuwuity should request from the IDP. This may be
# necessary to access certain claims. Continuwuity always requests the
# `openid` scope.
# `openid` scope, regardless of the contents of this option,
# and will also request the `profile` scope by default if this option is
# not set.
#
# env: CONTINUWUITY_OAUTH__OIDC__ADDITIONAL_SCOPES
#additional_scopes = []
#additional_scopes = ["profile"]
# Additional trusted audiences that Continuwuity will accept in the `aud`
# claim of the OIDC token returned by the IDP. If your identity
@@ -2780,6 +2768,22 @@
# env: CONTINUWUITY_EXPERIMENTS__MSC4494
#msc4494 = false
# MSC4556: Notary request limits
#
# Creates a new key notary server route that has stricter limits on how
# many signing keys can be requested in one query, to avoid a resource
# exhaustion exploit vector in the existing key notary endpoint.
#
# Continuwuity mitigates the exploit vector in the old notary endpoint
# anyway, so you do not need to enable this to be protected.
#
# Requires that remote servers support this MSC before it does anything.
#
# https://github.com/matrix-org/matrix-spec-proposals/pull/4556
#
# env: CONTINUWUITY_EXPERIMENTS__MSC4556
#msc4556 = false
# MSC4560: Stripped state requests over federation
#
# Implements a more efficient way for servers to acquire and serve
+1 -1
View File
@@ -50,7 +50,7 @@ EOF
# Developer tool versions
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
ENV BINSTALL_VERSION=1.27.0
ENV BINSTALL_VERSION=1.28.0
# renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree
+1 -1
View File
@@ -18,7 +18,7 @@ RUN --mount=type=cache,target=/etc/apk/cache apk add \
# Developer tool versions
# renovate: datasource=github-releases depName=cargo-bins/cargo-binstall
ENV BINSTALL_VERSION=1.27.0
ENV BINSTALL_VERSION=1.28.0
# renovate: datasource=github-releases depName=psastras/sbom-rs
ENV CARGO_SBOM_VERSION=0.9.1
# renovate: datasource=crate depName=lddtree
-5
View File
@@ -18,10 +18,5 @@
"type": "file",
"name": "testing",
"label": "Testing"
},
{
"type": "file",
"name": "hot_reload",
"label": "Hot Reloading"
}
]
-200
View File
@@ -1,200 +0,0 @@
# Hot Reloading ("Live" Development)
Note that hot reloading has not been refactored in quite a while and is not
guaranteed to work at this time.
### Summary
When developing in debug-builds with the nightly toolchain, Continuwuity is modular
using dynamic libraries and various parts of the application are hot-reloadable
while the server is running: http api handlers, admin commands, services,
database, etc. These are all split up into individual workspace crates as seen
in the `src/` directory. Changes to sourcecode in a crate rebuild that crate and
subsequent crates depending on it. Reloading then occurs for the changed crates.
Release builds still produce static binaries which are unaffected. Rust's
soundness guarantees are in full force. Thus you cannot hot-reload release
binaries.
### Requirements
Currently, this development setup only works on x86_64 and aarch64 Linux glibc.
[musl explicitly does not support hot reloadable libraries, and does not
implement `dlclose`][2]. macOS does not fully support our usage of `RTLD_GLOBAL`
possibly due to some thread-local issues. [This Rust issue][3] may be of
relevance, specifically [this comment][4]. It may be possible to get it working
on only very modern macOS versions such as at least Sonoma, as currently loading
dylibs is supported, but not unloading them in our setup, and the cited comment
mentions an Apple WWDC confirming there have been TLS changes to somewhat make
this possible.
As mentioned above this requires the nightly toolchain. This is due to reliance
on various Cargo.toml features that are only available on nightly, most
specifically `RUSTFLAGS` in Cargo.toml. Some of the implementation could also be
simpler based on other various nightly features. We hope lots of nightly
features start making it out of nightly sooner as there have been dozens of very
helpful features that have been stuck in nightly ("unstable") for at least 5+
years that would make this simpler. We encourage greater community consensus to
move these features into stability.
This currently only works on x86_64/aarch64 Linux with a glibc C library. musl C
library, macOS, and likely other host architectures are not supported (if other
architectures work, feel free to let us know and/or make a PR updating this).
This should work on GNU ld and lld (rust-lld) and gcc/clang, however if you
happen to have linker issues it's recommended to try using `mold` or `gold`
linkers, and please let us know in the [Continuwuity Matrix room][7] the linker
error and what linker solved this issue so we can figure out a solution. Ideally
there should be minimal friction to using this, and in the future a build script
(`build.rs`) may be suitable to making this easier to use if the capabilities
allow us.
### Usage
As of 19 May 2024, the instructions for using this are:
0. Have patience. Don't hesitate to join the [Continuwuity Matrix room][7] to
receive help using this. As indicated by the various rustflags used and some
of the interesting issues linked at the bottom, this is definitely not something
the Rust ecosystem or toolchain is used to doing.
1. Install the nightly toolchain using rustup. You may need to use `rustup
override set nightly` in your local Continuwuity directory, or use `cargo
+nightly` for all actions.
2. Uncomment `cargo-features` at the top level / root Cargo.toml
3. Scroll down to the `# Developer profile` section and uncomment ALL the
rustflags for each dev profile and their respective packages.
4. In each workspace crate's Cargo.toml (everything under `src/*` AND
`deps/rust-rocksdb/Cargo.toml`), uncomment the `dylib` crate type under
`[lib]`.
5. Due to [this rpath issue][5], you must export the `LD_LIBRARY_PATH`
environment variable to your nightly Rust toolchain library directory. If
using rustup (hopefully), use this: `export
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/`
6. Start the server. You can use `cargo +nightly run` for this along with the
standard.
7. Make some changes where you need to.
8. In a separate terminal window in the same directory (or using a terminal
multiplexer like tmux), run the *build* Cargo command `cargo +nightly build`.
Cargo should only rebuild what was changed / what's necessary, so it should
not be rebuilding all the crates.
9. In your Continuwuity server terminal, hit/send `CTRL+C` signal. This will tell
Continuwuity to find which libraries need to be reloaded, and reloads them as
necessary.
10. If there were no errors, it will tell you it successfully reloaded `#`
modules, and your changes should now be visible. Repeat 7 - 9 as needed.
To shutdown Continuwuity in this setup, hit/send `CTRL+\`. Normal builds still
shutdown with `CTRL+C` as usual.
Steps 1 - 5 are the initial first-time steps for using this. To remove the hot
reload setup, revert/comment all the Cargo.toml changes.
As mentioned in the requirements section, if you happen to have some linker
issues, try using the `-fuse-ld=` rustflag and specify mold or gold in all the
`rustflags` definitions in the top level Cargo.toml, and please let us know in
the [Continuwuity Matrix room][7] the problem. mold can be installed typically
through your distro, and gold is provided by the binutils package.
It's possible a helper script can be made to do all of this, or most preferably
a specially made build script (build.rs). `cargo watch` support will be
implemented soon which will eliminate the need to manually run `cargo build` all
together.
### Addendum
Conduit was inherited as a single crate without modularity or reloading in its
design. Reasonable partitioning and abstraction allowed a split into several
crates, though many circular dependencies had to be corrected. The resulting
crates now form a directed graph as depicted in figures below. The interfacing
between these crates is still extremely broad which is not mitigable.
Initially [hot_lib_reload][6] was investigated but found appropriate for a
project designed with modularity through limited interfaces, not a large and
complex existing codebase. Instead a bespoke solution built directly on
[libloading][8] satisfied our constraints. This required relatively minimal
modifications and zero maintenance burden compared to what would be required
otherwise. The technical difference lies with relocation processing: we leverage
global bindings (`RTLD_GLOBAL`) in a very intentional way. Most libraries and
off-the-shelf module systems (such as [hot_lib_reload][6]) restrict themselves
to local bindings (`RTLD_LOCAL`). This allows them to release software to
multiple platforms with much greater consistency, but at the cost of burdening
applications to explicitly manage these bindings. In our case with an optional
feature for developers, we shrug any such requirement to enjoy the cost/benefit
on platforms where global relocations are properly cooperative.
To make use of `RTLD_GLOBAL` the application has to be oriented as a directed
acyclic graph. The primary rule is simple and illustrated in the figure below:
**no crate is allowed to call a function or use a variable from a crate below
it.**
![Continuwuity's dynamic library setup diagram - created by Jason
Volk](./assets/libraries.png)
When a symbol is referenced between crates they become bound: **crates cannot be
unloaded until their calling crates are first unloaded.** Thus we start the
reloading process from the crate which has no callers. There is a small problem
though: the first crate is called by the base executable itself! This is solved
by using an `RTLD_LOCAL` binding for just one link between the main executable
and the first crate, freeing the executable from all modules as no global
binding ever occurs between them.
![Continuwuity's reload and load order diagram - created by Jason
Volk](./assets/reload_order.png)
Proper resource management is essential for reliable reloading to occur. This is
a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is
remarkably low, generally stemming from poor patterns and practices.
Unfortunately static analysis doesn't enforce reload-safety programmatically
(though it could one day), for now hazards can be avoided by knowing a few basic
do's and dont's:
1. Understand that code is memory. Just like one is forbidden from referencing
free'd memory, one must not transfer control to free'd code. Exposure to this
is primarily from two things:
- Callbacks, which this project makes very little use of.
- Async tasks, which are addressed below.
2. Tie all resources to a scope or object lifetime with greatest possible
symmetry (locality). For our purposes this applies to code resources, which
means async blocks and tokio tasks.
- **Never spawn a task without receiving and storing its JoinHandle**.
- **Always wait on join handles** before leaving a scope or in another cleanup
function called by an owning scope.
3. Know any minor specific quirks documented in code or here:
- Don't use `tokio::spawn`, instead use our `Handle` in `core/server.rs`, which
is reachable in most of the codebase via `services()` or other state. This is
due to some bugs or assumptions made in tokio, as it happens in `unsafe {}`
blocks, which are mitigated by circumventing some thread-local variables. Using
runtime handles is good practice in any case.
The initial implementation PR is available [here][1].
### Interesting related issues/bugs
- [DT_RUNPATH produced in binary with rpath = true is wrong (cargo)][5]
- [Disabling MIR Optimization in Rust Compilation
(cargo)](https://internals.rust-lang.org/t/disabling-mir-optimization-in-rust-compilation/19066/5)
- [Workspace-level metadata
(cargo-deb)](https://github.com/kornelski/cargo-deb/issues/68)
[1]: https://forgejo.ellis.link/continuwuation/continuwuity/pulls/387
[2]: https://wiki.musl-libc.org/functional-differences-from-glibc.html#Unloading-libraries
[3]: https://github.com/rust-lang/rust/issues/28794
[4]: https://github.com/rust-lang/rust/issues/28794#issuecomment-368693049
[5]: https://github.com/rust-lang/cargo/issues/12746
[6]: https://crates.io/crates/hot-lib-reloader/
[7]: https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org
[8]: https://crates.io/crates/libloading
-7
View File
@@ -37,13 +37,6 @@ It is highly unlikely you will ever need to add a new workspace member, but if
you truly find yourself needing to, we recommend reaching out to us in the
Matrix room for discussions about it beforehand.
The primary inspiration for this design was apart of hot reloadable development,
to support "Continuwuity as a library" where specific parts can simply be
swapped out. There is evidence Conduit wanted to go this route too as `axum` is
technically an optional feature in Conduit, and can be compiled without the
binary or axum library for handling inbound web requests; but it was never
completed or worked.
See the Rust documentation on [Workspaces][workspaces] for general questions and
information on Cargo workspaces.
+3
View File
@@ -71,6 +71,9 @@ Names below are as they appear in Prometheus. OTLP uses the dotted OpenTelemetry
| `continuwuity_sender_events_total` | counter | `destination`, `kind`, `outcome` | PDUs and EDUs sent in outgoing transactions |
| `continuwuity_sender_events_queued_total` | counter | `destination`, `kind` | PDUs and EDUs queued for sending |
| `continuwuity_sender_queue_depth` | gauge | | Messages waiting for the sender workers |
| `continuwuity_sender_requests` | gauge | `state` | Estimated outgoing requests stored as `queued` or `active` (in flight) |
| `continuwuity_sender_workers` | gauge | | Running sender workers; below the configured count means a worker is restarting |
| `continuwuity_sender_panics_total` | counter | `scope` | Panics caught in a single outgoing `transaction` or a whole sender `worker` |
| `continuwuity_users` | gauge | `origin` | Known `local` users, including deactivated, and `remote` users |
| `continuwuity_invites_total` | counter | `direction`, `destination`, `outcome` | Invites sent by local users or received over federation |
| `continuwuity_media_write_size_bytes` | histogram | `origin` | Media files written, from local uploads or cached remote media |
+5 -5
View File
@@ -302,7 +302,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))",
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))",
"legendFormat": "",
"refId": "A",
"range": true
@@ -496,7 +496,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))",
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))",
"legendFormat": "p50",
"refId": "A",
"range": true
@@ -506,7 +506,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))",
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))",
"legendFormat": "p95",
"refId": "B",
"range": true
@@ -516,7 +516,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\"}[$__rate_interval])))",
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{instance=~\"$instance\",http_route!~\".*/sync\"}[$__rate_interval])))",
"legendFormat": "p99",
"refId": "C",
"range": true
@@ -1228,7 +1228,7 @@
{
"type": "timeseries",
"title": "PDU lag",
"description": "Time between an accepted PDU's origin_server_ts and its arrival; affected by clock skew",
"description": "Time between an accepted PDU's origin_server_ts and its transaction arriving; affected by clock skew",
"id": 21,
"datasource": {
"type": "prometheus",
-4
View File
@@ -36,10 +36,6 @@ List database backups
Send a message to the admin room
## `!admin server reload`
Hot-reload the server
## `!admin server restart`
Restart the server
+1
View File
@@ -26,6 +26,7 @@
LD_LIBRARY_PATH = lib.makeLibraryPath (
[
pkgs.stdenv.cc.cc.lib
pkgs.llvmPackages.libclang.lib
]
++ lib.optionals pkgs.stdenv.hostPlatform.isLinux [
pkgs.liburing
+122 -115
View File
@@ -11,26 +11,26 @@
"devDependencies": {
"@rspress/core": "^2.0.0",
"@rspress/plugin-client-redirects": "^2.0.0",
"@rspress/plugin-sitemap": "^2.0.0",
"@types/node": "^26.6.6",
"typescript": "^7.0.0"
}
},
"node_modules/@emnapi/core": {
"version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz",
"integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==",
"version": "2.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.3.tgz",
"integrity": "sha512-KA+gOBtbifRATmUa/Gpf5C2B2EJ0r4brHUT3XSgACeHREcuiObXH56xd+B3fFsEFbUT04VBEe6MuZiCtMp0tQg==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "1.2.3",
"@emnapi/wasi-threads": "2.2.0",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "1.11.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
"version": "2.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.3.tgz",
"integrity": "sha512-ayb/PyyLzpwRyFVxeC0uoEHu59QlB1iWGcGsOpXQcaB/Dc+uGfBmNmpCHp3HmTT0t8lSsMmg3j7+tdJW/TlHjQ==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -39,9 +39,9 @@
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz",
"integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==",
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
"integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -106,33 +106,36 @@
}
},
"node_modules/@napi-rs/wasm-runtime": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.6.tgz",
"integrity": "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg==",
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.7.tgz",
"integrity": "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@tybys/wasm-util": "^0.10.3"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/Brooooooklyn"
},
"peerDependencies": {
"@emnapi/core": "^1.7.1",
"@emnapi/runtime": "^1.7.1"
"@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3",
"@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3"
}
},
"node_modules/@rsbuild/core": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.1.tgz",
"integrity": "sha512-dv5tL7djb8ex5z4sqnDmUbd5PnGNr/CXuFfiMD4RkUsF1JEZZkGH8lc+QW4fqYQIHM7RTvcMUakgvwVU/O9WMw==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rsbuild/core/-/core-2.3.3.tgz",
"integrity": "sha512-IdbBXZrIY16RxnQduXRrsRBQtJ/X7JkYESrk6D46WA918wrckYTBxE09vHvDxR+3JoCLE02vOm2NPBNxqaUw5A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@rspack/core": "~2.3.1",
"@swc/helpers": "^0.5.23"
"@rspack/core": "~2.3.3",
"@swc/helpers": "^0.5.24"
},
"bin": {
"rsbuild": "bin/rsbuild.js"
@@ -169,32 +172,32 @@
}
},
"node_modules/@rspack/binding": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.1.tgz",
"integrity": "sha512-pfCJGBFNK2tnNnoDP6ZoTbOjxbKr1U2eGFDJ8bIuZQai4FBNhWQlKFmNup+X5K935XYRulZBomIBAL6GL6W2YQ==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding/-/binding-2.3.3.tgz",
"integrity": "sha512-wwF++36a3rqYi0G9zj+rUavn/GIMzbzXehelGS1jkYeKPHyPXrVYwRHqwEKNKMD9z+FdW4YJKQcfFkPlHEiwUg==",
"dev": true,
"license": "MIT",
"optionalDependencies": {
"@rspack/binding-darwin-arm64": "2.3.1",
"@rspack/binding-darwin-x64": "2.3.1",
"@rspack/binding-linux-arm64-gnu": "2.3.1",
"@rspack/binding-linux-arm64-musl": "2.3.1",
"@rspack/binding-linux-ppc64-gnu": "2.3.1",
"@rspack/binding-linux-riscv64-gnu": "2.3.1",
"@rspack/binding-linux-riscv64-musl": "2.3.1",
"@rspack/binding-linux-s390x-gnu": "2.3.1",
"@rspack/binding-linux-x64-gnu": "2.3.1",
"@rspack/binding-linux-x64-musl": "2.3.1",
"@rspack/binding-wasm32-wasi": "2.3.1",
"@rspack/binding-win32-arm64-msvc": "2.3.1",
"@rspack/binding-win32-ia32-msvc": "2.3.1",
"@rspack/binding-win32-x64-msvc": "2.3.1"
"@rspack/binding-darwin-arm64": "2.3.3",
"@rspack/binding-darwin-x64": "2.3.3",
"@rspack/binding-linux-arm64-gnu": "2.3.3",
"@rspack/binding-linux-arm64-musl": "2.3.3",
"@rspack/binding-linux-ppc64-gnu": "2.3.3",
"@rspack/binding-linux-riscv64-gnu": "2.3.3",
"@rspack/binding-linux-riscv64-musl": "2.3.3",
"@rspack/binding-linux-s390x-gnu": "2.3.3",
"@rspack/binding-linux-x64-gnu": "2.3.3",
"@rspack/binding-linux-x64-musl": "2.3.3",
"@rspack/binding-wasm32-wasi": "2.3.3",
"@rspack/binding-win32-arm64-msvc": "2.3.3",
"@rspack/binding-win32-ia32-msvc": "2.3.3",
"@rspack/binding-win32-x64-msvc": "2.3.3"
}
},
"node_modules/@rspack/binding-darwin-arm64": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.1.tgz",
"integrity": "sha512-koLyL2r8PUcLD0StjuZ/n5XM6GJ0C8dzJN0IuIV9d7nQcibJxwjjSAWEPGVz6bm8WuzypvuVKNoa1+GGAHeMQA==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-arm64/-/binding-darwin-arm64-2.3.3.tgz",
"integrity": "sha512-G9WcBOP/6ZWeqTM/G0/rkJRY4DWmYQvk2untzcpj92uO12tqjZ9BSMgtBFvwElwagfQBkX8PPutkAZgtnlAoWA==",
"cpu": [
"arm64"
],
@@ -206,9 +209,9 @@
]
},
"node_modules/@rspack/binding-darwin-x64": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.1.tgz",
"integrity": "sha512-YK39JLiu1YC6+3BMxkP7e848pHD7e2T/0OSNogDi7whfiZNg95wa9Ncd7I5ppAf0nhmV+FNew/sCBIFp5h67Jw==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-darwin-x64/-/binding-darwin-x64-2.3.3.tgz",
"integrity": "sha512-6agI5XDoihay+84vzZgIwwpQQ3xBWbe2HTWBRc0n42LzynIj9h7Qv8CJzf1gSDV1Ts0jzDgAJCYUFJ6Ya5F6MA==",
"cpu": [
"x64"
],
@@ -220,9 +223,9 @@
]
},
"node_modules/@rspack/binding-linux-arm64-gnu": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.1.tgz",
"integrity": "sha512-Q+RCA/KM2tn6m6R5U4lktXDs5cCRm3SyleQk86iqqUFX7wKzVRUvr5BTsreg6K9of3gpYmQ6+g1PGT5cwo0rLA==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-2.3.3.tgz",
"integrity": "sha512-VdjK1mDq+GBexd041lmWBFmAvcWIZy7kepTJbJgxLeHYYOnI3KmBG15kemhlK0pBySa+bePX7p2w8uYtl1HsCA==",
"cpu": [
"arm64"
],
@@ -234,9 +237,9 @@
]
},
"node_modules/@rspack/binding-linux-arm64-musl": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.1.tgz",
"integrity": "sha512-He+muVDON1fohGtdYamh3zHVwf6/E6fZu/+iEAkxjclE0P94bsCfYVcZW/a4/l1tJ2zvLZtB4jD7Qr6r4vG/WA==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-arm64-musl/-/binding-linux-arm64-musl-2.3.3.tgz",
"integrity": "sha512-xF4Wy4XwGjC3m13tFm1q9p9Qpm31qrk6f5zEMPZC31UVabb+2jrgTI1pfZ8IRuo9x/Qw9s+Zq3hyDbtJvvD8Pg==",
"cpu": [
"arm64"
],
@@ -248,9 +251,9 @@
]
},
"node_modules/@rspack/binding-linux-ppc64-gnu": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.1.tgz",
"integrity": "sha512-blIZUgyPt4FcSHkZL6sJ2xbzc7ACgDeU49An4mXLSebwdgnlhTzxeSFnh2VeJDlGza8CUaZYB/zS/6oZ2kCDcw==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-2.3.3.tgz",
"integrity": "sha512-jVmn+LpF44D4FdZyT91rlT/tPMdHIfPfQTgVzwPB5nDICp4b57SFjVBApuAPIxnLT1pKLkv/LIcdvGSdAeX12w==",
"cpu": [
"ppc64"
],
@@ -262,9 +265,9 @@
]
},
"node_modules/@rspack/binding-linux-riscv64-gnu": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.1.tgz",
"integrity": "sha512-3FtW2DUFmXxhBORUA3zSc+ot4d6R/1/U6z/48TDN4jeIYDUG9VqYBF6LUohX4vBY6IP0DCyXb2N9WayD/9QXoA==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-2.3.3.tgz",
"integrity": "sha512-JcQJm8M634jkbG6zJ3TfziKYsCINEAh3FwKuxLljvBgGDEupBxPuB0n2bXBIUeI8P9C33B45IYX6BwWYXll/zw==",
"cpu": [
"riscv64"
],
@@ -276,9 +279,9 @@
]
},
"node_modules/@rspack/binding-linux-riscv64-musl": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.1.tgz",
"integrity": "sha512-+5qNgdNdXzp/K8f8BjgJ3m7tcbBKPENN7WPDfBcSHvWb5GF4+o/pbrX26c0+LEugo0bYUOAoitBNd94AwcNvpA==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-2.3.3.tgz",
"integrity": "sha512-YMIOS7rFvCDnpeyxoVEVbM7U/TwcC2VDtN3Oiq9BenRsNTEvk0imINhuVRFanh15+wkiQHk9h0b+pzcggYLAsA==",
"cpu": [
"riscv64"
],
@@ -290,9 +293,9 @@
]
},
"node_modules/@rspack/binding-linux-s390x-gnu": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.1.tgz",
"integrity": "sha512-yNcg/y1+MV0wZ984CVU4d1HAYYwMcDPXoQO0xynU+K5YuBxPWALHOxuRRCKCcykBdL1GIEshAIewEFrsW/cmJg==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-2.3.3.tgz",
"integrity": "sha512-tHGtIG6GGHsk2KvSleQp/BrVqiGdjDsLJuMKR7hE7W1uJW6WDJ+a+Z23Rk5kHXh5BjeFLjXxcufGuokvmLmTag==",
"cpu": [
"s390x"
],
@@ -304,9 +307,9 @@
]
},
"node_modules/@rspack/binding-linux-x64-gnu": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.1.tgz",
"integrity": "sha512-ffclKBuH8wwimOBd6xGUxrBfVKKY5Ow4E7OFdHZeg4xffm2O8auGszmOgvFu1eoDoOYHaVJn+cEV6UD0KwZk8A==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-gnu/-/binding-linux-x64-gnu-2.3.3.tgz",
"integrity": "sha512-spe8SjywfO+dD7Sk+vIpPaOXf56wstrgeuztfJdiI9zTeQmf/lhdaNUUSUAXlGIaLjrN/PhV8i5kbQ7VaAkenw==",
"cpu": [
"x64"
],
@@ -318,9 +321,9 @@
]
},
"node_modules/@rspack/binding-linux-x64-musl": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.1.tgz",
"integrity": "sha512-qcDwwuyxR7TMtrW+r5Y9RIW25boXd1Ip/9jz04jhdq/OiU/Am7rCP2X90CH8sWdzovIF9UNmsGjY4KklR0F2Mg==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-linux-x64-musl/-/binding-linux-x64-musl-2.3.3.tgz",
"integrity": "sha512-4E4OJodrmsS52zkSAWShG/F07etr0OG4oSrIN+/2BBgc0qR2wwu2T+rAs308IL3lbywlS+J+cynrRcsSFMD+Kg==",
"cpu": [
"x64"
],
@@ -332,9 +335,9 @@
]
},
"node_modules/@rspack/binding-wasm32-wasi": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.1.tgz",
"integrity": "sha512-3dr6zjFaCK3A920ftCriSJkiRhEfhHtat7LtBdj6g0mcV5Rt+iealmli0vjeAvD0UdpE1u8EKWlfw82JLgFLSQ==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-wasm32-wasi/-/binding-wasm32-wasi-2.3.3.tgz",
"integrity": "sha512-AhlsPjW31TGP8N+J7OmbCPaamARUl+OQNiT3xo0PL5Dz5oMm+bEfYLostpehKyy8MNDrmJcY97M9pDb5MDMA0w==",
"cpu": [
"wasm32"
],
@@ -342,15 +345,15 @@
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "1.11.3",
"@emnapi/runtime": "1.11.3",
"@napi-rs/wasm-runtime": "1.1.6"
"@emnapi/core": "2.0.0-beta.3",
"@emnapi/runtime": "2.0.0-beta.3",
"@napi-rs/wasm-runtime": "1.2.7"
}
},
"node_modules/@rspack/binding-win32-arm64-msvc": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.1.tgz",
"integrity": "sha512-AZbuLPylt1xvWssN93AsirbYs3WgfcrA8tMsqHmVJIHahLu9E+JPKZ3Gmsw6IYEZk3EfnV3ujQzeQ1/VfF0Vsw==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-2.3.3.tgz",
"integrity": "sha512-Zqbj7GBPtkJ8GlUKAjFgvmOxKkQwjfS3XfjwGBcmoIAUb4IxUsmMqvi+gfKrvI45SjYVFZaJnTpOJw6GL79K+Q==",
"cpu": [
"arm64"
],
@@ -362,9 +365,9 @@
]
},
"node_modules/@rspack/binding-win32-ia32-msvc": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.1.tgz",
"integrity": "sha512-R5NVU68TePZcgRdYUzrQX9YFNxmcyXZEPwaPv40AAgsqNyacG3iRaYVmV79jt3rWYfa0QJaqvRLUchDe2SZ6zQ==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-2.3.3.tgz",
"integrity": "sha512-sJJmbrdzH6kI48mCsUu5a2+BzEktLmHrHUmWGkAPAi0zhi4anA7sOdS1+uERbkkd/XAzs0bdn3JXyT2djY+3IA==",
"cpu": [
"ia32"
],
@@ -376,9 +379,9 @@
]
},
"node_modules/@rspack/binding-win32-x64-msvc": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.1.tgz",
"integrity": "sha512-5T9DYjNPQpLbrNXjCssGd2B6xMQPlc3LxVOKHGUA1O0GV+88vBkTXAcryJ+Fo+yVEMPCzp4VvwBMGAVDpCjcSA==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/binding-win32-x64-msvc/-/binding-win32-x64-msvc-2.3.3.tgz",
"integrity": "sha512-1r3wxV1pBNykqpbEbZWqcrZd13PKLq0e7Ku6qv8IGKKeftuf3RUxTkeM5AzppGMGEIA9sw8mRdN7NvEXxqLLxw==",
"cpu": [
"x64"
],
@@ -390,13 +393,13 @@
]
},
"node_modules/@rspack/core": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.1.tgz",
"integrity": "sha512-9BWfaiEJLgLK9U53Q4WVruBZ19Mu/XWHXHEu0UFla4lUtH8Z+/ET2m044tiqbtyIgqQyG58fMrxHeVIAiXMXHg==",
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/@rspack/core/-/core-2.3.3.tgz",
"integrity": "sha512-stAYr0SXf+ZFXFsWTv+Ljxoj/nQs2p7gX9V1kBwlO2IXlRAAhabLONYibT3ZeEGybx3kowrs7uJkcOQsuHgghw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@rspack/binding": "2.3.1"
"@rspack/binding": "2.3.3"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
@@ -431,17 +434,17 @@
}
},
"node_modules/@rspress/core": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.3.tgz",
"integrity": "sha512-qKa5c7zHO8cmhxkReURd3dN/ZRfHYnEztdIQ9hMuolaNzhSYo2A36XErUvLvbMf2EUM2AxfPYRQv+4Crfeq6pw==",
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/@rspress/core/-/core-2.1.4.tgz",
"integrity": "sha512-7OmP7ABDgQLSpVfpBHfpjqu4H3PGBGMyhLxF1crPQ48Q6MIWAVu77nw7cONn8AZa9GoVq0N/DoE3GEtgZzlu6w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@mdx-js/mdx": "^3.1.1",
"@mdx-js/react": "^3.1.1",
"@rsbuild/core": "^2.2.14",
"@rsbuild/core": "^2.3.3",
"@rsbuild/plugin-react": "~2.1.1",
"@rspress/shared": "2.1.3",
"@rspress/shared": "2.1.4",
"@shikijs/rehype": "^4.2.0",
"@shikijs/transformers": "^4.2.0",
"@types/mdast": "^4.0.4",
@@ -485,22 +488,9 @@
}
},
"node_modules/@rspress/plugin-client-redirects": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.3.tgz",
"integrity": "sha512-iEqJ8qEFuUxGKRVaS/WMyFi8FiJlogdcEHbGK/UjY8+8Hg8r8aSv4YihmNh3Ev/uIW21hrC8aXMEgVo0H51Q+g==",
"dev": true,
"license": "MIT",
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"peerDependencies": {
"@rspress/core": "^2.1.0-beta.2"
}
},
"node_modules/@rspress/plugin-sitemap": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@rspress/plugin-sitemap/-/plugin-sitemap-2.1.3.tgz",
"integrity": "sha512-Fqo7/4PfQK1ecHUFoUDMrR/E+Hcu+kIohxSs8QabflMy3dqk+M3ZqzJDOHpVYB+HLLGwKiqkPLT4BK+W93clkw==",
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/@rspress/plugin-client-redirects/-/plugin-client-redirects-2.1.4.tgz",
"integrity": "sha512-6/g+Mr8lslqiFzlMBouex8TLm6PlQK6cmZ71Yfv82+Uxcrb+LaFAFiPbq2G7gToXBQUoECM4D/7nSLAfeOhnEQ==",
"dev": true,
"license": "MIT",
"engines": {
@@ -511,13 +501,13 @@
}
},
"node_modules/@rspress/shared": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.3.tgz",
"integrity": "sha512-VwJ7kgsTWVqHzSXQVHIUCsdMparmq9b/IDmTa3a6jMPl1zmm5Qg9M0eP4j8JXWoIS9n19XtCkQcZmMTFOPRy3A==",
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/@rspress/shared/-/shared-2.1.4.tgz",
"integrity": "sha512-SuQyVKn9xcQwkzfl+4bPBzX10gxbhCs9UupqSoPtxvyr9pMgSbXnlo3gxTPZXLzk5HUqZZ6tlIju25PVCEtYWA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@rsbuild/core": "^2.2.14",
"@rsbuild/core": "^2.3.3",
"@shikijs/rehype": "^4.2.0",
"@types/react": "^19.3.0",
"mdast-util-mdx-jsx": "^3.2.1",
@@ -672,9 +662,9 @@
"license": "Apache-2.0"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.4",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz",
"integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==",
"version": "0.10.5",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
"integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -743,6 +733,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "26.6.6",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.9.0"
}
},
"node_modules/@types/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
@@ -3815,6 +3815,13 @@
"@typescript/typescript-win32-x64": "7.0.2"
}
},
"node_modules/undici-types": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true,
"license": "MIT"
},
"node_modules/unhead": {
"version": "2.1.17",
"resolved": "https://registry.npmjs.org/unhead/-/unhead-2.1.17.tgz",
+2 -2
View File
@@ -20,11 +20,11 @@
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"type": "module",
"devDependencies": {
"@rspress/core": "^2.0.0",
"@rspress/plugin-client-redirects": "^2.0.0",
"@rspress/plugin-sitemap": "^2.0.0",
"@types/node": "^26.6.6",
"typescript": "^7.0.0"
}
}
+46
View File
@@ -0,0 +1,46 @@
#-------------------------------------------------------------------------------#
# Qodana analysis is configured by qodana.yaml file #
# https://www.jetbrains.com/help/qodana/qodana-yaml.html #
#-------------------------------------------------------------------------------#
#################################################################################
# WARNING: Do not store sensitive information in this file, #
# as its contents will be included in the Qodana report. #
#################################################################################
version: "1.0"
#Specify inspection profile for code analysis
profile:
name: qodana.starter
#Enable inspections
#include:
# - name: <SomeEnabledInspectionId>
#Disable inspections
#exclude:
# - name: <SomeDisabledInspectionId>
# paths:
# - <path/where/not/run/inspection>
#Execute shell command before Qodana execution (Applied in CI/CD pipeline)
#bootstrap: sh ./prepare-qodana.sh
#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
#plugins:
# - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
# Quality gate. Will fail the CI/CD pipeline if any condition is not met
# severityThresholds - configures maximum thresholds for different problem severities
# testCoverageThresholds - configures minimum code coverage on a whole project and newly added code
# Code Coverage is available in Ultimate and Ultimate Plus plans
#failureConditions:
# severityThresholds:
# any: 15
# critical: 5
# testCoverageThresholds:
# fresh: 70
# total: 50
#Specify Qodana linter for analysis (Applied in CI/CD pipeline)
linter: jetbrains/qodana-<linter>:2026.2
+8 -9
View File
@@ -1,10 +1,13 @@
import { defineConfig } from '@rspress/core';
import { pluginSitemap } from '@rspress/plugin-sitemap';
import { pluginClientRedirects } from '@rspress/plugin-client-redirects';
const sitePath: string = process.env.SITE_PATH ?? '/';
export default defineConfig({
root: 'docs',
title: 'Continuwuity',
siteOrigin: sitePath != "/" ? "https://preview.continuwuity.org" : "https://continuwuity.org",
base: sitePath,
description: 'A community-driven Matrix homeserver',
icon: '/assets/logo.svg',
logo: {
@@ -75,14 +78,10 @@ export default defineConfig({
lastUpdated: true,
enableContentAnimation: true,
enableAppearanceAnimation: false,
footer: {
},
footer: {},
},
plugins: [pluginSitemap({
siteUrl: 'https://continuwuity.org', // TODO: Set automatically in build pipeline
}),
pluginClientRedirects({
plugins: [pluginClientRedirects({
redirects: [{
from: '^/config_reference$',
to: '/reference/config'
@@ -105,8 +104,8 @@ export default defineConfig({
from: "^/source(|_code)$",
to: "https://forgejo.ellis.link/continuwuation/continuwuity",
}, {
from: "^/(CONTRIBUTING.md|contributing)$",
to: "/development/contributing"
from: "^/(CONTRIBUTING.md|contributing)$",
to: "/development/contributing"
}
]
})],
-3
View File
@@ -34,9 +34,6 @@ pub(crate) use crate::{context::Context, utils::get_room_info};
pub(crate) const PAGE_SIZE: usize = 100;
conduwuit::mod_ctor! {}
conduwuit::mod_dtor! {}
pub use crate::admin::AdminCommand;
/// Install the admin command processor
-8
View File
@@ -110,14 +110,6 @@ impl crate::Context<'_> {
self.write_str("Notice was sent to #admins").await
}
pub(super) async fn reload_mods(&self) -> Result {
self.bail_restricted()?;
self.services.server.reload()?;
self.write_str("Reloading server...").await
}
#[cfg(unix)]
pub(super) async fn restart(&self, force: bool) -> Result {
use conduwuit::utils::sys::current_exe_deleted;
-4
View File
@@ -39,10 +39,6 @@ pub enum ServerCommand {
message: Vec<String>,
},
/// Hot-reload the server
#[command(name = "reload", alias = "reload-mods")]
ReloadMods,
#[cfg(unix)]
/// Restart the server
Restart {
+3 -1
View File
@@ -2,7 +2,7 @@ use std::time::Duration;
use axum::extract::State;
use conduwuit::{
Err, Result, err,
Err, Result, debug, err,
utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize},
};
use conduwuit_core::error;
@@ -219,10 +219,12 @@ pub(crate) async fn get_media_preview_route(
)));
}
debug!("Fetching a URL preview for {url} on behalf of {sender_user}");
let preview = services
.media
.get_url_preview(&url)
.await
.inspect(|_| debug!(user=%sender_user, %url, "Finished fetching a URL preview"))
.map_err(|error| {
err!(Request(Unknown(
debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}")
+238 -474
View File
@@ -1,9 +1,10 @@
use std::{borrow::Borrow, collections::HashMap, sync::Arc};
use std::collections::{HashMap, hash_map::Entry};
use axum::extract::State;
use conduwuit::{
Err, Result, debug, debug_info, debug_warn, err, info,
Err, EventTypeExt, Result, debug, debug_warn, err, info,
matrix::{
StateKey,
event::gen_event_id,
pdu::{PartialPdu, PduEvent},
},
@@ -15,28 +16,25 @@ use conduwuit::{
use futures::{FutureExt, StreamExt};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName,
OwnedUserId, RoomId, UserId,
api::{client::knock::knock_room, federation},
OwnedUserId, RoomId, RoomVersionId, UserId,
api::{
client::knock::knock_room,
error::{ErrorKind, IncompatibleRoomVersionErrorData},
federation::{self, membership::RawStrippedState},
},
canonical_json::to_canonical_value,
events::{
StateEventType,
room::{
join_rules::{AllowRule, JoinRule},
member::{MembershipState, RoomMemberEventContent},
},
room::member::{MembershipState, RoomMemberEventContent},
},
};
use service::{
Services,
rooms::{
membership::validate_remote_member_event_stub,
state::RoomMutexGuard,
state_compressor::{CompressedState, HashSetCompressStateEvent},
},
rooms::{membership::validate_remote_member_event_stub, state::RoomMutexGuard},
};
use super::banned_room_check;
use crate::Ruma;
use crate::{Ruma, server::validate_partial_membership_event};
/// # `POST /_matrix/client/*/knock/{roomIdOrAlias}`
///
@@ -58,30 +56,42 @@ pub(crate) async fn knock_room_route(
.await?;
let mut servers = body.via.clone();
servers.extend(
services
.rooms
.state_cache
.servers_invite_via(&room_id)
.collect::<Vec<_>>()
.await,
);
if servers.is_empty() {
debug!("No via servers provided for knock, injecting some.");
servers.extend(
services
.rooms
.state_cache
.servers_invite_via(&room_id)
.collect::<Vec<_>>()
.await,
);
servers.extend(
services
let invite_state = services
.rooms
.state_cache
.invite_state(sender_user, &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()),
);
.unwrap_or_default();
let knock_state = services
.rooms
.state_cache
.knock_state(sender_user, &room_id)
.await
.unwrap_or_default();
if let Some(server) = room_id.server_name() {
servers.push(server.to_owned());
servers.extend(
invite_state
.iter()
.chain(knock_state.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()),
);
if let Some(server) = room_id.server_name() {
servers.push(server.to_owned());
}
}
servers.sort_unstable();
@@ -103,20 +113,28 @@ pub(crate) async fn knock_room_route(
let addl_via_servers = services.rooms.state_cache.servers_invite_via(&room_id);
let addl_state_servers = services
let addl_invite_state = services
.rooms
.state_cache
.invite_state(sender_user, &room_id)
.await
.unwrap_or_default();
let addl_knock_state = services
.rooms
.state_cache
.knock_state(sender_user, &room_id)
.await
.unwrap_or_default();
let mut addl_servers: Vec<_> = addl_state_servers
let mut addl_servers: Vec<_> = addl_invite_state
.iter()
.chain(addl_knock_state.iter())
.map(|event| event.get_field("sender"))
.filter_map(FlatOk::flat_ok)
.map(|user: OwnedUserId| user.server_name().to_owned())
.stream()
.chain(addl_via_servers)
.chain(body.via.iter().cloned().stream())
.collect()
.await;
@@ -143,165 +161,69 @@ async fn knock_room_by_id_helper(
) -> Result<knock_room::v3::Response> {
let state_lock = services.rooms.state.mutex.lock(room_id).await;
if services
.rooms
.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
.rooms
.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
.rooms
.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::new(room_id.into()));
}
if let Ok(membership) = services
.rooms
.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.")));
}
}
// For knock_restricted rooms, check if the user meets the restricted
// conditions If they do, attempt to join instead of knock
// This is not mentioned in the spec, but should be allowable (we're allowed
// to auto-join invites to knocked rooms)
let join_rule = services.rooms.state_accessor.get_join_rules(room_id).await;
if let JoinRule::KnockRestricted(restricted) = &join_rule {
let restriction_rooms: Vec<_> = restricted
.allow
.iter()
.filter_map(|a| match a {
| AllowRule::RoomMembership(r) => Some(&r.room_id),
| _ => None,
})
.collect();
// Check if the user is in any of the allowed rooms
let mut user_meets_restrictions = false;
for restriction_room_id in &restriction_rooms {
if services
.rooms
.state_cache
.is_joined(sender_user, restriction_room_id)
.await
{
user_meets_restrictions = true;
break;
}
}
// If the user meets the restrictions, try joining instead
if user_meets_restrictions {
debug_info!(
"{sender_user} meets the restricted criteria in knock_restricted room \
{room_id}, attempting to join instead of knock"
);
// For this case, we need to drop the state lock and get a new one
// in join_room_by_id_helper We need to release the lock here and
// let join_room_by_id_helper acquire it again
drop(state_lock);
match services
.rooms
.membership
.join_room(sender_user, room_id, reason.clone(), servers)
.await
{
| Ok(_) => return Ok(knock_room::v3::Response::new(room_id.to_owned())),
| Err(e) => {
debug_warn!(
"Failed to convert knock to join for {sender_user} in {room_id}: {e:?}"
);
// Get a new state lock for the remaining knock logic
let new_state_lock = services.rooms.state.mutex.lock(room_id).await;
let server_in_room = services
.rooms
.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,
new_state_lock,
)
.boxed()
.await?;
} else {
knock_room_helper_remote(
services,
sender_user,
room_id,
reason,
servers,
new_state_lock,
)
.boxed()
.await?;
}
return Ok(knock_room::v3::Response::new(room_id.to_owned()));
},
}
}
} else if !matches!(join_rule, JoinRule::Knock | JoinRule::KnockRestricted(_)) {
debug_warn!(
"{sender_user} attempted to knock on room {room_id} but its join rule is \
{join_rule:?}, not knock or knock_restricted"
);
}
let server_in_room = services
.rooms
.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]));
// Only check our known membership if we're already in the room.
if server_in_room {
if services
.rooms
.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 local_knock {
knock_room_helper_local(services, sender_user, room_id, reason, servers, state_lock)
if services
.rooms
.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 let Ok(membership) = services
.rooms
.state_accessor
.get_member(room_id, sender_user)
.await
&& 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.")));
}
// Local knocks can't fail unless the room is corrupted, so we don't
// fall back to remote knocks like we do with remote joins.
knock_room_helper_local(services, sender_user, room_id, reason, state_lock)
.boxed()
.await?;
} else {
knock_room_helper_remote(services, sender_user, room_id, reason, servers, state_lock)
drop(state_lock);
let remote_servers: Vec<_> = servers
.iter()
.filter(|sn| !services.globals.server_is_ours(sn))
.cloned()
.collect();
if remote_servers.is_empty() {
return Err!(Request(NotFound(
"Room {room_id} not found and no remote servers were provided to discover it"
)));
}
knock_room_helper_remote(services, sender_user, room_id, reason, &remote_servers)
.boxed()
.await?;
}
@@ -309,16 +231,14 @@ async fn knock_room_by_id_helper(
Ok(knock_room::v3::Response::new(room_id.to_owned()))
}
#[tracing::instrument(name = "local", skip(services, reason, state_lock))]
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 = services.rooms.state.get_room_version(room_id).await?;
let room_version_rules = room_version
.rules()
@@ -331,10 +251,9 @@ async fn knock_room_helper_local(
let mut content = RoomMemberEventContent::new(MembershipState::Knock);
content.displayname = services.users.displayname(sender_user).await.ok();
content.avatar_url = services.users.avatar_url(sender_user).await.ok();
content.reason.clone_from(&reason.clone());
content.reason = reason;
// Try normal knock first
let Err(error) = services
services
.rooms
.timeline
.build_and_append_pdu(
@@ -344,147 +263,24 @@ async fn knock_room_helper_local(
&state_lock,
)
.await
else {
return Ok(());
};
if servers.is_empty() || (servers.len() == 1 && services.globals.server_is_ours(&servers[0]))
{
return Err(error);
}
let (make_knock_response, remote_server) =
make_knock_request(services, sender_user, room_id, servers).await?;
info!("make_knock finished");
let room_version = make_knock_response.room_version;
let room_version_rules = room_version
.rules()
.expect("room version should have defined rules");
if !services.server.supported_room_version(&room_version) {
return Err!(BadServerResponse("Remote room version {room_version} is not supported"));
}
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:?}"))
})?;
validate_remote_member_event_stub(
&MembershipState::Knock,
sender_user,
room_id,
&knock_event_stub,
)?;
knock_event_stub.insert(
"origin".to_owned(),
CanonicalJsonValue::String(services.globals.server_name().as_str().to_owned()),
);
knock_event_stub.insert(
"origin_server_ts".to_owned(),
CanonicalJsonValue::Integer(
utils::millis_since_unix_epoch()
.try_into()
.expect("Timestamp is valid js_int value"),
),
);
knock_event_stub.insert(
"content".to_owned(),
to_canonical_value(content).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_rules)?;
// Generate event id
let event_id = gen_event_id(&knock_event_stub, &room_version_rules)?;
// Add event_id
knock_event_stub
.insert("event_id".to_owned(), 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::new(
room_id.to_owned(),
event_id.clone(),
services
.sending
.convert_to_outgoing_federation_event(knock_event.clone())
.await,
);
services
.sending
.send_federation_request(&remote_server, send_knock_request)
.await?;
info!("send_knock finished");
services
.rooms
.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");
// TODO: this call does not appear to do anything because
// `update_membership` doesn't call `mark_as_knock`. investigate further,
// ideally with the aim of removing this call entirely -- Ginger thinks
// `update_membership` should only be called from `force_state` and
// `append_pdu`.
services
.rooms
.state_cache
.update_membership(room_id, sender_user, &parsed_knock_pdu, false)
.await?;
info!("Appending room knock event locally");
services
.rooms
.timeline
.progress_extremities(&parsed_knock_pdu)
.await?;
services
.rooms
.timeline
.append_pdu(&parsed_knock_pdu, knock_event, room_id)
.await;
Ok(())
.map(|_| ())
}
#[tracing::instrument(name = "remote", skip(services, reason, servers))]
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.");
info!(via=?servers, "Knocking on {room_id} over federation.");
let (make_knock_response, remote_server) =
let (mut stub, room_version, remote_server) =
make_knock_request(services, sender_user, room_id, servers).await?;
info!("make_knock finished");
info!(%remote_server, "make_knock finished");
let room_version = make_knock_response.room_version;
let room_version_rules = room_version
.rules()
.expect("room version should have defined rules");
@@ -493,16 +289,7 @@ async fn knock_room_helper_remote(
return Err!(BadServerResponse("Remote room version {room_version} is not supported"));
}
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".to_owned(),
CanonicalJsonValue::String(services.globals.server_name().as_str().to_owned()),
);
knock_event_stub.insert(
stub.insert(
"origin_server_ts".to_owned(),
CanonicalJsonValue::Integer(
utils::millis_since_unix_epoch()
@@ -516,7 +303,7 @@ async fn knock_room_helper_remote(
knock_content.avatar_url = services.users.avatar_url(sender_user).await.ok();
knock_content.reason = reason;
knock_event_stub.insert(
stub.insert(
"content".to_owned(),
to_canonical_value(knock_content).expect("event is valid, we just created it"),
);
@@ -525,17 +312,15 @@ async fn knock_room_helper_remote(
// needs to be present
services
.server_keys
.hash_and_sign_event(&mut knock_event_stub, &room_version_rules)?;
.hash_and_sign_event(&mut stub, &room_version_rules)?;
// Generate event id
let event_id = gen_event_id(&knock_event_stub, &room_version_rules)?;
let event_id = gen_event_id(&stub, &room_version_rules)?;
// Add event_id
knock_event_stub
.insert("event_id".to_owned(), CanonicalJsonValue::String(event_id.clone().into()));
// It has enough fields to be called a proper event now
let knock_event = knock_event_stub;
// Just verify that this event isn't hilariously malformed before we sent it
// off.
debug!(?stub, "Parsing knock event");
PduEvent::from_id_val(&event_id, stub.clone())
.map_err(|e| err!(BadServerResponse("Invalid knock event PDU: {e:?}")))?;
info!("Asking {remote_server} for send_knock in room {room_id}");
let request = federation::membership::create_knock_event::v1::Request::new(
@@ -543,7 +328,7 @@ async fn knock_room_helper_remote(
event_id.clone(),
services
.sending
.convert_to_outgoing_federation_event(knock_event.clone())
.convert_to_outgoing_federation_event(stub.clone())
.await,
);
@@ -554,126 +339,95 @@ async fn knock_room_helper_remote(
info!("send_knock finished");
info!("Validating send_knock response");
services
.rooms
.short
.get_or_create_shortroomid(room_id)
.await;
let mut state: HashMap<(StateEventType, StateKey), CanonicalJsonObject> =
HashMap::with_capacity(send_knock_response.knock_room_state.len().saturating_add(1));
let mut create_event: Option<(OwnedEventId, CanonicalJsonObject)> = None;
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| {
#[allow(deprecated)]
let raw_value = match event {
| federation::membership::RawStrippedState::Stripped(raw_state) =>
&raw_state.clone().into_json(),
| federation::membership::RawStrippedState::Pdu(raw_value) => raw_value,
| _ => panic!("unknown raw stripped state type"),
};
serde_json::from_str::<CanonicalJsonObject>(raw_value.get())
})
.filter_map(Result::ok);
let mut state_map: HashMap<u64, OwnedEventId> = HashMap::new();
for mut 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;
for (idx, event) in send_knock_response.knock_room_state.iter().enumerate() {
let (state_event_id, key, state_event_json) = match validate_partial_membership_event(
services,
event,
&room_version_rules,
room_id,
idx,
)
.await
{
| Ok(res) => res,
| Err(e) => {
debug_warn!(%idx, "Dropping invalid event from knock_room_state: {e}");
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_rules)?;
let shortstatekey = services
.rooms
.short
.get_or_create_shortstatekey(&event_type, &state_key)
.await;
event.insert("event_id".into(), CanonicalJsonValue::String(event_id.to_string()));
services.rooms.outlier.add_pdu_outlier(&event_id, &event);
state_map.insert(shortstatekey, event_id.clone());
match state.entry(key) {
| Entry::Occupied(entry) => {
debug_warn!(
key=?entry.key(),
"Dropping duplicate state event from knock_room_state"
);
},
| Entry::Vacant(entry) => {
if entry.key().0 == StateEventType::RoomCreate {
create_event = Some((state_event_id, state_event_json.clone()));
}
entry.insert(state_event_json);
},
}
}
info!("Compressing state from send_knock");
let compressed: CompressedState = services
.rooms
.state_compressor
.compress_state_events(state_map.iter().map(|(ssk, eid)| (ssk, eid.borrow())))
.collect()
.await;
if let Some((create_event_id, create_event_json)) = &create_event {
state.retain(|key, event_json| {
if let Err(e) = service::rooms::event_handler::Service::pdu_format_check_1(
event_json,
&room_version_rules,
create_event_id,
) {
debug_warn!(
?key,
"Dropping event from knock_room_state violating room event format: {e}"
);
return false;
}
true
});
debug!("Saving compressed state");
let HashSetCompressStateEvent {
shortstatehash: statehash_before_knock,
added,
removed,
} = services
.rooms
.state_compressor
.save_state(room_id, Arc::new(compressed))
.await?;
// Much like when receiving an invite over federation, if we're in this
// room we'll receive the knock PDU over /send. Otherwise, we need to
// add it as an outlier. Since this function isn't a fallback when local
// knocks fail, we can do this unconditionally.
services
.rooms
.outlier
.add_pdu_outlier(create_event_id, create_event_json);
}
debug!("Forcing state for new room");
services
.rooms
.state
.force_state(room_id, statehash_before_knock, added, removed, &state_lock)
.await?;
state.insert(StateEventType::RoomMember.with_state_key(sender_user.as_str()), stub);
let statehash_after_knock = services
.rooms
.state
.append_to_state(&parsed_knock_pdu, room_id)
.await?;
let knocked_state = state
.into_values()
.filter_map(|event_json| serde_json::value::to_raw_value(&event_json).ok())
.map(RawStrippedState::Pdu)
.collect();
info!("Updating membership locally to knock state with provided stripped state events");
// TODO: see TODO on the other call to `update_membership`
info!("Saving knock data");
services
.rooms
.state_cache
.update_membership(room_id, sender_user, &parsed_knock_pdu, false)
.await?;
info!("Appending room knock event locally");
.mark_as_knocked(sender_user, room_id, knocked_state);
services
.rooms
.timeline
.progress_extremities(&parsed_knock_pdu)
.await?;
services
.rooms
.timeline
.append_pdu(&parsed_knock_pdu, knock_event, room_id)
.state_cache
.update_joined_count(room_id)
.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
.rooms
.state
.set_room_state(room_id, statehash_after_knock, &state_lock);
services.sync.wake(sender_user).await;
Ok(())
}
@@ -683,18 +437,13 @@ async fn make_knock_request(
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 {
) -> Result<(CanonicalJsonObject, RoomVersionId, OwnedServerName)> {
for (idx, remote_server) in servers.iter().enumerate() {
if services.globals.server_is_ours(remote_server) {
continue;
}
info!("Asking {remote_server} for make_knock ({make_knock_counter})");
info!("Asking {remote_server} for make_knock ({})", idx.saturating_add(1));
let mut request = federation::membership::prepare_knock_event::v1::Request::new(
room_id.to_owned(),
@@ -708,36 +457,51 @@ async fn make_knock_request(
.await;
trace!("make_knock response: {make_knock_response:?}");
make_knock_counter = make_knock_counter.saturating_add(1);
if let Ok(r) = &make_knock_response {
if let Err(e) = validate_remote_member_event_stub(
&MembershipState::Knock,
sender_user,
room_id,
&to_canonical_object(&r.event)?,
) {
warn!("make_knock response from {remote_server} failed validation: {e}");
continue;
}
}
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;
match make_knock_response
.and_then(|r| {
to_canonical_object(&r.event)
.map(|o| (o, r.room_version))
.map_err(Into::into)
})
.and_then(|(stub, room_version)| {
validate_remote_member_event_stub(
&MembershipState::Knock,
sender_user,
room_id,
&stub,
)
.map(|()| (stub, room_version))
}) {
| Ok((evt, room_version)) =>
return Ok((evt, room_version, remote_server.to_owned())),
| Err(e) => match e.kind() {
| ErrorKind::IncompatibleRoomVersion(IncompatibleRoomVersionErrorData {
room_version,
..
}) => {
warn!(
"{remote_server} reports the room we are trying to knock on is \
v{room_version}, which we do not support."
);
return Err(e);
},
| ErrorKind::Forbidden => {
warn!("{remote_server} refuses to let us knock: {e}.");
return Err(e);
},
| ErrorKind::NotFound => {
info!(
"{remote_server} does not know about {room_id}: {e}. Will continue \
trying."
);
},
| _ => {
info!("{remote_server} failed to make_knock: {e}. Will continue trying.");
},
},
}
}
make_knock_response_and_server
info!("All {} servers were unable to assist in knocking {room_id} :(", servers.len());
Err!(BadServerResponse("No server available to assist in knocking."))
}
+2 -8
View File
@@ -88,19 +88,13 @@ pub async fn leave_room(
.server_in_room(services.globals.server_name(), room_id)
.eq(&false);
let not_knocked = services
.rooms
.state_cache
.is_knocked(user_id, room_id)
.eq(&false);
pin_mut!(is_banned, is_disabled);
/*
there are three possible cases when leaving a room:
1. the room is banned or disabled, so we're not federating with it.
2. nobody on the homeserver is in the room, which can happen if the user is rejecting an invite
to a room that we don't have any members in.
or rescinding a knock for a room that we don't have any members in.
3. someone else on the homeserver is in the room. in this case we can leave like normal by sending a PDU over federation.
in cases 1 and 2, we have to update the state cache using `mark_as_left` directly.
@@ -113,7 +107,7 @@ pub async fn leave_room(
// case 1: the room is banned/disabled. we don't want to federate with
// another server to leave, so we can't create an outlier PDU.
None
} else if dont_have_room.and(not_knocked).await {
} else if dont_have_room.await {
// case 2: ask a remote server to assist us with leaving
// we always mark the room as left locally, regardless of if the
// federated leave failed
+2 -2
View File
@@ -29,7 +29,7 @@ pub(crate) async fn get_profile_route(
State(services): State<crate::State>,
body: Ruma<get_profile::v3::Request>,
) -> Result<get_profile::v3::Response> {
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
if body.identity.is_none() {
return Err!(Request(Unauthorized(
"This server requires authentication to access user profiles."
)));
@@ -46,7 +46,7 @@ pub(crate) async fn get_profile_field_route(
State(services): State<crate::State>,
body: Ruma<get_profile_field::v3::Request>,
) -> Result<get_profile_field::v3::Response> {
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
if body.identity.is_none() {
return Err!(Request(Unauthorized(
"This server requires authentication to access user profiles."
)));
+23 -9
View File
@@ -9,7 +9,7 @@ use service::Services;
use crate::{Ruma, router::ClientIdentity};
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous`
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous`
pub(crate) async fn discover_rendezvous_route(
State(services): State<crate::State>,
body: Ruma<discover_rendezvous::msc4388::Request>,
@@ -20,7 +20,7 @@ pub(crate) async fn discover_rendezvous_route(
)))
}
/// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/`
/// `POST /_matrix/client/unstable/io.element.msc4388/rendezvous`
pub(crate) async fn create_rendezvous_session_route(
State(services): State<crate::State>,
body: Ruma<create_rendezvous_session::msc4388::Request>,
@@ -32,7 +32,7 @@ pub(crate) async fn create_rendezvous_session_route(
services.rendezvous.create_session(body.data.clone())
}
/// `PUT /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}/{txn_id}`
/// `PUT /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}/{txn_id}`
pub(crate) async fn update_rendezvous_session_route(
State(services): State<crate::State>,
body: Ruma<update_rendezvous_session::msc4388::Request>,
@@ -45,16 +45,30 @@ pub(crate) async fn update_rendezvous_session_route(
)
}
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
pub(crate) async fn get_rendezvous_session_route(
State(services): State<crate::State>,
headers: HeaderMap,
body: Ruma<get_rendezvous_session::msc4388::Request>,
) -> Result<get_rendezvous_session::msc4388::Response> {
if let Some(mode) = headers.get("Sec-Fetch-Mode")
&& let Ok(mode) = mode.to_str()
&& mode == "navigate"
{
let is_navigation_mode = headers
.get_all("Sec-Fetch-Mode")
.iter()
.filter_map(|v| v.to_str().ok())
.any(|mode| {
mode.eq_ignore_ascii_case("navigate") || mode.eq_ignore_ascii_case("nested-navigate")
});
let is_navigation_dest = headers
.get_all("Sec-Fetch-Dest")
.iter()
.filter_map(|v| v.to_str().ok())
.any(|dest| {
matches!(
dest.to_ascii_lowercase().as_str(),
"document" | "iframe" | "frame" | "object" | "embed" | "fencedframe"
)
});
if is_navigation_mode || is_navigation_dest {
return Err!(Request(Forbidden(
"Rendezvous sessions do not accept browser navigation requests."
)));
@@ -63,7 +77,7 @@ pub(crate) async fn get_rendezvous_session_route(
services.rendezvous.get_session(&body.id)
}
/// `DELETE /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
/// `DELETE /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
pub(crate) async fn delete_rendezvous_session_route(
State(services): State<crate::State>,
body: Ruma<delete_rendezvous_session::msc4388::Request>,
+3 -1
View File
@@ -4,10 +4,12 @@ mod event;
mod initial_sync;
mod stripped_state;
mod summary;
mod timestamp_to_event;
mod upgrade;
pub(crate) use self::{
aliases::get_room_aliases_route, create::create_room_route, event::get_room_event_route,
initial_sync::room_initial_sync_route, stripped_state::get_stripped_state_route,
summary::get_room_summary, upgrade::upgrade_room_route,
summary::get_room_summary, timestamp_to_event::get_event_by_timestamp_route,
upgrade::upgrade_room_route,
};
+61
View File
@@ -0,0 +1,61 @@
use axum::extract::State;
use conduwuit::{Err, Event, Result, utils::stream::TryIgnore};
use futures::{StreamExt, pin_mut};
use ruma::api::client::room::get_event_by_timestamp;
use crate::Ruma;
const MAX_CANDIDATES: usize = 20;
/// # `GET /_matrix/client/v1/rooms/{roomId}/timestamp_to_event`
///
/// Gets the ID of the event closest to the given timestamp, in the direction
/// specified by `dir`.
pub(crate) async fn get_event_by_timestamp_route(
State(ref services): State<crate::State>,
body: Ruma<get_event_by_timestamp::v1::Request>,
) -> Result<get_event_by_timestamp::v1::Response> {
let sender_user = body.identity.expect_sender_user()?;
let room_id = &body.room_id;
if !services
.rooms
.state_accessor
.user_can_see_state_events(sender_user, room_id)
.await
{
return Err!(Request(Forbidden("You don't have permission to view this room.")));
}
if !services.rooms.timeline.timestamp_index_ready().await {
return Err!(FeatureDisabled("timestamp_to_event"));
}
let candidates = services
.rooms
.timeline
.pdus_by_timestamp(room_id, body.ts, body.dir)
.ignore_err()
.take(MAX_CANDIDATES);
pin_mut!(candidates);
while let Some((_, pdu)) = candidates.next().await {
if services
.rooms
.state_accessor
.user_can_see_event(sender_user, room_id, pdu.event_id())
.await
{
return Ok(get_event_by_timestamp::v1::Response::new(
pdu.event_id().to_owned(),
pdu.origin_server_ts(),
));
}
}
Err!(Request(NotFound(
"Unable to find event from {} in direction {:?}",
body.ts.get(),
body.dir
)))
}
+22 -11
View File
@@ -1,9 +1,12 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use ruma::{
api::client::discovery::{
discover_homeserver::{self, HomeserverInfo},
discover_policy_server, discover_support,
api::client::{
discovery::{
discover_homeserver::{self, HomeserverInfo},
discover_policy_server, discover_support,
},
rtc,
},
assign,
};
@@ -37,17 +40,25 @@ pub(crate) async fn well_known_client(
}
/// # `GET /_matrix/client/v1/rtc/transports`
/// # `GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports`
///
/// Returns the list of MatrixRTC foci (transports) configured for this
/// homeserver, implementing MSC4143.
/// Returns the list of MatrixRTC transports configured for this homeserver,
/// implementing the stable version of MSC4143.
pub(crate) async fn get_rtc_transports(
State(services): State<crate::State>,
_body: Ruma<ruma::api::client::rtc::transports::msc4143::Request>,
) -> Result<ruma::api::client::rtc::transports::msc4143::Response> {
Ok(ruma::api::client::rtc::transports::msc4143::Response::new(
services.config.matrix_rtc.foci.clone(),
))
_body: Ruma<rtc::transports::v1::Request>,
) -> Result<rtc::transports::v1::Response> {
Ok(rtc::transports::v1::Response::new(services.config.matrix_rtc.foci.clone()))
}
/// # `GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports`
///
/// Unstable version of [`get_rtc_transports`], which names the response field
/// `rtc_transports` instead of `transports`.
pub(crate) async fn get_rtc_transports_unstable(
State(services): State<crate::State>,
_body: Ruma<rtc::transports::msc4143::Request>,
) -> Result<rtc::transports::msc4143::Response> {
Ok(rtc::transports::msc4143::Response::new(services.config.matrix_rtc.foci.clone()))
}
/// # `GET /.well-known/matrix/support`
-3
View File
@@ -16,6 +16,3 @@ pub mod client_ip;
pub mod admin;
pub(crate) use self::router::{Ruma, RumaResponse, State};
conduwuit::mod_ctor! {}
conduwuit::mod_dtor! {}
+25 -6
View File
@@ -52,6 +52,7 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::set_pushrule_actions_route)
.ruma_route(&client::delete_pushrule_route)
.ruma_route(&client::get_room_event_route)
.ruma_route(&client::get_event_by_timestamp_route)
.ruma_route(&client::get_room_aliases_route)
.ruma_route(&client::get_filter_route)
.ruma_route(&client::create_filter_route)
@@ -188,12 +189,25 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::well_known_client)
.ruma_route(&client::well_known_policy_server)
.ruma_route(&client::get_rtc_transports)
.ruma_route(&client::get_rtc_transports_unstable)
.ruma_route(&client::room_initial_sync_route)
.ruma_route(&client::discover_rendezvous_route)
.ruma_route(&client::create_rendezvous_session_route)
.ruma_route(&client::update_rendezvous_session_route)
.ruma_route(&client::get_rendezvous_session_route)
.ruma_route(&client::delete_rendezvous_session_route)
.merge(
Router::new()
.ruma_route(&client::discover_rendezvous_route)
.ruma_route(&client::create_rendezvous_session_route)
.ruma_route(&client::update_rendezvous_session_route)
.ruma_route(&client::get_rendezvous_session_route)
.ruma_route(&client::delete_rendezvous_session_route)
.layer(axum::middleware::map_response(
async |mut response: axum::response::Response| {
response.headers_mut().insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_static("no-store"),
);
response
},
)),
)
.ruma_route(&client::get_authorization_server_metadata_route)
.merge(client::oauth::router(state))
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
@@ -217,7 +231,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
if config.allow_federation {
router = router
.ruma_route(&server::get_server_version_route)
.route("/_matrix/key/v2/server", get(server::get_server_keys_route))
.ruma_route(&server::get_server_keys_route)
.ruma_route(&server::get_remote_server_keys_batch_route)
.ruma_route(&server::get_remote_server_keys_route)
.ruma_route(&server::get_public_rooms_route)
.ruma_route(&server::get_public_rooms_filtered_route)
.ruma_route(&server::send_transaction_message_route)
@@ -244,6 +260,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&server::get_content_route)
.ruma_route(&server::get_content_thumbnail_route)
.route("/_continuwuity/local_user_count", get(client::continuwuity_local_user_count));
if config.experiments.msc4556.is_enabled() {
router = router.ruma_route(&server::get_remote_server_keys_batch_v3_unstable_route);
}
if config.experiments.msc4560.is_enabled() {
router = router.ruma_route(&server::get_stripped_state_route);
}
+17 -3
View File
@@ -11,7 +11,11 @@ use axum::{
use conduwuit::{Error, Result, err, error};
use ruma::{
CanonicalJsonObject,
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
api::{
IncomingRequest, IncomingRequestExt,
auth_scheme::AuthScheme,
error::{DeserializationError, FromHttpRequestError},
},
};
use serde::Deserialize;
@@ -114,8 +118,18 @@ where
.await?;
// Deserialize the body
let body = R::try_from_http_request(request, &borrowed_path)
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
let body_is_empty = body.is_empty();
let body = R::try_from_http_request(request, &borrowed_path).map_err(|e| match e {
| FromHttpRequestError::Deserialization(DeserializationError::Json(ref json_err))
if body_is_empty || json_err.is_syntax() || json_err.is_eof() =>
err!(Request(NotJson(debug_warn!("{e}")))),
| FromHttpRequestError::Deserialization(DeserializationError::Utf8(_)) =>
err!(Request(NotJson(debug_warn!("{e}")))),
| FromHttpRequestError::Deserialization(
DeserializationError::Ident(_) | DeserializationError::Query(_),
) => err!(Request(InvalidParam(debug_warn!("{e}")))),
| _ => err!(Request(BadJson(debug_warn!("{e}")))),
})?;
Ok(Self { body, json_body, identity })
}
+24 -1
View File
@@ -194,6 +194,10 @@ impl CheckAuth for AccessTokenOptional {
authentication: Self::Output,
query: AuthQueryParams,
) -> Result<Self::Identity> {
if R::RATE_LIMITED && is_rendezvous_create_route(TypeId::of::<R>()) {
services.rendezvous.check_create_ratelimit(request_ip)?;
}
if let Some(authentication) = authentication {
check_access_token(
services,
@@ -278,6 +282,11 @@ impl CheckAuth for NoAccessToken {
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
})?;
let is_rendezvous_session = is_rendezvous_session_route(TypeId::of::<R>());
if R::RATE_LIMITED && is_rendezvous_session {
services.rendezvous.check_session_ratelimit(request_ip)?;
}
if let Some(authentication) = authentication {
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
OAuthClientScope::ApiFullAccess,
@@ -285,7 +294,7 @@ impl CheckAuth for NoAccessToken {
.await
.map(Some)
} else {
if R::RATE_LIMITED {
if R::RATE_LIMITED && !is_rendezvous_session {
check_unauthenticated_request_ratelimiting(services, request_ip)?;
}
@@ -433,6 +442,20 @@ async fn check_appservice_token(services: &Services, token: &str) -> Result<Regi
Ok(appservice_info)
}
fn is_rendezvous_create_route(route: TypeId) -> bool {
route == TypeId::of::<client::rendezvous::discover_rendezvous::msc4388::Request>()
|| route
== TypeId::of::<client::rendezvous::create_rendezvous_session::msc4388::Request>()
}
fn is_rendezvous_session_route(route: TypeId) -> bool {
route == TypeId::of::<client::rendezvous::get_rendezvous_session::msc4388::Request>()
|| route
== TypeId::of::<client::rendezvous::update_rendezvous_session::msc4388::Request>()
|| route
== TypeId::of::<client::rendezvous::delete_rendezvous_session::msc4388::Request>()
}
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
if services
.config
+92 -63
View File
@@ -12,8 +12,8 @@ use conduwuit::{
warn,
};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedUserId, ServerName,
UserId,
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId,
ServerName, UserId,
api::{
error::{ErrorKind, IncompatibleRoomVersionErrorData},
federation::membership::{RawStrippedState, create_invite},
@@ -22,6 +22,7 @@ use ruma::{
room_version_rules::RoomVersionRules,
};
use serde::Deserialize;
use service::Services;
use crate::{Ruma, server::utils::validate_any_membership_event};
@@ -45,7 +46,7 @@ pub(crate) async fn create_invite_route(
}
async fn create_invite(
services: &crate::State,
services: &Services,
body: Ruma<create_invite::v2::Request>,
) -> Result<create_invite::v2::Response> {
if !services.server.supported_room_version(&body.room_version) {
@@ -79,7 +80,7 @@ async fn create_invite(
via=?body.via,
"Validating invite room state for invite request"
);
let (create_event_id, state) = validate_invite_state(
let (create_event_id, state) = validate_partial_membership_state(
services,
&body.invite_room_state,
&room_version_rules,
@@ -260,7 +261,7 @@ async fn create_invite(
///
/// [spec]: https://spec.matrix.org/v1.19/server-server-api/#put_matrixfederationv2inviteroomideventid
async fn validate_invite_membership_event(
services: &crate::State,
services: &Services,
body: &serde_json::value::RawValue,
room_version_rules: &RoomVersionRules,
origin: &ServerName,
@@ -299,83 +300,111 @@ async fn validate_invite_membership_event(
Ok((pdu, sender_user, recipient_user))
}
/// Validates a single event from partial membership state (`invite_room_state`
/// or `knock_room_state`), returning its event ID, `(event_type, state_key)`,
/// and parsed canonical JSON.
pub(crate) async fn validate_partial_membership_event(
services: &Services,
event: &RawStrippedState,
room_version_rules: &RoomVersionRules,
room_id: &RoomId,
idx: usize,
) -> Result<(OwnedEventId, (StateEventType, StateKey), CanonicalJsonObject)> {
// Stripped state hasn't been sent over federation since v1.16.
let RawStrippedState::Pdu(raw_pdu) = event else {
debug!(%idx, "Partial membership state event is not a PDU");
return Err!(Request(InvalidParam(
"PDU in partial membership state (index {idx}) violates the room event format"
)));
};
let (state_event_room_id, state_event_id, state_event_json) = services
.rooms
.event_handler
.parse_incoming_pdu(raw_pdu, Some(room_version_rules))
.await
.map_err(|e| {
err!(Request(InvalidParam(debug_warn!(
"Invalid PDU in partial membership state: {e}"
))))
})?;
if state_event_room_id != room_id {
return Err!(Request(InvalidParam(debug_warn!(
%state_event_room_id,
%room_id,
"PDU in partial membership state ({state_event_id}) belongs to the wrong room"
))));
}
services
.server_keys
.verify_event_json(&state_event_json, room_version_rules)
.await
.map_err(|e| {
err!(Request(InvalidParam(
"Signature verification failed on partial membership state event: {e}"
)))
})?;
let Some(state_key) = state_event_json.get("state_key").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_info!(
"PDU in partial membership state ({state_event_id}) is not a state event"
))));
};
let Some(event_type) = state_event_json.get("type").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_warn!(
"PDU in partial membership state ({state_event_id}) is not an event?"
))));
};
let key = StateEventType::from(event_type).with_state_key(state_key);
if key.0 == StateEventType::RoomCreate {
// Ensure this is a legal create event.
let pdu_event = PduEvent::from_id_val(&state_event_id, state_event_json.clone())
.expect("must be able to create pdu event from event json");
debug!("Validating discovered create event in partial membership room state");
validate_invite_create_event(&pdu_event, room_version_rules).await?;
}
Ok((state_event_id, key, state_event_json))
}
/// Validates the *invite state* of an invite request, per the steps listed
/// under the endpoint's [spec].
///
/// Returns the create event's event ID, and the partial state map.
///
/// [spec]: https://spec.matrix.org/v1.19/server-server-api/#put_matrixfederationv2inviteroomideventid
async fn validate_invite_state(
services: &crate::State,
pub(crate) async fn validate_partial_membership_state(
services: &Services,
invite_state: &[RawStrippedState],
room_version_rules: &RoomVersionRules,
room_id: OwnedRoomId,
) -> Result<(OwnedEventId, HashMap<(StateEventType, StateKey), CanonicalJsonObject>)> {
trace!(?invite_state, "Raw invite state");
trace!(?invite_state, "Raw partial membership state");
let mut invite_state_map: HashMap<(StateEventType, StateKey), _> =
HashMap::with_capacity(invite_state.len());
let mut create_event_id: Option<OwnedEventId> = None;
for (idx, invite_state_event) in invite_state.iter().cloned().enumerate() {
trace!(%idx, ?invite_state_event, "Invite state event");
// Stripped state hasn't been sent over federation since v1.16.
let RawStrippedState::Pdu(raw_pdu) = invite_state_event else {
debug!(%idx, "Invite state event is not a PDU");
return Err!(Request(InvalidParam(
"PDU in invite state (index {idx}) violates the room event format"
)));
};
let (state_event_room_id, state_event_id, state_event_json) = services
.rooms
.event_handler
.parse_incoming_pdu(&raw_pdu, Some(room_version_rules))
.await
.map_err(|e| {
err!(Request(InvalidParam(debug_warn!("Invalid PDU in invite state: {e}"))))
})?;
for (idx, invite_state_event) in invite_state.iter().enumerate() {
trace!(%idx, ?invite_state_event, "Partial membership state event");
let (state_event_id, key, state_event_json) = validate_partial_membership_event(
services,
invite_state_event,
room_version_rules,
&room_id,
idx,
)
.await?;
if state_event_room_id != room_id {
return Err!(Request(InvalidParam(debug_warn!(
%state_event_room_id,
%room_id,
"PDU in invite state ({state_event_id}) belongs to the wrong room"
))));
}
services
.server_keys
.verify_event_json(&state_event_json, room_version_rules)
.await
.map_err(|e| {
err!(Request(InvalidParam("Signature verification failed on invite event: {e}")))
})?;
let Some(state_key) = state_event_json.get("state_key").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_info!(
"PDU in invite state ({state_event_id}) is not a state event"
))));
};
let Some(event_type) = state_event_json.get("type").and_then(|k| k.as_str()) else {
return Err!(Request(InvalidParam(debug_warn!(
"PDU in invite state ({state_event_id}) is not an event?"
))));
};
let key = StateEventType::from(event_type).with_state_key(state_key);
match invite_state_map.entry(key) {
| Entry::Occupied(entry) =>
return Err!(Request(InvalidParam(
"Duplicate state events in invite state for state key: {:?}",
"Duplicate state events in partial membership state for state key: {:?}",
entry.key(),
))),
| Entry::Vacant(entry) => {
if entry.key().0 == StateEventType::RoomCreate {
// Ensure this is a legal create event.
let pdu_event =
PduEvent::from_id_val(&state_event_id, state_event_json.clone())
.expect("must be able to create pdu event from event json");
debug!("Validating discovered create event in invite room state");
validate_invite_create_event(&pdu_event, room_version_rules).await?;
create_event_id = Some(state_event_id);
}
entry.insert(state_event_json);
@@ -385,7 +414,7 @@ async fn validate_invite_state(
let Some(create_event_id) = create_event_id else {
return Err!(Request(InvalidParam(debug_warn!(
parsed_state=?invite_state_map,
"Invite state does not contain the m.room.create event"
"Partial membership state does not contain the m.room.create event"
))));
};
invite_state_map.iter().try_for_each(|(key, event_json)| {
@@ -396,7 +425,7 @@ async fn validate_invite_state(
)
.map_err(|e| {
err!(Request(InvalidParam(
"PDU in invite state for {key:?} violates the room event format: {e}"
"PDU in partial membership state for {key:?} violates the room event format: {e}"
)))
})
})?;
@@ -414,7 +443,7 @@ struct MFederate {
///
/// 1. It passes auth checks (aka is valid)
/// 2. The room is federated (there's no point persisting unfederated rooms)
async fn validate_invite_create_event(
pub(crate) async fn validate_invite_create_event(
pdu: &PduEvent,
room_version_rules: &RoomVersionRules,
) -> Result {
+288 -68
View File
@@ -1,89 +1,309 @@
use std::{collections::BTreeMap, mem::take, time::Duration};
use std::{
collections::{BTreeMap, HashSet},
sync::Arc,
time::Instant,
};
use axum::{Json, extract::State, response::IntoResponse};
use conduwuit::{Result, utils::timepoint_from_now};
use futures::StreamExt;
use axum::extract::State;
use conduwuit::{
Err, Result,
config::experiments::ToggledExperiment,
debug_info,
utils::{ReadyExt, stream::automatic_width},
};
use ruma::{
MilliSecondsSinceUnixEpoch,
api::{
OutgoingResponseExt,
federation::discovery::{OldVerifyKey, ServerSigningKeys, get_server_keys},
MilliSecondsSinceUnixEpoch, OwnedServerName, OwnedServerSigningKeyId,
api::federation::discovery::{
ServerSigningKeys, get_remote_server_keys, get_remote_server_keys_batch,
get_remote_server_keys_batch::v2::QueryCriteria, get_server_keys,
},
assign,
serde::Raw,
};
use service::{server_keys, server_keys::in_one_week};
use service::server_keys::{self, in_one_week};
use crate::router::Ruma;
/// # `GET /_matrix/key/v2/server`
///
/// Gets the public signing keys of this server.
pub(crate) async fn get_server_keys_route(
State(services): State<crate::State>,
) -> Result<impl IntoResponse> {
let server_name = services.globals.server_name();
let verify_keys = BTreeMap::from([services.server_keys.active_verify_key()]);
_body: Ruma<get_server_keys::v2::Request>,
) -> Result<get_server_keys::v2::Response> {
services
.server_keys
.build_server_keys_response()
.await
.map(get_server_keys::v2::Response::new)
}
let old_verify_keys = if let Some(k) = &services.config.old_verify_keys {
k.to_owned()
} else {
// We need to figure out any old signing keys we've acquired from
// notaries.
let mut keys = services.server_keys.signing_keys_for(server_name);
let mut old_keys = BTreeMap::new();
while let Some(resp) = keys.next().await {
// We need to verify that this response is still trusted based on
// the current configuration. It's possible we got this response
// from a notary who we no longer trust.
if resp.parsed.valid_until_ts > in_one_week() {
continue;
}
let trusted = services.config.trusted_servers.iter().any(|notary| {
server_keys::Service::verify_server_keys_response(
&resp,
Some((notary.server_name(), notary.verify_keys())),
)
.is_ok()
});
if !trusted {
continue;
}
for (old_key_id, old_key) in resp.parsed.old_verify_keys {
if old_key.expired_ts > resp.parsed.valid_until_ts {
// This key expired in the future which is probably illegal
continue;
}
old_keys
.entry(old_key_id)
.and_modify(|current_old_key: &mut OldVerifyKey| {
// Use the lowest expiry timestamp
if current_old_key.expired_ts > old_key.expired_ts {
*current_old_key = old_key.clone();
}
})
.or_insert(old_key);
}
const MAX_KEYS_PER_QUERY: usize = 16384;
const MAX_SERVERS_PER_QUERY: usize = 4096;
/// # `POST /_matrix/key/v2/query`
///
/// Fetches remote server signing keys in bulk, seeding from the local server's
/// database.
///
/// This route applies a semaphore to slow down requests that query more signing
/// keys than is allowed by [MSC4556].
///
/// [MSC4556]: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
pub(crate) async fn get_remote_server_keys_batch_route(
State(services): State<crate::State>,
body: Ruma<get_remote_server_keys_batch::v2::Request>,
) -> Result<get_remote_server_keys_batch::v2::Response> {
query_inner(&services, &body.server_keys, true)
.await
.map(get_remote_server_keys_batch::v2::Response::new)
}
/// # `POST /_matrix/key/unstable/org.continuwuity.msc4556/query`
/// ## `POST /_matrix/key/v3/query`
///
/// Fetches remote server signing keys in bulk, seeding from the local server's
/// database.
///
/// MSC4556: https://github.com/matrix-org/matrix-spec-proposals/pull/4556
pub(crate) async fn get_remote_server_keys_batch_v3_unstable_route(
State(services): State<crate::State>,
body: Ruma<ruminuwuity::federation::notary::unstable::Request>,
) -> Result<ruminuwuity::federation::notary::unstable::Response> {
query_inner(&services, &body.server_keys, false)
.await
.map(ruminuwuity::federation::notary::unstable::Response::new)
}
/// Handles querying the server keys for `/_matrix/key/*/query`.
///
/// `v2` should be `true` if the request path is `/_matrix/key/v2/query` - this
/// will potentially apply a rate-limit to the request.
async fn query_inner(
services: &crate::State,
body: &BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>,
v2: bool,
) -> Result<Vec<Raw<ServerSigningKeys>>> {
let start = (Instant::now(), MilliSecondsSinceUnixEpoch::now());
// If the remote server isn't asking for any keys, we can return an empty
// array immediately.
if body.is_empty() {
return Ok(Vec::new());
}
// Count how many keys are being requested.
// Each server incurs a cost of at least one, and then the count of each key
// being queried per-server.
let total_queried_servers = body.len();
let total_queried_keys = body
.values()
.fold(0_usize, |acc, q| acc.saturating_add(q.len().max(1)));
if !v2 && services.config.experiments.msc4556.is_enabled() {
// If we're on the v3 endpoint, we can apply these limits explicitly.
if total_queried_servers > MAX_SERVERS_PER_QUERY {
return Err!(Request(TooLarge(
"Too many server keys requested ({total_queried_servers} > \
{MAX_SERVERS_PER_QUERY}",
)));
}
old_keys
if total_queried_keys > MAX_KEYS_PER_QUERY {
return Err!(Request(TooLarge(
"Too many keys requested ({total_queried_keys} > {MAX_KEYS_PER_QUERY})"
)));
}
}
let penalise =
total_queried_servers > MAX_SERVERS_PER_QUERY || total_queried_keys > MAX_KEYS_PER_QUERY;
debug_info!("Fetching {total_queried_keys} keys across {} servers", body.len());
let mut futs: tokio::task::JoinSet<_> = tokio::task::JoinSet::new();
// If we're on the v2 endpoint, we aren't allowed to reject the request.
// To avoid overloading the server, we'll apply a semaphore to limit how
// many futures can be active at a time.
let width = automatic_width();
let semaphore: Option<Arc<tokio::sync::Semaphore>> = if v2 && penalise {
Some(Arc::new(tokio::sync::Semaphore::new(width)))
} else {
None
};
let server_key = assign!(ServerSigningKeys::new(server_name.to_owned(), valid_until_ts()), {
verify_keys,
old_verify_keys,
});
for (server_name, queries) in body.clone() {
let server_keys = services.server_keys.clone();
let semaphore = semaphore.clone();
let server_key = Raw::new(&server_key)?;
let mut response = get_server_keys::v2::Response::new(server_key)
.try_into_http_response::<Vec<u8>>()
.map(|mut response| take(response.body_mut()))
.and_then(|body| serde_json::from_slice(&body).map_err(Into::into))?;
futs.spawn_on(
async move {
let _permit = if let Some(sem) = semaphore {
let cost = queries
.len()
.saturating_add(1)
.min(automatic_width())
.try_into()
.unwrap_or(u32::MAX);
services.server_keys.sign_json(&mut response)?;
sem.acquire_many_owned(cost).await.ok()
} else {
None
};
Ok(Json(response))
acquire_keys_as_notary(server_keys, server_name, queries, start.1).await
},
services.server.runtime(),
);
}
let mut response = Vec::with_capacity(total_queried_keys);
while let Some(Ok(v)) = futs.join_next().await {
response.extend(v);
}
debug_info!(
elapsed=?start.0.elapsed(),
%total_queried_servers,
%total_queried_keys,
"Fetched {} key responses",
response.len()
);
Ok(response)
}
fn valid_until_ts() -> MilliSecondsSinceUnixEpoch {
let dur = Duration::from_hours(12);
let timepoint = timepoint_from_now(dur).expect("SystemTime should not overflow");
MilliSecondsSinceUnixEpoch::from_system_time(timepoint).expect("UInt should not overflow")
/// `GET /_matrix/key/v2/query/{serverName}`
///
/// Fetches the latest keys for a specific server name.
pub(crate) async fn get_remote_server_keys_route(
State(services): State<crate::State>,
body: Ruma<get_remote_server_keys::v2::Request>,
) -> Result<get_remote_server_keys::v2::Response> {
let server_keys = acquire_keys_as_notary(
services.server_keys.clone(),
body.server_name.clone(),
BTreeMap::new(),
body.minimum_valid_until_ts,
)
.await;
Ok(get_remote_server_keys::v2::Response::new(server_keys))
}
#[tracing::instrument(skip(server_keys, queries, start))]
async fn acquire_keys_as_notary(
server_keys: Arc<server_keys::Service>,
remote: OwnedServerName,
queries: BTreeMap<OwnedServerSigningKeyId, QueryCriteria>,
start: MilliSecondsSinceUnixEpoch,
) -> Vec<Raw<ServerSigningKeys>> {
let mut candidate_remote_keys = Vec::with_capacity(queries.len().max(1));
// If we haven't contacted the origin recently, we need to do that now
// to update our caches, and we might as well use its response as a
// candidate.
if server_keys.origin_not_contacted_recently(&remote) {
if let Ok(remote_keys) = server_keys.origin_request(remote.clone(), start).await {
debug_info!("Considering keys from origin response");
candidate_remote_keys.push(remote_keys);
}
}
if queries.is_empty() {
// The querying server wants all of the origin's keys. If we decided to
// contact it earlier, we can safely assume its response already
// includes all of its keys. Otherwise, we'll add all of our cached
// responses as candidates.
if candidate_remote_keys.is_empty() {
debug_info!("Querying server wants all keys, considering all cached key responses");
server_keys
.signing_keys_for(&remote)
.ready_for_each(|remote_keys| candidate_remote_keys.push(remote_keys))
.await;
}
} else {
// The querying server is asking for specific key IDs.
for key_id in queries.keys() {
if let Some(remote_keys) = server_keys.get_signing_key(&remote, key_id).await {
debug_info!(?key_id, "Considering cached response containing key");
candidate_remote_keys.push(remote_keys);
} else {
debug_info!(?key_id, "No cached response contains key");
}
}
}
// Now we need to filter and sign the remote key responses.
// The signing key responses containing the keys the querying server wants.
let mut signed_remote_key_responses = Vec::with_capacity(queries.len().max(1));
// The key IDs we've already included in a response.
let mut signed_remote_key_ids = HashSet::with_capacity(queries.len().max(1));
for remote_keys in candidate_remote_keys {
// Skip this key response if all of its keys were already included
// in other key responses.
if remote_keys
.all_key_ids()
.all(|key_id| signed_remote_key_ids.contains(key_id))
{
continue;
}
// Skip this key response if it expires too far in the future.
if remote_keys.parsed.valid_until_ts > in_one_week() {
continue;
}
// Check query criteria (currently just the minimum expiry time) for
// each key included in this key response. We skip this response if
// _all_ of the keys in the response fail their criteria.
let all_verify_keys_expired = remote_keys.parsed.verify_keys.keys().all(|key_id| {
let minimum_valid_until_ts = queries
.get(key_id)
.and_then(|criterion| criterion.minimum_valid_until_ts)
.unwrap_or(start);
remote_keys.parsed.valid_until_ts < minimum_valid_until_ts
});
let all_old_verify_keys_too_old =
remote_keys
.parsed
.old_verify_keys
.iter()
.all(|(key_id, key)| {
if let Some(criterion) = queries.get(key_id)
&& let Some(minimum_valid_until_ts) = criterion.minimum_valid_until_ts
{
key.expired_ts < minimum_valid_until_ts
} else {
// If the querying server didn't explicitly set a
// minimum timestamp for an old verify key,
// we should treat it as valid.
false
}
});
if all_verify_keys_expired && all_old_verify_keys_too_old {
continue;
}
// This response is acceptable, let's sign and send it.
let signed_remote_keys = server_keys
.self_sign_signing_keys(&remote, &remote_keys.raw)
.expect("should be able to sign remote keys");
signed_remote_key_responses.push(signed_remote_keys);
for key_id in remote_keys.all_key_ids() {
signed_remote_key_ids.insert(key_id.to_owned());
}
}
signed_remote_key_responses
}
+2 -1
View File
@@ -332,6 +332,7 @@ async fn handle_room(
room_id: OwnedRoomId,
pdus: impl Iterator<Item = Pdu> + Send,
) -> std::result::Result<Vec<(OwnedEventId, Result)>, TransactionError> {
let arrived = millis_since_unix_epoch();
let _room_lock = services
.rooms
.event_handler
@@ -392,7 +393,7 @@ async fn handle_room(
.federation_incoming_pdu_duration
.record(start.elapsed().as_secs_f64(), std::slice::from_ref(&outcome));
if let (Ok(()), Some(ts)) = (&result, origin_server_ts) {
let lag = millis_since_unix_epoch().saturating_sub(ts);
let lag = arrived.saturating_sub(ts);
instruments
.federation_incoming_pdu_lag
.record(Duration::from_millis(lag).as_secs_f64(), &[]);
+1 -3
View File
@@ -63,7 +63,7 @@ pub(crate) async fn create_knock_event_v1_route(
return Err!(Request(Forbidden("Room version does not support knocking.")));
}
let (mut event, target_membership, sender, target) = validate_any_membership_event(
let (event, target_membership, sender, target) = validate_any_membership_event(
&services,
&body.pdu,
&room_version_rules,
@@ -83,8 +83,6 @@ pub(crate) async fn create_knock_event_v1_route(
return Err!(Request(InvalidParam("Sender does not match state key")));
}
event.insert("event_id".to_owned(), body.event_id.as_str().into());
let pdu = PduEvent::from_id_val(&body.event_id, event.clone())
.map_err(|e| err!(Request(InvalidParam("Invalid knock event PDU: {e}"))))?;
+1 -1
View File
@@ -84,7 +84,7 @@ impl AccessCheck<'_> {
///
/// A resulting tuple of (PDU JSON, target membership state, sender, recipient).
pub(crate) async fn validate_any_membership_event(
services: &crate::State,
services: &Services,
body: &serde_json::value::RawValue,
room_version_rules: &RoomVersionRules,
create_event_id: OwnedEventId,
+4 -9
View File
@@ -20,9 +20,6 @@ crate-type = [
brotli_compression = [
"reqwest/brotli",
]
conduwuit_mods = [
"dep:libloading"
]
gzip_compression = [
"reqwest/gzip",
]
@@ -41,12 +38,12 @@ mimalloc = [
]
jemalloc_conf = []
jemalloc_prof = [
"tikv-jemalloc-sys/profiling",
"tikv-jemalloc-sys?/profiling",
]
jemalloc_stats = [
"tikv-jemalloc-sys/stats",
"tikv-jemalloc-ctl/stats",
"tikv-jemallocator/stats",
"tikv-jemalloc-sys?/stats",
"tikv-jemalloc-ctl?/stats",
"tikv-jemallocator?/stats",
]
perf_measurements = []
release_max_log_level = [
@@ -85,8 +82,6 @@ http-body-util.workspace = true
http.workspace = true
ipaddress.workspace = true
libc.workspace = true
libloading.workspace = true
libloading.optional = true
lettre.workspace = true
num-traits.workspace = true
rand.workspace = true
+16
View File
@@ -118,6 +118,22 @@ pub struct Experiments {
/// default: false
#[serde(default)]
pub msc4494: SimpleExperiment,
/// MSC4556: Notary request limits
///
/// Creates a new key notary server route that has stricter limits on how
/// many signing keys can be requested in one query, to avoid a resource
/// exhaustion exploit vector in the existing key notary endpoint.
///
/// Continuwuity mitigates the exploit vector in the old notary endpoint
/// anyway, so you do not need to enable this to be protected.
///
/// Requires that remote servers support this MSC before it does anything.
///
/// https://github.com/matrix-org/matrix-spec-proposals/pull/4556
///
/// default: false
#[serde(default)]
pub msc4556: SimpleExperiment,
/// MSC4560: Stripped state requests over federation
///
/// Implements a more efficient way for servers to acquire and serve
+142 -85
View File
@@ -1,8 +1,6 @@
use std::{
cell::{Cell, RefCell},
ops::Deref,
ptr,
ptr::null_mut,
ptr::NonNull,
sync::{
Arc,
atomic::{AtomicPtr, Ordering},
@@ -10,119 +8,178 @@ use std::{
};
use super::Config;
use crate::Result;
use crate::{Result, SyncMutex};
/// The configuration manager is an indirection to reload the configuration for
/// the server while it is running. In order to not burden or clutter the many
/// callsites which query for configuration items, this object implements Deref
/// for the actively loaded configuration.
///
/// Every installed `Arc<Config>` is kept at a stable heap address in `retired`
/// for the entire lifetime of `Manager` (intentionally retaining prior configs
/// across the rare, admin-triggered reloads until shutdown). Because
/// `Deref::deref(&self)` ties the returned `&Arc<Config>` lifetime to `&self`,
/// readers can perform a single `Acquire` load with no locking, no TLS, and no
/// risk of dangling or aliasing UB across reloads.
pub struct Manager {
active: AtomicPtr<Config>,
active: AtomicPtr<Arc<Config>>,
/// Append-only owner of every `Box<Arc<Config>>` ever published to
/// `active` (including the currently active config). Entries are only
/// freed when `Manager` itself is dropped (`&mut self`), guaranteeing that
/// any `&Arc<Config>` returned by `Deref::deref` remains valid and
/// immutable for the lifetime of `self`.
retired: SyncMutex<Vec<PinnedConfig>>,
}
thread_local! {
static INDEX: Cell<usize> = 0.into();
static HANDLE: RefCell<Handles> = const {
RefCell::new([const { None }; HISTORY])
};
/// Heap-pinned `Arc<Config>` stored as a raw `NonNull` rather than `Box` so
/// moving it (e.g., when `Vec` reallocates) never retags or invalidates raw
/// pointers previously published to `Manager::active`.
struct PinnedConfig(NonNull<Arc<Config>>);
// SAFETY: `Arc<Config>` is `Send + Sync`, and `PinnedConfig` uniquely owns the
// `Box<Arc<Config>>` allocation until it is dropped in `Manager::drop`.
unsafe impl Send for PinnedConfig {}
impl PinnedConfig {
fn new(config: Config) -> Self {
let ptr = Box::into_raw(Box::new(Arc::new(config)));
Self(NonNull::new(ptr).expect("Box::into_raw returned null"))
}
#[inline]
const fn as_ptr(&self) -> *mut Arc<Config> { self.0.as_ptr() }
}
type Handle = Option<Arc<Config>>;
type Handles = [Handle; HISTORY];
const HISTORY: usize = 8;
impl Drop for PinnedConfig {
fn drop(&mut self) {
// SAFETY: `self.0` was created via `Box::into_raw` in
// `PinnedConfig::new` and is only dropped when `Manager` itself is
// dropped (`&mut self`), after all borrows derived from `Deref::deref`
// have ended.
unsafe {
drop(Box::from_raw(self.0.as_ptr()));
}
}
}
impl Manager {
pub(crate) fn new(config: Config) -> Self {
let config = Arc::new(config);
let pinned = PinnedConfig::new(config);
let ptr = pinned.as_ptr();
Self {
active: AtomicPtr::new(Arc::into_raw(config).cast_mut()),
active: AtomicPtr::new(ptr),
retired: SyncMutex::new(vec![pinned]),
}
}
/// Update the active configuration, returning prior configuration.
#[tracing::instrument(skip_all, level = "info")]
pub fn update(&self, config: Config) -> Result<Arc<Config>> {
let config = Arc::new(config);
let new = Arc::into_raw(config);
let old = self.active.swap(new.cast_mut(), Ordering::AcqRel);
let pinned = PinnedConfig::new(config);
let new_ptr = pinned.as_ptr();
// SAFETY: The old active pointer was set using an Arc::into_raw().
// We're obliged to reconstitute that into Arc otherwise it will leak.
Ok(unsafe { Arc::from_raw(old) })
}
let mut retired = self.retired.lock();
// Push before publishing to `active` so ownership is recorded even if
// `Vec::push` were to unwind.
retired.push(pinned);
fn load(&self, handle: &mut [Option<Arc<Config>>]) -> &'static Arc<Config> {
let config = self.active.load(Ordering::Acquire);
// `Release` publishes the initialized `Box<Arc<Config>>` to readers
// performing `Acquire` loads in `Deref::deref`.
let old_ptr = self.active.swap(new_ptr, Ordering::AcqRel);
// Branch taken after config reload or first access by this thread.
if handle[INDEX.get()]
.as_ref()
.is_none_or(|handle| !ptr::eq(config, Arc::as_ptr(handle)))
{
INDEX.set(INDEX.get().wrapping_add(1).wrapping_rem(HISTORY));
return load_miss(handle, INDEX.get(), config);
}
// SAFETY: `old_ptr` points to a `PinnedConfig` still owned by `retired`
// and cannot be freed until `Manager` is dropped.
let old = unsafe { Arc::clone(&*old_ptr) };
let config: &Arc<Config> = handle[INDEX.get()]
.as_ref()
.expect("handle was already cached for this thread");
// SAFETY: The caller should not hold multiple references at a time
// directly into Config, as a subsequent reference might invalidate
// the thread's cache causing another reference to dangle.
//
// This is a highly unusual pattern as most config values are copied by
// value or used immediately without running overlap with another
// value. Even if it does actually occur somewhere, the window of
// danger is limited to the config being reloaded while the reference
// is held and another access is made by the same thread into a
// different config value. This is mitigated by creating a buffer
// of old configs rather than discarding at the earliest opportunity;
// the odds of this scenario are thus astronomical.
unsafe { std::mem::transmute(config) }
}
}
impl Drop for Manager {
fn drop(&mut self) {
let config = self.active.swap(null_mut(), Ordering::AcqRel);
// SAFETY: The active pointer was set using an Arc::into_raw(). We're
// obliged to reconstitute that into Arc otherwise it will leak.
unsafe { Arc::from_raw(config) };
Ok(old)
}
}
impl Deref for Manager {
type Target = Arc<Config>;
fn deref(&self) -> &Self::Target { HANDLE.with_borrow_mut(|handle| self.load(handle)) }
#[inline]
fn deref(&self) -> &Self::Target {
let ptr = self.active.load(Ordering::Acquire);
// SAFETY: `ptr` was initialized in `Manager::new` or published via
// `Ordering::AcqRel` in `Manager::update` and points to a
// `PinnedConfig` in `self.retired`. Entries in `self.retired` are never
// removed or mutated until `Manager` is dropped (`&mut self`), so the
// returned `&'self Arc<Config>` remains valid and immutable for the
// entire borrow of `self`.
unsafe { &*ptr }
}
}
#[tracing::instrument(
name = "miss",
level = "trace",
skip_all,
fields(%index, ?config)
)]
#[allow(clippy::transmute_ptr_to_ptr)]
fn load_miss(
handle: &mut [Option<Arc<Config>>],
index: usize,
config: *const Config,
) -> &'static Arc<Config> {
// SAFETY: The active pointer was set prior and always remains valid. We're
// reconstituting the Arc here but as a new reference, so the count is
// incremented. This instance will be cached in the thread-local.
let config = unsafe {
Arc::increment_strong_count(config);
Arc::from_raw(config)
};
#[cfg(test)]
mod tests {
use std::thread;
// SAFETY: See the note on the transmute above. The caller should not hold
// more than one reference at a time directly into Config, as the second
// access might invalidate the thread's cache, dangling the reference to
// the first.
unsafe { std::mem::transmute(handle[index].insert(config)) }
use super::*;
fn test_config(server_name: &str) -> Config {
use figment::{
Figment,
providers::{Format, Toml},
};
let raw = format!("server_name = \"{server_name}\"\ndatabase_path = \"/tmp\"\n");
Figment::new()
.merge(Toml::string(&raw))
.extract()
.expect("valid test config")
}
#[test]
fn deref_survives_many_reloads() {
let manager = Manager::new(test_config("initial.example"));
let first: &Arc<Config> = &manager;
let first_name: &str = first.server_name.as_str();
for i in 0..32 {
let prev = manager
.update(test_config(&format!("reload-{i}.example")))
.expect("update succeeds");
if i == 0 {
assert_eq!(prev.server_name.as_str(), "initial.example");
}
}
// Original reference remains valid and unchanged after > HISTORY
// reloads.
assert_eq!(first_name, "initial.example");
assert_eq!(manager.server_name.as_str(), "reload-31.example");
}
#[test]
fn concurrent_reads_and_updates() {
let manager = Manager::new(test_config("start.example"));
thread::scope(|s| {
for _ in 0..4 {
s.spawn(|| {
for _ in 0..200 {
let cfg: &Arc<Config> = &manager;
assert!(cfg.server_name.as_str().ends_with(".example"));
}
});
}
s.spawn(|| {
for i in 0..32 {
let _ = manager
.update(test_config(&format!("iter-{i}.example")))
.expect("update succeeds");
}
});
});
}
#[test]
fn reference_outlives_scoped_thread() {
let manager = Manager::new(test_config("scoped.example"));
let cfg_ref: &Arc<Config> = thread::scope(|s| s.spawn(|| &*manager).join().unwrap());
assert_eq!(cfg_ref.server_name.as_str(), "scoped.example");
}
}
+47 -51
View File
@@ -195,7 +195,7 @@ pub struct Config {
/// announcements or major updates. This is not an update check endpoint.
///
/// default: true
#[serde(alias = "allow_check_for_updates", default = "true_fn")]
#[serde(default = "true_fn")]
pub allow_announcements_check: bool,
/// Set this to any float value to multiply continuwuity's in-memory LRU
@@ -490,7 +490,7 @@ pub struct Config {
#[serde(default = "default_ip_lookup_strategy")]
pub ip_lookup_strategy: u8,
/// The preferred source to use for getting the real client IP.
/// DEPRECATED: The preferred source to use for getting the real client IP.
///
/// Takes any of the following options:
///
@@ -509,9 +509,10 @@ pub struct Config {
/// to set this header" check; if the header selected is present, it is
/// used.
///
/// Ignored if `accepted_ip_sources` is set.
/// Ignored if `accepted_ip_sources` is set. `accepted_ip_sources` is
/// the preferred alternative.
///
/// If not set set, `direct` is used. Additionally, `direct` is used
/// If not set, `direct` is used. Additionally, `direct` is used
/// as a fallback if the chosen header is not found.
#[serde(default)]
pub request_ip_source: Option<String>,
@@ -919,19 +920,6 @@ pub struct Config {
#[serde(default)]
pub forget_forced_upon_leave: bool,
/// Set this to true to require authentication when looking up user profiles
/// through this server.
///
/// By default this is false, allowing tools such as matrix.to to access
/// profiles of users on this server and on other servers.
/// Setting this to true will block those tools, and may block automated
/// crawlers from scraping users' profiles, although it will not block
/// other homeservers from accessing users' profiles.
///
/// default: false
#[serde(default)]
pub require_auth_for_profile_requests: bool,
/// Set this to true to require authentication to create a rendezvous
/// session. Rendezvous sessions are used for QR code login.
///
@@ -1153,10 +1141,7 @@ pub struct Config {
/// (trusted key notary servers), as well as serve as trusted servers for
/// other operations like backfill and event fetching.
///
/// Currently, continuwuity doesn't support inbound key requests, so
/// this list should only contain other Synapse servers.
///
/// example: ["matrix.org", "starstruck.systems"]
/// example: ["continuwuity.org", "matrix.org"]
///
/// It is possible to restrict which signing keys trusted servers are
/// allowed to sign responses with. Without configuring this, all responses
@@ -1193,7 +1178,7 @@ pub struct Config {
/// empty list (`[]`) to operate without trusted server assistance, but this
/// is discouraged for performance and reliability reasons.
///
/// default: ["matrix.org"]
/// default: ["continuwuity.org", "continuwuity.rocks", "matrix.org"]
#[serde(default = "default_trusted_servers")]
pub trusted_servers: Vec<TrustedServer>,
@@ -2822,10 +2807,12 @@ pub struct OidcConfig {
/// Additional scopes Continuwuity should request from the IDP. This may be
/// necessary to access certain claims. Continuwuity always requests the
/// `openid` scope.
/// `openid` scope, regardless of the contents of this option,
/// and will also request the `profile` scope by default if this option is
/// not set.
///
/// default: []
#[serde(default)]
/// default: ["profile"]
#[serde(default = "default_additional_scopes")]
pub additional_scopes: Vec<Scope>,
/// Additional trusted audiences that Continuwuity will accept in the `aud`
@@ -2993,11 +2980,17 @@ impl<'de, K: Hash + Eq + Clone> Deserialize<'de> for PerMinuteRatelimiter<K> {
}
const DEPRECATED_KEYS: &[&str] = &[
"allow_check_for_updates",
"allow_moderators_to_view_redacted_content",
"allow_sticky_events",
"cache_capacity",
"conduit_cache_capacity_modifier",
"max_concurrent_requests",
"otlp_protocol",
"request_ip_source",
"require_auth_for_profile_requests",
"roomid_spacehierarchy_cache_capacity",
"unredacted_content_max_age_secs",
"well_known_client",
"well_known_server",
"well_known_support_page",
@@ -3005,9 +2998,6 @@ const DEPRECATED_KEYS: &[&str] = &[
"well_known_support_email",
"well_known_support_mxid",
"well_known.rtc_focus_server_urls",
"allow_sticky_events",
"allow_moderators_to_view_redacted_content",
"unredacted_content_max_age_secs",
];
impl Config {
@@ -3138,41 +3128,41 @@ fn default_database_backups_to_keep() -> i16 { 1 }
fn default_db_write_buffer_capacity_mb() -> f64 { 48.0 + parallelism_scaled_f64(4.0) }
fn default_db_cache_capacity_mb() -> f64 { 128.0 + parallelism_scaled_f64(64.0) }
fn default_db_cache_capacity_mb() -> f64 { 512.0 + parallelism_scaled_f64(512.0) }
fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(10_000).saturating_add(100_000) }
fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(50_000).saturating_add(100_000) }
fn default_cache_capacity_modifier() -> f64 { 1.0 }
fn default_auth_chain_cache_capacity() -> u32 {
parallelism_scaled_u32(10_000).saturating_add(100_000)
}
fn default_shorteventid_cache_capacity() -> u32 {
parallelism_scaled_u32(50_000).saturating_add(100_000)
}
fn default_shorteventid_cache_capacity() -> u32 {
parallelism_scaled_u32(100_000).saturating_add(100_000)
}
fn default_eventidshort_cache_capacity() -> u32 {
parallelism_scaled_u32(25_000).saturating_add(100_000)
parallelism_scaled_u32(50_000).saturating_add(100_000)
}
fn default_eventid_pdu_cache_capacity() -> u32 {
parallelism_scaled_u32(25_000).saturating_add(100_000)
parallelism_scaled_u32(50_000).saturating_add(100_000)
}
fn default_shortstatekey_cache_capacity() -> u32 {
parallelism_scaled_u32(10_000).saturating_add(100_000)
parallelism_scaled_u32(100_000).saturating_add(100_000)
}
fn default_statekeyshort_cache_capacity() -> u32 {
parallelism_scaled_u32(10_000).saturating_add(100_000)
parallelism_scaled_u32(50_000).saturating_add(100_000)
}
fn default_servernameevent_data_cache_capacity() -> u32 {
parallelism_scaled_u32(100_000).saturating_add(500_000)
parallelism_scaled_u32(100_000).saturating_add(100_000)
}
fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(100) }
fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(500).clamp(100, 12000) }
fn default_dns_cache_entries() -> u32 { 32768 }
@@ -3259,12 +3249,11 @@ fn default_otlp_filter() -> String {
fn default_tracing_flame_output_path() -> String { "./tracing.folded".to_owned() }
fn default_trusted_servers() -> Vec<TrustedServer> {
// TODO(nex): Once we can be a notary, add maintainer(?) homeservers here.
// Rationale: Users are already running our code, arguably that's a higher
// level of trust than is assigned to notaries in the first place.
// We should still remind everyone that notaries are evil and out to get you
// and to replace this list with servers they actually trust.
let trusted_servers = vec![ruma::owned_server_name!("matrix.org")];
let trusted_servers = vec![
ruma::owned_server_name!("continuwuity.org"),
ruma::owned_server_name!("continuwuity.rocks"),
ruma::owned_server_name!("matrix.org"),
];
trusted_servers
.into_iter()
.map(TrustedServer::Name)
@@ -3395,15 +3384,20 @@ fn default_admin_log_capture() -> String {
fn default_admin_room_tag() -> String { "m.server_notice".to_owned() }
#[must_use]
#[allow(clippy::as_conversions, clippy::cast_precision_loss)]
fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
pub fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
fn parallelism_scaled_u32(val: u32) -> u32 {
let val = val.try_into().expect("failed to cast u32 to usize");
parallelism_scaled(val).try_into().unwrap_or(u32::MAX)
#[must_use]
#[allow(clippy::as_conversions, clippy::cast_possible_truncation)]
pub fn parallelism_scaled_u32(val: u32) -> u32 {
val.saturating_mul(sys::available_parallelism() as u32)
}
fn parallelism_scaled(val: usize) -> usize { val.saturating_mul(sys::available_parallelism()) }
#[must_use]
pub fn parallelism_scaled(val: usize) -> usize {
val.saturating_mul(sys::available_parallelism())
}
fn default_db_pool_workers() -> usize {
sys::available_parallelism()
@@ -3443,6 +3437,8 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
}
fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
// NOTE: This must be declared *after* every config struct in this file. The
// example config generator writes sections in macro expansion order, and the
// `global` section truncates the file, so declaring this module any earlier
+3 -1
View File
@@ -171,13 +171,14 @@ impl Error {
/// Returns the Matrix error code / error kind
#[inline]
pub fn kind(&self) -> ErrorKind {
use ruma::api::error::ErrorKind::{Unknown, Unrecognized};
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized};
match self {
| Self::Federation(_, error) | Self::Ruma(error) =>
response::ruma_error_kind(error).clone(),
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
| Self::FeatureDisabled(..) => Unrecognized,
| Self::Path(_) | Self::Query(_) => InvalidParam,
| _ => Unknown,
}
}
@@ -194,6 +195,7 @@ impl Error {
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
| Self::Conflict(_) => StatusCode::CONFLICT,
| Self::Path(_) | Self::Query(_) => StatusCode::BAD_REQUEST,
| Self::Io(error) => response::io_error_code(error.kind()),
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
| _ => StatusCode::INTERNAL_SERVER_ERROR,
+3
View File
@@ -73,6 +73,9 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
// 413
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
// 409
| ConcurrentWrite => StatusCode::CONFLICT,
// 404
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
+2
View File
@@ -18,6 +18,7 @@ pub fn versions() -> Vec<String> {
"v1.3".to_owned(),
"v1.4".to_owned(),
"v1.5".to_owned(),
"v1.6".to_owned(),
"v1.8".to_owned(),
"v1.11".to_owned(),
"v1.12".to_owned(),
@@ -37,6 +38,7 @@ pub fn unstable_features(experiments: &Experiments) -> BTreeMap<String, bool> {
// MatrixRTC (https://github.com/matrix-org/matrix-spec-proposals/pull/4143)
// Expected for spec v1.20/v2.0
("org.matrix.msc4143".to_owned(), true),
("org.matrix.msc4143.stable".to_owned(), true),
// Simplified Sliding sync (https://github.com/matrix-org/matrix-spec-proposals/pull/4186)
// Expected for spec v1.20/v2.0
("org.matrix.simplified_msc3575".to_owned(), true),
+26 -4
View File
@@ -21,6 +21,7 @@ pub struct Instruments {
pub sender_transaction_duration: Histogram<f64>,
pub sender_events: Counter<u64>,
pub sender_events_queued: Counter<u64>,
pub sender_panics: Counter<u64>,
pub media_write_size: Histogram<u64>,
pub media_read_size: Histogram<u64>,
@@ -45,6 +46,14 @@ impl Instruments {
.with_boundaries(duration_buckets())
.build()
};
let long_duration = |name: &'static str, description: &'static str| {
meter
.f64_histogram(name)
.with_description(description)
.with_unit("s")
.with_boundaries(long_duration_buckets())
.build()
};
let size = |name: &'static str, description: &'static str| {
meter
.u64_histogram(name)
@@ -55,11 +64,11 @@ impl Instruments {
};
Self {
federation_outgoing_request_duration: duration(
federation_outgoing_request_duration: long_duration(
"continuwuity.federation.outgoing.request.duration",
"Duration of outgoing federation requests",
),
federation_incoming_transaction_duration: duration(
federation_incoming_transaction_duration: long_duration(
"continuwuity.federation.incoming.transaction.duration",
"Time taken to process incoming federation transactions",
),
@@ -75,11 +84,13 @@ impl Instruments {
federation_incoming_pdu_lag: meter
.f64_histogram("continuwuity.federation.incoming.pdu.lag")
.with_description(
"Time between an accepted incoming PDU's origin_server_ts and its arrival",
"Time between an accepted incoming PDU's origin_server_ts and its \
transaction arriving",
)
.with_unit("s")
.with_boundaries(vec![
0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 300.0, 900.0, 3600.0,
21600.0, 86400.0,
])
.build(),
federation_incoming_edus: meter
@@ -92,7 +103,7 @@ impl Instruments {
"Time taken to handle an incoming federation EDU",
),
sender_transaction_duration: duration(
sender_transaction_duration: long_duration(
"continuwuity.sender.transaction.duration",
"Duration of outgoing transactions by destination type and outcome",
),
@@ -106,6 +117,11 @@ impl Instruments {
.with_description("PDUs and EDUs queued for sending")
.with_unit("{event}")
.build(),
sender_panics: meter
.u64_counter("continuwuity.sender.panics")
.with_description("Panics caught in outgoing transactions and sender workers")
.with_unit("{panic}")
.build(),
media_write_size: size(
"continuwuity.media.write.size",
@@ -130,6 +146,12 @@ impl Instruments {
#[must_use]
pub fn duration_buckets() -> Vec<f64> { (0..16).map(|i| 0.001 * f64::from(1_u32 << i)).collect() }
/// Federation requests and transactions can run past the 60s default
/// `federation_timeout`.
fn long_duration_buckets() -> Vec<f64> {
(0..18).map(|i| 0.001 * f64::from(1_u32 << i)).collect()
}
fn size_buckets() -> Vec<f64> { (0..11).map(|i| 1024.0 * f64::from(4_u32.pow(i))).collect() }
fn register_process(meter: &Meter) {
-13
View File
@@ -8,19 +8,6 @@ pub mod info;
pub mod log;
pub mod matrix;
pub mod metrics;
pub mod mods;
#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))]
pub mod mods {
#[macro_export]
macro_rules! mod_ctor {
() => {};
}
#[macro_export]
macro_rules! mod_dtor {
() => {};
}
}
pub mod server;
pub mod utils;
-28
View File
@@ -1,28 +0,0 @@
use std::sync::atomic::{AtomicI32, Ordering};
const ORDERING: Ordering = Ordering::Relaxed;
static STATIC_DTORS: AtomicI32 = AtomicI32::new(0);
/// Called by Module::unload() to indicate module is about to be unloaded and
/// static destruction is intended. This will allow verifying it actually took
/// place.
pub(crate) fn prepare() {
let count = STATIC_DTORS.fetch_sub(1, ORDERING);
debug_assert!(count <= 0, "STATIC_DTORS should not be greater than zero.");
}
/// Called by static destructor of a module. This call should only be found
/// inside a mod_fini! macro. Do not call from anywhere else.
#[inline(always)]
pub fn report() { let _count = STATIC_DTORS.fetch_add(1, ORDERING); }
/// Called by Module::unload() (see check()) with action in case a check()
/// failed. This can allow a stuck module to be noted while allowing for other
/// independent modules to be diagnosed.
pub(crate) fn check_and_reset() -> bool { STATIC_DTORS.swap(0, ORDERING) == 0 }
/// Called by Module::unload() after unload to verify static destruction took
/// place. A call to prepare() must be made prior to Module::unload() and making
/// this call.
#[allow(dead_code)]
pub(crate) fn check() -> bool { STATIC_DTORS.load(ORDERING) == 0 }
-44
View File
@@ -1,44 +0,0 @@
#[macro_export]
macro_rules! mod_ctor {
( $($body:block)? ) => {
$crate::mod_init! {{
$crate::debug_info!("Module loaded");
$($body)?
}}
}
}
#[macro_export]
macro_rules! mod_dtor {
( $($body:block)? ) => {
$crate::mod_fini! {{
$crate::debug_info!("Module unloading");
$($body)?
$crate::mods::canary::report();
}}
}
}
#[macro_export]
macro_rules! mod_init {
($body:block) => {
#[used]
#[cfg_attr(target_family = "unix", unsafe(link_section = ".init_array"))]
static MOD_INIT: unsafe extern "C" fn() = { _mod_init };
#[cfg_attr(target_family = "unix", unsafe(link_section = ".text.startup"))]
unsafe extern "C" fn _mod_init() -> () $body
};
}
#[macro_export]
macro_rules! mod_fini {
($body:block) => {
#[used]
#[cfg_attr(target_family = "unix", unsafe(link_section = ".fini_array"))]
static MOD_FINI: unsafe extern "C" fn() = { _mod_fini };
#[cfg_attr(target_family = "unix", unsafe(link_section = ".text.startup"))]
unsafe extern "C" fn _mod_fini() -> () $body
};
}
-11
View File
@@ -1,11 +0,0 @@
#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
pub(crate) use libloading::os::unix::{Library, Symbol};
pub mod canary;
pub mod macros;
pub mod module;
pub mod new;
pub mod path;
pub use module::Module;
-75
View File
@@ -1,75 +0,0 @@
use std::{
ffi::{CString, OsString},
time::SystemTime,
};
use super::{Library, Symbol, canary, new, path};
use crate::{Result, error};
pub struct Module {
handle: Option<Library>,
loaded: SystemTime,
path: OsString,
}
impl Module {
pub fn from_name(name: &str) -> Result<Self> { Self::from_path(path::from_name(name)?) }
pub fn from_path(path: OsString) -> Result<Self> {
Ok(Self {
handle: Some(new::from_path(&path)?),
loaded: SystemTime::now(),
path,
})
}
pub fn unload(&mut self) {
canary::prepare();
self.close();
if !canary::check_and_reset() {
let name = self.name().expect("Module is named");
error!("Module {name:?} is stuck and failed to unload.");
}
}
pub(crate) fn close(&mut self) {
if let Some(handle) = self.handle.take() {
handle.close().expect("Module handle closed");
}
}
pub fn get<Prototype>(&self, name: &str) -> Result<Symbol<Prototype>> {
let cname = CString::new(name.to_owned()).expect("terminated string from provided name");
let handle = self
.handle
.as_ref()
.expect("backing library loaded by this instance");
// SAFETY: Calls dlsym(3) on unix platforms. This might not have to be
// unsafe if wrapped in libloading with_dlerror().
let sym = unsafe { handle.get::<Prototype>(cname.as_bytes()) };
let sym = sym.expect("symbol found; binding successful");
Ok(sym)
}
pub fn deleted(&self) -> Result<bool> {
let mtime = path::mtime(self.path())?;
let res = mtime > self.loaded;
Ok(res)
}
pub fn name(&self) -> Result<String> { path::to_name(self.path()) }
#[must_use]
pub fn path(&self) -> &OsString { &self.path }
}
impl Drop for Module {
fn drop(&mut self) {
if self.handle.is_some() {
self.unload();
}
}
}
-23
View File
@@ -1,23 +0,0 @@
use std::ffi::OsStr;
use super::{Library, path};
use crate::{Err, Result};
const OPEN_FLAGS: i32 = libloading::os::unix::RTLD_LAZY | libloading::os::unix::RTLD_GLOBAL;
pub fn from_name(name: &str) -> Result<Library> {
let path = path::from_name(name)?;
from_path(&path)
}
pub fn from_path(path: &OsStr) -> Result<Library> {
//SAFETY: Calls dlopen(3) on unix platforms. This might not have to be
// unsafe if wrapped in with_dlerror.
let lib = unsafe { Library::open(Some(path), OPEN_FLAGS) };
if let Err(e) = lib {
let name = path::to_name(path)?;
return Err!("Loading module {name:?} failed: {e}");
}
Ok(lib.expect("module loaded"))
}
-41
View File
@@ -1,41 +0,0 @@
use std::{
env::current_exe,
ffi::{OsStr, OsString},
path::{Path, PathBuf},
time::SystemTime,
};
use libloading::library_filename;
use crate::Result;
pub fn from_name(name: &str) -> Result<OsString> {
let root = PathBuf::new();
let exe_path = current_exe()?;
let exe_dir = exe_path.parent().unwrap_or(&root);
let mut mod_path = exe_dir.to_path_buf();
let mod_file = library_filename(name);
mod_path.push(mod_file);
Ok(mod_path.into_os_string())
}
pub fn to_name(path: &OsStr) -> Result<String> {
let path = Path::new(path);
let name = path
.file_stem()
.expect("path file stem")
.to_str()
.expect("name string");
let name = name.strip_prefix("lib").unwrap_or(name).to_owned();
Ok(name)
}
pub fn mtime(path: &OsStr) -> Result<SystemTime> {
let meta = std::fs::metadata(path)?;
let mtime = meta.modified()?;
Ok(mtime)
}
-27
View File
@@ -27,10 +27,6 @@ pub struct Server {
/// observable used on shutdown and should not be modified.
pub stopping: AtomicBool,
/// Reload/shutdown desired indicator; when false, shutdown is desired. This
/// is an observable used on shutdown and modifying is not recommended.
pub reloading: AtomicBool,
/// Restart desired; when true, restart it desired after shutdown.
pub restarting: AtomicBool,
@@ -60,7 +56,6 @@ impl Server {
config: config::Manager::new(config),
started: SystemTime::now(),
stopping: AtomicBool::new(false),
reloading: AtomicBool::new(false),
restarting: AtomicBool::new(false),
runtime,
signal: broadcast::channel::<&'static str>(1).0,
@@ -69,25 +64,6 @@ impl Server {
}
}
pub fn reload(&self) -> Result<()> {
if cfg!(any(not(conduwuit_mods), not(feature = "conduwuit_mods"))) {
return Err!("Reloading not enabled");
}
if self.reloading.swap(true, Ordering::AcqRel) {
return Err!("Reloading already in progress");
}
if self.stopping.swap(true, Ordering::AcqRel) {
return Err!("Shutdown already in progress");
}
self.signal("SIGINT").inspect_err(|_| {
self.stopping.store(false, Ordering::Release);
self.reloading.store(false, Ordering::Release);
})
}
pub fn restart(&self) -> Result {
if self.restarting.swap(true, Ordering::AcqRel) {
return Err!("Restart already in progress");
@@ -146,9 +122,6 @@ impl Server {
#[inline]
pub fn is_stopping(&self) -> bool { self.stopping.load(Ordering::Relaxed) }
#[inline]
pub fn is_reloading(&self) -> bool { self.reloading.load(Ordering::Relaxed) }
#[inline]
pub fn is_restarting(&self) -> bool { self.restarting.load(Ordering::Relaxed) }
+79 -15
View File
@@ -1,10 +1,8 @@
//! Extended external extensions to futures::FutureExt
use std::marker::Unpin;
use futures::{
Future, FutureExt,
future::{select_ok, try_join, try_join_all, try_select},
future::{try_join, try_join_all},
};
pub trait BoolExt
@@ -18,8 +16,8 @@ where
fn or<B>(self, b: B) -> impl Future<Output = bool> + Send
where
B: Future<Output = bool> + Send + Unpin,
Self: Sized + Unpin;
B: Future<Output = bool> + Send,
Self: Sized;
}
impl<Fut> BoolExt for Fut
@@ -44,20 +42,20 @@ where
#[inline]
fn or<B>(self, b: B) -> impl Future<Output = bool> + Send
where
B: Future<Output = bool> + Send + Unpin,
Self: Sized + Unpin,
B: Future<Output = bool> + Send,
Self: Sized,
{
type Result = crate::Result<(), ()>;
let a = self.map(|a| a.then_some(()).ok_or(Result::Err(())));
let a = self.map(|a| (!a).then_some(()).ok_or(Result::Err(())));
let b = b.map(|b| b.then_some(()).ok_or(Result::Err(())));
let b = b.map(|b| (!b).then_some(()).ok_or(Result::Err(())));
try_select(a, b).map(|result| result.is_ok())
try_join(a, b).map(|result| result.is_err())
}
}
pub async fn and<I, F>(args: I) -> impl Future<Output = bool> + Send
pub fn and<I, F>(args: I) -> impl Future<Output = bool> + Send
where
I: Iterator<Item = F> + Send,
F: Future<Output = bool> + Send,
@@ -69,14 +67,80 @@ where
try_join_all(args).map(|result| result.is_ok())
}
pub async fn or<I, F>(args: I) -> impl Future<Output = bool> + Send
pub fn or<I, F>(args: I) -> impl Future<Output = bool> + Send
where
I: Iterator<Item = F> + Send,
F: Future<Output = bool> + Send + Unpin,
F: Future<Output = bool> + Send,
{
type Result = crate::Result<(), ()>;
let args = args.map(|a| a.map(|a| a.then_some(()).ok_or(Result::Err(()))));
let args = args.map(|a| a.map(|a| (!a).then_some(()).ok_or(Result::Err(()))));
select_ok(args).map(|result| result.is_ok())
try_join_all(args).map(|result| result.is_err())
}
#[cfg(test)]
mod tests {
use std::pin::pin;
use futures::future;
use super::{BoolExt, and, or};
#[tokio::test]
async fn bool_ext_truth_tables() {
for a in [false, true] {
for b in [false, true] {
assert_eq!(future::ready(a).and(future::ready(b)).await, a && b, "and({a}, {b})");
assert_eq!(future::ready(a).or(future::ready(b)).await, a || b, "or({a}, {b})");
}
}
assert!(
future::ready(false)
.or(future::ready(false))
.or(future::ready(true))
.await,
"chained or with trailing true must return true"
);
assert!(
!future::ready(false)
.or(future::ready(false))
.or(future::ready(false))
.await,
"chained or with all false must return false"
);
}
#[tokio::test]
async fn bool_ext_short_circuits() {
let pend = pin!(future::pending::<bool>());
assert!(
future::ready(true).or(pend).await,
"or must short-circuit on true without polling pending"
);
let pend = pin!(future::pending::<bool>());
assert!(
!future::ready(false).and(pend).await,
"and must short-circuit on false without polling pending"
);
}
#[tokio::test]
async fn free_and_or() {
assert!(and(std::iter::empty::<future::Ready<bool>>()).await, "empty and is true");
assert!(!or(std::iter::empty::<future::Ready<bool>>()).await, "empty or is false");
assert!(and([future::ready(true), future::ready(true)].into_iter()).await, "all true");
assert!(
!and([future::ready(true), future::ready(false)].into_iter()).await,
"and with false"
);
assert!(
or([future::ready(false), future::ready(true)].into_iter()).await,
"or with true"
);
assert!(!or([future::ready(false), future::ready(false)].into_iter()).await, "all false");
}
}
+3
View File
@@ -5,6 +5,7 @@ pub type DigestOut = [u8; 256 / 8];
/// Sha256 hash (input gather joined by 0xFF bytes)
#[must_use]
#[tracing::instrument(skip(inputs), level = "trace")]
#[allow(clippy::unnecessary_fallible_conversions)]
pub fn delimited<'a, T, I>(mut inputs: I) -> DigestOut
where
I: Iterator<Item = T> + 'a,
@@ -25,6 +26,7 @@ where
/// Sha256 hash (input gather)
#[must_use]
#[tracing::instrument(skip(inputs), level = "trace")]
#[allow(clippy::unnecessary_fallible_conversions)]
pub fn concat<'a, T, I>(inputs: I) -> DigestOut
where
I: Iterator<Item = T> + 'a,
@@ -43,6 +45,7 @@ where
#[inline]
#[must_use]
#[tracing::instrument(skip(input), level = "trace")]
#[allow(clippy::unnecessary_fallible_conversions)]
pub fn hash<T>(input: T) -> DigestOut
where
T: AsRef<[u8]>,
+47 -3
View File
@@ -62,14 +62,28 @@ macro_rules! validated {
}
#[inline]
#[allow(clippy::as_conversions)]
#[allow(clippy::as_conversions, clippy::cast_possible_truncation, clippy::cast_sign_loss)]
pub fn usize_from_f64(val: f64) -> Result<usize, Error> {
// Exclusive upper bound for values whose truncation fits in `usize`.
// Note that `usize::MAX as f64` rounds up to 2^64 on 64-bit targets, so a
// strict `<` check against 2^(usize::BITS) rejects all out-of-range values
// on both 32-bit and 64-bit targets.
#[allow(clippy::cast_precision_loss)]
const MAX_USIZE_EXCLUSIVE: f64 = (1_u128 << usize::BITS) as f64;
if !val.is_finite() {
return Err!(Arithmetic("Converting non-finite float to unsigned integer"));
}
if val < 0.0 {
return Err!(Arithmetic("Converting negative float to unsigned integer"));
}
//SAFETY: <https://doc.rust-lang.org/std/primitive.f64.html#method.to_int_unchecked>
Ok(unsafe { val.to_int_unchecked::<usize>() })
if val >= MAX_USIZE_EXCLUSIVE {
return Err!(Arithmetic("Converting out-of-range float to unsigned integer"));
}
Ok(val as usize)
}
#[inline]
@@ -111,3 +125,33 @@ fn try_into_err<Dst: TryFrom<Src>, Src>(e: <Dst as TryFrom<Src>>::Error) -> Erro
#[inline]
pub fn clamp<T: Ord>(val: T, min: T, max: T) -> T { cmp::min(cmp::max(val, min), max) }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn usize_from_f64_valid() {
assert_eq!(usize_from_f64(0.0).unwrap(), 0);
assert_eq!(usize_from_f64(-0.0).unwrap(), 0);
assert_eq!(usize_from_f64(42.9).unwrap(), 42);
assert_eq!(usize_from_f64(1_048_576.0).unwrap(), 1_048_576);
}
#[test]
fn usize_from_f64_rejects_invalid() {
usize_from_f64(-1.0).unwrap_err();
usize_from_f64(-0.5).unwrap_err();
usize_from_f64(f64::NAN).unwrap_err();
usize_from_f64(f64::INFINITY).unwrap_err();
usize_from_f64(f64::NEG_INFINITY).unwrap_err();
usize_from_f64(1e30).unwrap_err();
#[cfg(target_pointer_width = "64")]
{
// `usize::MAX as f64` rounds up to 2^64, which is out of range.
#[allow(clippy::as_conversions, clippy::cast_precision_loss)]
let rounded_max = usize::MAX as f64;
usize_from_f64(rounded_max).unwrap_err();
}
}
}
+3 -5
View File
@@ -1,7 +1,6 @@
use std::convert::Infallible;
use super::{DebugInspect, Result};
use crate::error;
use super::Result;
pub trait UnwrapInfallible<T> {
fn unwrap_infallible(self) -> T;
@@ -10,8 +9,7 @@ pub trait UnwrapInfallible<T> {
impl<T> UnwrapInfallible<T> for Result<T, Infallible> {
#[inline]
fn unwrap_infallible(self) -> T {
// SAFETY: Branchless unwrap for errors that can never happen. In debug
// mode this is asserted.
unsafe { self.debug_inspect_err(error::infallible).unwrap_unchecked() }
let Ok(val) = self;
val
}
}
+5 -4
View File
@@ -32,11 +32,12 @@ impl<'a> From<&'a str> for &'a Unquoted {
fn from(s: &'a str) -> &'a Unquoted {
let s: &'a str = s.unquote_infallible();
//SAFETY: This is a pattern I lifted from ruma-identifiers for
// strong-type strs by wrapping in a tuple-struct.
#[allow(clippy::transmute_ptr_to_ptr)]
// SAFETY: `Unquoted` is `#[repr(transparent)]` over `str`, so
// `*const str` and `*const Unquoted` have identical layout and
// metadata, and the returned reference preserves lifetime `'a`.
#[allow(clippy::as_conversions)]
unsafe {
std::mem::transmute(s)
&*(std::ptr::from_ref::<str>(s) as *const Unquoted)
}
}
}
+5 -13
View File
@@ -120,21 +120,13 @@ pub fn cores_available() -> impl Iterator<Item = Id> { from_mask(*CORES_AVAILABL
pub fn getcpu() -> Result<usize> {
use crate::{Error, utils::math};
// SAFETY: This is part of an interface with many low-level calls taking
// many raw params, but it's unclear why this specific call is unsafe.
// Nevertheless the value obtained here is semantically unsafe because it
// can change on the instruction boundary trailing its own acquisition and
// also any other time.
// SAFETY: `sched_getcpu(2)` takes no pointers and has no preconditions.
// Note that it may still return -1 with errno set (e.g. under seccomp
// filters or kernels without getcpu support), so the error branch below
// must remain live.
let ret: i32 = unsafe { libc::sched_getcpu() };
#[cfg(target_os = "linux")]
// SAFETY: On modern linux systems with a vdso if we can optimize away the branch checking
// for error (see getcpu(2)) then this system call becomes a memory access.
unsafe {
std::hint::assert_unchecked(ret >= 0);
};
if ret == -1 {
if ret < 0 {
return Err(Error::from_errno());
}
-12
View File
@@ -472,17 +472,5 @@ impl<'a, 'de: 'a> de::MapAccess<'de> for &'a mut Deserializer<'de> {
}
}
// activate when stable; too soon now
//#[cfg(debug_assertions)]
#[inline]
fn deserialize_str(input: &[u8]) -> Result<&str> { string::str_from_bytes(input) }
//#[cfg(not(debug_assertions))]
#[cfg(disable)]
#[inline]
fn deserialize_str(input: &[u8]) -> Result<&str> {
// SAFETY: Strings were written by the serializer to the database. Assuming
// no database corruption, the string will be valid. Database corruption is
// detected via rocksdb checksums.
unsafe { std::str::from_utf8_unchecked(input) }
}
+1 -1
View File
@@ -29,7 +29,7 @@ fn descriptor_cf_options(
let mut opts = set_table_options(opts, &desc, cache)?;
opts.set_min_write_buffer_number(1);
opts.set_max_write_buffer_number(2);
opts.set_max_write_buffer_number(3);
opts.set_write_buffer_size(desc.write_size);
opts.set_target_file_size_base(desc.file_size);
+4
View File
@@ -46,6 +46,10 @@ use crate::{Engine, watchers::Watchers};
pub struct Map {
name: &'static str,
watchers: Watchers,
/// SAFETY / DROP ORDER: `cf` holds a lifetime-erased RocksDB column family
/// handle (see `open::open`) and MUST be declared before `db` so that the
/// handle is destroyed before `Engine` (and the underlying RocksDB `DB`)
/// can be dropped.
cf: Arc<ColumnFamily>,
db: Arc<Engine>,
read_options: ReadOptions,
+15 -1
View File
@@ -1,10 +1,24 @@
use std::sync::Arc;
use rocksdb::ColumnFamily;
use rocksdb::{BoundColumnFamily, ColumnFamily};
use crate::Engine;
pub(super) fn open(db: &Arc<Engine>, name: &str) -> Arc<ColumnFamily> {
// Compile-time guard: `BoundColumnFamily` and `ColumnFamily` are both
// `#[repr(Rust)]` in `rust-rocksdb`, so fail compilation if their size or
// alignment ever diverge.
const {
assert!(
size_of::<BoundColumnFamily<'_>>() == size_of::<ColumnFamily>(),
"BoundColumnFamily and ColumnFamily must have identical size"
);
assert!(
align_of::<BoundColumnFamily<'_>>() == align_of::<ColumnFamily>(),
"BoundColumnFamily and ColumnFamily must have identical alignment"
);
}
let bounded_arc = db.cf(name);
let bounded_ptr = Arc::into_raw(bounded_arc);
let cf_ptr = bounded_ptr.cast::<ColumnFamily>();
+11
View File
@@ -12,6 +12,17 @@ impl super::Map {
/// Iterate key-value entries in the map from the beginning.
///
/// - Result is deserialized
///
/// # Unsoundness
/// Because Rust's `Stream` trait does not support lending items tied to
/// `&mut self`, `stream::slice_longevity` unsafely extends the lifetime of
/// raw RocksDB iterator slices to `'a` (the borrow of `Arc<Map>`). As a
/// consequence, borrowed deserialized types (e.g. `&str`, `&UserId`,
/// `&[u8]`) reference the underlying RocksDB cursor buffer and are
/// invalidated on the next poll of the stream. Do not hold borrowed items
/// across polls (e.g. via `collect()`, `ready_chunks()`, `peekable()`,
/// `buffered()`, `buffer_unordered()`, `broadband`, or `wideband`) without
/// converting them to owned values first.
pub fn stream<'a, K, V>(
self: &'a Arc<Self>,
) -> impl Stream<Item = Result<KeyVal<'a, K, V>>> + Send
+4
View File
@@ -232,6 +232,10 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "roomsynctoken_shortstatehash",
..descriptor::DROPPED
},
Descriptor {
name: "roomts_pduid",
..descriptor::SEQUENTIAL_SMALL
},
Descriptor {
name: "roomuserdataid_accountdata",
..descriptor::RANDOM_SMALL
-3
View File
@@ -5,9 +5,6 @@ extern crate rust_rocksdb as rocksdb;
conduwuit_macros::introspect_crate! {}
conduwuit::mod_ctor! {}
conduwuit::mod_dtor! {}
#[cfg(test)]
mod benches;
mod cork;
+23 -11
View File
@@ -54,8 +54,14 @@ pub(crate) struct Get {
/// Note: only initial seek is supported at this time on the assumption rocksdb
/// prefetching prevents mid-iteration polls from blocking on I/O.
pub(crate) struct Seek {
pub(crate) map: Arc<Map>,
/// SAFETY / DROP ORDER: `state` wraps a RocksDB
/// `DBRawIteratorWithThreadMode` referencing `map.db.db` whose lifetime has
/// been erased to `'static`. `state` MUST be declared before `map` so the
/// iterator is destroyed before `map` (and potentially the last
/// `Arc<Engine>`) can be dropped if `Seek` is dropped early (e.g. on
/// cancellation or queue closure).
pub(crate) state: stream::State<'static>,
pub(crate) map: Arc<Map>,
pub(crate) dir: Direction,
pub(crate) key: Option<KeyBuf>,
pub(crate) res: Option<ResultSender<stream::State<'static>>>,
@@ -416,24 +422,30 @@ impl Drop for Pool {
}
fn into_send_get(result: BatchResult<'_>) -> BatchResult<'static> {
// SAFETY: Necessary to send the Handle (rust_rocksdb::PinnableSlice)
// through the channel. The lifetime on the handle is a device by
// rust-rocksdb to associate a database lifetime with its assets. The
// Handle must be dropped before the database is dropped.
// SAFETY: Necessary to send `Handle` (which wraps
// `rocksdb::DBPinnableSlice`) through the oneshot channel. The lifetime on
// `Handle` ties it to the RocksDB `DB` instance; callers of `execute_get`
// borrow `&self.db.pool` (which is owned by `Engine`), ensuring the
// received `BatchResult<'_>` cannot outlive the database.
unsafe { std::mem::transmute(result) }
}
fn into_recv_get<'a>(result: BatchResult<'static>) -> BatchResult<'a> {
// SAFETY: This is to receive the Handle from the channel.
// SAFETY: Shrinking the erased `'static` lifetime back to `'a` (borrowed
// from `&self.db.pool`). `SmallVec<A>` is invariant over `A`, so this
// cannot be done via implicit covariance.
unsafe { std::mem::transmute(result) }
}
pub(crate) fn into_send_seek(result: stream::State<'_>) -> stream::State<'static> {
// SAFETY: Necessary to send the State through the channel; see above.
// SAFETY: Necessary to send `stream::State` through the pool channel.
// While in flight on the queue, `Seek` owns an `Arc<Map>` (declared after
// `state` so `state` drops first on early cancellation); once received back
// from `execute_iter`, the lifetime is shrunk via `into_recv_seek` to the
// caller's borrow of `&self.db.pool` (and `&'a Arc<Map>`), ensuring the
// returned `stream::State<'_>` cannot outlive the database.
unsafe { std::mem::transmute(result) }
}
fn into_recv_seek(result: stream::State<'static>) -> stream::State<'static> {
// SAFETY: This is to receive the State from the channel; see above.
unsafe { std::mem::transmute(result) }
}
#[inline]
const fn into_recv_seek<'a>(result: stream::State<'static>) -> stream::State<'a> { result }
+14 -16
View File
@@ -133,22 +133,20 @@ fn keyval_longevity<'a, 'b: 'a>(item: KeyVal<'a>) -> KeyVal<'b> {
}
fn slice_longevity<'a, 'b: 'a>(item: &'a Slice) -> &'b Slice {
// SAFETY: The lifetime of the data returned by the rocksdb cursor is only
// valid between each movement of the cursor. It is hereby unsafely
// extended to match the lifetime of the cursor itself. This is due to the
// limitation of the Stream trait where the Item is incapable of conveying
// a lifetime; this is due to GAT's being unstable during its development.
// This unsafety can be removed as soon as this limitation is addressed by
// an upcoming version.
// SAFETY: the lifetime of the data returned by
// the RocksDB cursor is only valid until the next movement of the cursor,
// but is unsafely extended here to match the lifetime `'b` of the `Map`
// borrow because `futures::Stream` is not a lending stream.
//
// We have done our best to mitigate the implications of this in conjunction
// with the deserialization API such that borrows being held across
// movements of the cursor do not happen accidentally. The compiler will
// still error when values herein produced try to leave a closure passed to
// a StreamExt API. But escapes can happen if you explicitly and
// intentionally attempt it, and there will be no compiler error or
// warning. This is primarily the case with calling collect() without a
// preceding map(ToOwned::to_owned). A collection of references here is
// illegal, but this will not be enforced by the compiler.
// Callers MUST NOT hold borrowed items (or borrowed deserialized views such
// as `&str`, `&UserId`, or `&[u8]`) across subsequent polls of the stream —
// in particular, never call `collect()`, `ready_chunks()`, `peekable()`,
// `buffered()`, `buffer_unordered()`, `broadband`, or `wideband` on a
// stream yielding borrowed references without first converting items to
// owned values (e.g. `map(ToOwned::to_owned)`). The compiler does NOT
// reject such escapes when items borrow from `'b`.
//
// TODO: Fix this, it is old code and language changes may have made it
// unnecessary
unsafe { std::mem::transmute(item) }
}
-16
View File
@@ -1,28 +1,12 @@
use conduwuit::Result;
use rocksdb::{Direction, ErrorKind, IteratorMode};
//#[cfg(debug_assertions)]
macro_rules! unhandled {
($msg:literal) => {
unimplemented!($msg)
};
}
// activate when stable; we're not ready for this yet
#[cfg(disable)] // #[cfg(not(debug_assertions))]
macro_rules! unhandled {
($msg:literal) => {
// SAFETY: Eliminates branches for serializing and deserializing types never
// encountered in the codebase. This can promote optimization and reduce
// codegen. The developer must verify for every invoking callsite that the
// unhandled type is in no way involved and could not possibly be
// encountered.
unsafe {
std::hint::unreachable_unchecked();
}
};
}
pub(crate) use unhandled;
#[inline]
+29 -12
View File
@@ -48,6 +48,7 @@ assets = [
[features]
default = [
"standard",
"jemalloc",
"ring",
"bindgen-runtime", # replace with bindgen-static on alpine
]
@@ -57,7 +58,6 @@ standard = [
"element_hacks",
"gzip_compression",
"io_uring",
"jemalloc",
"jemalloc_conf",
"journald",
"media_thumbnail",
@@ -76,6 +76,7 @@ full = [
]
brotli_compression = [
"conduwuit-api/brotli_compression",
"conduwuit-core/brotli_compression",
"conduwuit-router/brotli_compression",
"conduwuit-service/brotli_compression",
@@ -87,30 +88,31 @@ direct_tls = [
"conduwuit-router/direct_tls"
]
element_hacks = [
"conduwuit-api/element_hacks",
"conduwuit-service/element_hacks",
"conduwuit-router/element_hacks",
]
gzip_compression = [
"conduwuit-api/gzip_compression",
"conduwuit-core/gzip_compression",
"conduwuit-router/gzip_compression",
"conduwuit-service/gzip_compression",
]
http3 = [
"conduwuit-service/http3"
"reqwest/http3"
]
ring = [
"rustls/ring",
"rustls/ring"
]
aws_lc_rs = [
"rustls/aws_lc_rs",
"dep:aws-lc-rs"
]
io_uring = [
"conduwuit-service/io_uring",
"conduwuit-database/io_uring",
]
jemalloc = [
"conduwuit-core/jemalloc",
"conduwuit-service/jemalloc",
"conduwuit-database/jemalloc",
]
mimalloc = [
"conduwuit-core/mimalloc",
@@ -142,13 +144,19 @@ perf_measurements = [
release_max_log_level = [
"tracing/max_level_trace",
"tracing/release_max_level_info",
"log/max_level_trace",
"log/release_max_level_info",
"conduwuit-admin/release_max_log_level",
"conduwuit-api/release_max_log_level",
"conduwuit-core/release_max_log_level",
"conduwuit-database/release_max_log_level",
"conduwuit-router/release_max_log_level",
"conduwuit-service/release_max_log_level",
]
sentry_telemetry = [
"dep:sentry",
"dep:sentry-tracing",
"dep:sentry-tower",
"conduwuit-core/sentry_telemetry",
"conduwuit-router/sentry_telemetry",
]
@@ -171,20 +179,19 @@ url_preview = [
"conduwuit-service/url_preview",
]
zstd_compression = [
"conduwuit-api/zstd_compression",
"conduwuit-core/zstd_compression",
"conduwuit-database/zstd_compression",
"conduwuit-router/zstd_compression",
"conduwuit-service/zstd_compression",
]
conduwuit_mods = [
"conduwuit-core/conduwuit_mods",
]
bindgen-static = [
# "bindgen/static"
# "clang-sys/static"
"conduwuit-service/bindgen-static"
"conduwuit-database/bindgen-static"
]
bindgen-runtime = [
"conduwuit-service/bindgen-runtime"
"conduwuit-database/bindgen-runtime"
]
[build-dependencies]
@@ -192,7 +199,10 @@ bindgen-runtime = [
# clang-sys = {version = "1", default-features = false}
[dependencies]
conduwuit-admin.workspace = true
conduwuit-api.workspace = true
conduwuit-core.workspace = true
conduwuit-database.workspace = true
conduwuit-router.workspace = true
conduwuit-service.workspace = true
conduwuit-build-metadata.workspace = true
@@ -204,6 +214,7 @@ dtor.workspace = true
console-subscriber.optional = true
console-subscriber.workspace = true
const-str.workspace = true
log.workspace = true
opentelemetry.workspace = true
opentelemetry-otlp.optional = true
opentelemetry-otlp.workspace = true
@@ -211,10 +222,14 @@ opentelemetry-prometheus.workspace = true
opentelemetry-semantic-conventions.workspace = true
opentelemetry_sdk.workspace = true
prometheus.workspace = true
sentry-tower.optional = true
sentry-tower.workspace = true
sentry-tracing.optional = true
sentry-tracing.workspace = true
sentry.optional = true
sentry.workspace = true
tokio-metrics.optional = true
tokio-metrics.workspace = true
tokio.workspace = true
tracing-flame.optional = true
tracing-flame.workspace = true
@@ -224,7 +239,9 @@ tracing-subscriber.workspace = true
tracing.workspace = true
tracing-journald = { workspace = true, optional = true }
parking_lot.workspace = true
reqwest = { workspace = true, default-features = false }
rustls = { workspace = true, default-features = false }
aws-lc-rs = { version = "1.19.0", default-features = false, optional = true }
[lints]
workspace = true
+8 -11
View File
@@ -26,18 +26,15 @@ pub(crate) fn init(
let mut builder = SdkMeterProvider::builder()
.with_resource(resource)
.with_view(|instrument: &Instrument| {
(instrument.name() == metric::HTTP_SERVER_REQUEST_DURATION)
.then(|| {
Stream::builder()
.with_aggregation(Aggregation::ExplicitBucketHistogram {
boundaries: duration_buckets(),
record_min_max: true,
})
.build()
.ok()
.with_view(|instrument: &Instrument| match instrument.name() {
| metric::HTTP_SERVER_REQUEST_DURATION => Stream::builder()
.with_aggregation(Aggregation::ExplicitBucketHistogram {
boundaries: duration_buckets(),
record_min_max: true,
})
.flatten()
.build()
.ok(),
| _ => None,
});
let registry = config
+7 -38
View File
@@ -10,7 +10,6 @@ mod clap;
mod deadlock;
mod logging;
mod metrics;
mod mods;
mod panic;
mod restart;
mod runtime;
@@ -33,6 +32,11 @@ pub fn run() -> Result<()> {
pub fn run_with_args(args: &Args) -> Result<()> {
// Spawn deadlock detection thread
deadlock::spawn();
#[cfg(not(any(feature = "jemalloc", feature = "mimalloc")))]
conduwuit_core::warn!(
"Your build configuration does not have a non-system allocator enabled. This may result \
in decreased performance."
);
// Because we're not using rustls default-tls, we have to initialise a TLS
// provider
@@ -63,9 +67,8 @@ pub fn run_with_args(args: &Args) -> Result<()> {
Ok(())
}
/// Operate the server normally in release-mode static builds. This will start,
/// run and stop the server within the asynchronous runtime.
#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))]
/// Operate the server. This will start, run and stop the server within the
/// asynchronous runtime.
#[tracing::instrument(
name = "main",
parent = None,
@@ -114,37 +117,3 @@ async fn async_main(server: &Arc<Server>) -> Result<(), Error> {
debug_info!("Exit runtime");
Ok(())
}
/// Operate the server in developer-mode dynamic builds. This will start, run,
/// and hot-reload portions of the server as-needed before returning for an
/// actual shutdown. This is not available in release-mode or static builds.
#[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
async fn async_main(server: &Arc<Server>) -> Result<(), Error> {
let mut starts = true;
let mut reloads = true;
while reloads {
if let Err(error) = mods::open(server).await {
error!("Loading router: {error}");
return Err(error);
}
let result = mods::run(server, starts).await;
if let Ok(result) = result {
(starts, reloads) = result;
}
let force = !reloads || result.is_err();
if let Err(error) = mods::close(server, force).await {
error!("Unloading router: {error}");
return Err(error);
}
if let Err(error) = result {
error!("{error}");
return Err(error);
}
}
debug_info!("Exit runtime");
Ok(())
}
-163
View File
@@ -1,163 +0,0 @@
#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
#[unsafe(no_link)]
extern crate conduwuit_service;
use std::{
future::Future,
pin::Pin,
sync::{Arc, atomic::Ordering},
};
use conduwuit_core::{Error, Result, debug, error, mods};
use conduwuit_service::Services;
use crate::Server;
type StartFuncResult = Pin<Box<dyn Future<Output = Result<Arc<Services>>> + Send>>;
type StartFuncProto = fn(&Arc<conduwuit_core::Server>) -> StartFuncResult;
type RunFuncResult = Pin<Box<dyn Future<Output = Result<()>> + Send>>;
type RunFuncProto = fn(&Arc<Services>) -> RunFuncResult;
type StopFuncResult = Pin<Box<dyn Future<Output = Result<()>> + Send>>;
type StopFuncProto = fn(Arc<Services>) -> StopFuncResult;
const RESTART_THRESH: &str = "conduwuit_service";
const MODULE_NAMES: &[&str] = &[
//"conduwuit_core",
"conduwuit_database",
"conduwuit_service",
"conduwuit_api",
"conduwuit_admin",
"conduwuit_router",
];
#[cfg(panic_trap)]
conduwuit_core::mod_init! {{
conduwuit_core::debug::set_panic_trap();
}}
pub(crate) async fn run(server: &Arc<Server>, starts: bool) -> Result<(bool, bool), Error> {
let main_lock = server.mods.read().await;
let main_mod = (*main_lock).last().expect("main module loaded");
if starts {
let start = main_mod.get::<StartFuncProto>("start")?;
match start(&server.server).await {
| Ok(services) => server.services.lock().await.insert(services),
| Err(error) => {
error!("Starting server: {error}");
return Err(error);
},
};
}
server.server.stopping.store(false, Ordering::Release);
let run = main_mod.get::<RunFuncProto>("run")?;
if let Err(error) = run(server
.services
.lock()
.await
.as_ref()
.expect("services initialized"))
.await
{
error!("Running server: {error}");
return Err(error);
}
let reloads = server.server.reloading.swap(false, Ordering::AcqRel);
let stops = !reloads || stale_from_mods(&main_lock)? <= restart_thresh();
let starts = reloads && stops;
if stops {
let stop = main_mod.get::<StopFuncProto>("stop")?;
if let Err(error) = stop(
server
.services
.lock()
.await
.take()
.expect("services initialized"),
)
.await
{
error!("Stopping server: {error}");
return Err(error);
}
}
Ok((starts, reloads))
}
pub(crate) async fn open(server: &Arc<Server>) -> Result<usize, Error> {
let mut mods_lock = server.mods.write().await;
let mods: &mut Vec<mods::Module> = &mut mods_lock;
debug!(
available = %available(),
loaded = %mods.len(),
"Loading modules",
);
for (i, name) in MODULE_NAMES.iter().enumerate() {
if mods.get(i).is_none() {
mods.push(mods::Module::from_name(name)?);
}
}
Ok(mods.len())
}
pub(crate) async fn close(server: &Arc<Server>, force: bool) -> Result<usize, Error> {
let stale = stale_count(server).await;
let mut mods_lock = server.mods.write().await;
let mods: &mut Vec<mods::Module> = &mut mods_lock;
debug!(
available = %available(),
loaded = %mods.len(),
stale = %stale,
force,
"Unloading modules",
);
while mods.last().is_some() {
let module = &mods.last().expect("module");
if force || module.deleted()? {
mods.pop();
} else {
break;
}
}
Ok(mods.len())
}
async fn stale_count(server: &Arc<Server>) -> usize {
let watermark = stale(server).await.unwrap_or(available());
available().saturating_sub(watermark)
}
async fn stale(server: &Arc<Server>) -> Result<usize, Error> {
let mods_lock = server.mods.read().await;
stale_from_mods(&mods_lock)
}
fn stale_from_mods(mods: &[mods::Module]) -> Result<usize, Error> {
for (i, module) in mods.iter().enumerate() {
if module.deleted()? {
return Ok(i);
}
}
Ok(mods.len())
}
fn restart_thresh() -> usize {
MODULE_NAMES
.iter()
.position(|&name| name.ends_with(RESTART_THRESH))
.unwrap_or(MODULE_NAMES.len())
}
const fn available() -> usize { MODULE_NAMES.len() }
-7
View File
@@ -27,10 +27,6 @@ pub(crate) struct Server {
#[cfg(feature = "sentry_telemetry")]
_sentry_guard: Option<::sentry::ClientInitGuard>,
#[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
// Module instances; TODO: move to mods::loaded mgmt vector
pub(crate) mods: tokio::sync::RwLock<Vec<conduwuit_core::mods::Module>>,
}
impl Server {
@@ -87,9 +83,6 @@ impl Server {
#[cfg(feature = "sentry_telemetry")]
_sentry_guard: sentry_guard,
#[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))]
mods: tokio::sync::RwLock::new(Vec::new()),
}))
}
+1 -4
View File
@@ -12,7 +12,6 @@ pub(super) async fn signal(server: Arc<Server>) {
use unix::SignalKind;
const CONSOLE: bool = cfg!(feature = "console");
const RELOADING: bool = cfg!(all(conduwuit_mods, feature = "conduwuit_mods", not(CONSOLE)));
let mut quit = unix::signal(SignalKind::quit()).expect("SIGQUIT handler");
let mut term = unix::signal(SignalKind::terminate()).expect("SIGTERM handler");
@@ -30,9 +29,7 @@ pub(super) async fn signal(server: Arc<Server>) {
}
warn!("Received {sig}");
let result = if RELOADING && sig == "SIGINT" {
server.server.reload()
} else if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") {
let result = if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") {
server.server.shutdown()
} else {
server.server.signal(sig)
+3 -13
View File
@@ -16,11 +16,7 @@ use conduwuit::{Error, Result, Server};
use conduwuit_service::Services;
use futures::{Future, FutureExt, TryFutureExt};
conduwuit::mod_ctor! {}
conduwuit::mod_dtor! {}
#[unsafe(no_mangle)]
pub extern "Rust" fn start(
pub fn start(
server: &Arc<Server>,
) -> Pin<Box<dyn Future<Output = Result<Arc<Services>>> + Send>> {
AssertUnwindSafe(run::start(server.clone()))
@@ -30,10 +26,7 @@ pub extern "Rust" fn start(
.boxed()
}
#[unsafe(no_mangle)]
pub extern "Rust" fn stop(
services: Arc<Services>,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
pub fn stop(services: Arc<Services>) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
AssertUnwindSafe(run::stop(services))
.catch_unwind()
.map_err(Error::from_panic)
@@ -41,10 +34,7 @@ pub extern "Rust" fn stop(
.boxed()
}
#[unsafe(no_mangle)]
pub extern "Rust" fn run(
services: &Arc<Services>,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
pub fn run(services: &Arc<Services>) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
AssertUnwindSafe(run::run(services.clone()))
.catch_unwind()
.map_err(Error::from_panic)
+10 -6
View File
@@ -8,7 +8,7 @@ use axum::{
extract::State,
response::{IntoResponse, Response},
};
use conduwuit::{Result, debug, debug_error, debug_warn, err, error, trace};
use conduwuit::{Result, debug_warn, err, error, info, trace};
use conduwuit_service::Services;
use futures::FutureExt;
use http::{Method, StatusCode, Uri};
@@ -64,7 +64,7 @@ pub(crate) async fn handle(
.server
.metrics
.requests_handle_active
.fetch_add(1, Ordering::Relaxed),
.load(Ordering::Relaxed),
handled = %services
.server
.metrics
@@ -81,7 +81,11 @@ async fn execute(
next: axum::middleware::Next,
parent: &Span,
) -> Response {
#[cfg(debug_assertions)]
services
.server
.metrics
.requests_handle_active
.fetch_add(1, Ordering::Relaxed);
conduwuit::defer! {{
_ = services.server
.metrics
@@ -102,11 +106,11 @@ fn handle_result(method: &Method, uri: &Uri, result: Response) -> Result<Respons
let reason = status.canonical_reason().unwrap_or("Unknown Reason");
if status.is_server_error() {
error!(%method, %uri, "{code} {reason}");
info!(%method, %uri, "{code} {reason}");
} else if status.is_client_error() {
debug_error!(%method, %uri, "{code} {reason}");
info!(%method, %uri, "{code} {reason}");
} else if status.is_redirection() {
debug!(%method, %uri, "{code} {reason}");
trace!(%method, %uri, "{code} {reason}");
} else {
trace!(%method, %uri, "{code} {reason}");
}
+5 -1
View File
@@ -8,7 +8,11 @@ use ruma::api::error::ErrorKind;
pub(crate) fn build(services: &Arc<Services>) -> (Router, Guard) {
let router = Router::<state::State>::new();
let (state, guard) = state::create(services.clone());
// SAFETY: `guard` is returned alongside `router` and held in `serve()`
// until the HTTP server has finished serving all requests and dropped
// `router`, ensuring no `State` copy can be dereferenced after `Services`
// is dropped.
let (state, guard) = unsafe { state::create(services.clone()) };
let router = conduwuit_api::router::build(router, state)
.merge(conduwuit_web::build(services))
.fallback(not_found)
+1
View File
@@ -0,0 +1 @@
pub mod notary;
+56
View File
@@ -0,0 +1,56 @@
//! `POST /_matrix/key/*/query`
//!
//! Endpoint to query signing keys through other (notary) servers.
pub mod unstable {
use std::collections::BTreeMap;
use ruma::{
OwnedServerName, OwnedServerSigningKeyId,
api::{
federation::{
authentication::ServerSignatures,
discovery::{ServerSigningKeys, get_remote_server_keys_batch::v2::QueryCriteria},
},
request, response,
},
metadata,
serde::Raw,
};
metadata! {
method: POST,
rate_limited: true,
authentication: ServerSignatures,
path: "/_matrix/key/unstable/org.continuwuity.msc4556/query",
}
#[request]
pub struct Request {
pub server_keys:
BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>,
}
#[response]
pub struct Response {
pub server_keys: Vec<Raw<ServerSigningKeys>>,
}
impl Request {
#[must_use]
pub fn new(
server_keys: BTreeMap<
OwnedServerName,
BTreeMap<OwnedServerSigningKeyId, QueryCriteria>,
>,
) -> Self {
Self { server_keys }
}
}
impl Response {
/// Creates a new `Response` with the given keys.
#[must_use]
pub fn new(server_keys: Vec<Raw<ServerSigningKeys>>) -> Self { Self { server_keys } }
}
}
+2
View File
@@ -6,3 +6,5 @@ pub mod invite_permission_config;
pub mod meowlnir_antispam;
pub mod policy;
pub mod pushers;
pub mod federation;
+1 -12
View File
@@ -16,12 +16,6 @@ crate-type = [
]
[features]
bindgen-runtime = [
"conduwuit-database/bindgen-runtime"
]
bindgen-static = [
"conduwuit-database/bindgen-static"
]
brotli_compression = [
"conduwuit-core/brotli_compression",
"reqwest/brotli",
@@ -35,9 +29,6 @@ gzip_compression = [
"conduwuit-core/gzip_compression",
"reqwest/gzip",
]
http3 = [
"reqwest/http3"
]
io_uring = [
"conduwuit-database/io_uring",
]
@@ -105,6 +96,7 @@ itertools.workspace = true
log.workspace = true
loole.workspace = true
lru-cache.workspace = true
mime.workspace = true
nonzero_ext.workspace = true
p256.workspace = true
regex.workspace = true
@@ -131,9 +123,6 @@ lettre.workspace = true
resolvematrix.workspace = true
serde_urlencoded.workspace = true
openidconnect.workspace = true
# We use this to set TLS backend features on the outdated reqwest bundled by openidconnect,
# which is necessary to call `danger_accept_invalid_certs`.
reqwest_0_12.workspace = true
rand.workspace = true
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
+1 -1
View File
@@ -111,7 +111,7 @@ impl crate::Service for Service {
.local_address(url_preview_bind_addr)
.timeout(Duration::from_secs(config.url_preview_timeout))
.redirect(redirect::Policy::limited(3))
.user_agent(url_preview_user_agent)
.user_agent(url_preview_user_agent.replace("<version>", conduwuit::version_ua()))
.build()?,
external_resource: base(config, reqwest_dns_resolver.clone())?
+7
View File
@@ -223,6 +223,8 @@ impl Data {
x => x,
};*/
// TODO(nex): Oh my god this is awful when can we kill it
let title = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
@@ -321,6 +323,11 @@ impl Data {
video_height,
audio,
audio_size,
..Default::default() /* TODO(nex,silversys): This weird manual field
* de/serialisation just needs replacing with JSON storage to
* avoid this mess. This is consequently intentionally
* dropping information added later (like image alt text).
* I'll do it later. */
})
}
}
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more