Compare commits

..

385 Commits

Author SHA1 Message Date
strawberry d5a9c98657 make federation retry timer-based
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 22:14:30 -04:00
strawberry 395b466b4a rename OutgoingKind enum to OutgoingDestination
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 20:11:18 -04:00
strawberry 0376b58006 use latest main rev for hickory (and for reqwest)
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 20:05:56 -04:00
strawberry 78c1e2f427 adjust DNS default config options
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 19:49:19 -04:00
strawberry 6614b8f6bf ci: remove download env
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 19:15:12 -04:00
strawberry c2fa8e6f8d split up CI steps
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 17:59:01 -04:00
strawberry b8108f5897 cargo fmt
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 17:50:34 -04:00
morguldir cf8358cbe6 Remove extra test flag when publishing to ghcr in the CI
test -n checks if a string is longer than non-zero, but we just need a compare

Signed-off-by: morguldir <morguldir@protonmail.com>
2024-04-17 17:22:52 -04:00
strawberry 7ecc570bb8 Revert "dont use loole for sending channel code"
This reverts commit d0a9666a29.
2024-04-17 15:16:01 -04:00
strawberry 002799177d fix wrong warn message
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 15:15:52 -04:00
strawberry d0a9666a29 dont use loole for sending channel code
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 11a2da3819 fix flake for other oci images too
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry fcda7252c3 fix flake
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry bb43351658 Revert "prevent empty transactions from going out"
This reverts commit cc7cd51e9c.
2024-04-17 14:51:08 -04:00
strawberry e95e4b9200 revert tag name in nix flake for OCI images
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 7300103796 check if user is allowed to invite for restricted room join
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 5667884a6a ci: wrap ref_name in quotes
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
Matthias Ahouansou 19e4befcb8 feat(appservice): ensure users/aliases outside of namespaces are not accessed
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
morguldir b303a774d8 Set the time of the HEAD commit as the OCI created field
Apparently it uses `date -Iseconds` to parse, so we can use @ with a timestamp

Also it doesn't parse `created` in buildImage, only buildLayeredImage

Signed-off-by: morguldir <morguldir@protonmail.com>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 5015fc7a2c add ci and flake support for using ref name to docker image tag
also runs ci on dev branch

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 641399e900 dont auto join rooms if registrations are from appservices
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 6131465d23 don't use bad_database (HTTP 500) for auth check failures
this is not database-related, and may trigger exponential backoff
against us from other servers

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry c5c8934db7 default to shared room history visibility if invalid (per spec)
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry eebdd30ed7 bump cargo.toml dependencies
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
Jason Volk 541fa2d2f7 tweak various log levels and messages
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-17 14:51:08 -04:00
Jason Volk 33cc3d56c1 lazy-construct presence; avoids useless db queries in sender and syncer.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-17 14:51:08 -04:00
Jason Volk 8b003e6be2 add DNS configuration for TCP fallback.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-17 14:51:08 -04:00
Jason Volk b6cf0e6fcf fix trust_negative_responses config option
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-17 14:51:08 -04:00
strawberry 160b9afe97 fix force room banning for room alias resolution
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 8e77d60abf bump major conduwuit version to 0.2.0 due to federation breakage
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 97c63604fd "global" ACLs config option, block room directory requests to forbidden servers
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 47c43769d7 improve some user admin cmd checks
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry 404bdd1db5 allow ban-list-of-rooms to take room aliases
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
Matthias Ahouansou 59be0b3ddc sync upstream token/appservice auth code
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
strawberry c76445e9c1 clear ratelimits when clearing cache too
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-17 14:51:08 -04:00
renovate[bot] 6d47c20efa Update Rust crate chrono to 0.4.38 2024-04-15 07:34:45 -04:00
Jason Volk cc7cd51e9c prevent empty transactions from going out
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-15 07:30:39 -04:00
strawberry 38b15418ca remove created date from OCI image generation
dockerhub and github container registry don't like this,
and i have no idea what to do.

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-15 07:01:00 -04:00
strawberry 775191d5c1 dont include the timestamp in the docker image created date
i hate this

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-15 00:55:07 -04:00
strawberry 527a5cbd73 don't allow moderators dangerous permissions, fix pl 100 state_default
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 23:05:26 -04:00
strawberry d1c139de26 add config option for url_preview_domain_explicit_denylist
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
Jason Volk 287887224f default empty presence string to offline.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk cdb2dff7dd federation incoming logging/tracing related
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk ad4e214d28 polylogarithmic debodge
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk e493b3a60d split prev_event loop body; fetch state; dedup room version procurement.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk 424e13cec2 split signing_keys from event_handler/mod.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk dba0575e75 some optimizations to get_auth_chain()
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk 678d87ced1 add multi_get_or_create_shorteventids()
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk b4080de749 fix multi_get for abstraction and limit to specific column for least-surprise
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk c4ebc2f1d1 fix double-deserialization in federation transaction handler.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk 97fc6c158f add edu select limit and condition for presence.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk 6c9e95f7c9 add config option for allow_outgoing_read_receipts
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
Jason Volk 2b54c00f04 add config option to disable rocksdb LOG file
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-14 22:35:23 -04:00
strawberry 20efe437fb default to debug log level if using debug build
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 878dcd71bb fix invalid database code for servers_invite_via
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 59ba3e3190 only allow admins to send room state events by default (e.g. ACLs)
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 27f8c5b63d don't debug log device display name for guest registrations
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 71611f0ae5 nix: try lastModifiedDate for oci image created date
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 0f3f919e7b add list of passed, failed, and all complement tests
Signed-off-by: strawberry <strawberry@pupbrain.dev>
2024-04-14 22:35:23 -04:00
strawberry ac5dd77783 update complement Dockerfile conduwuit config sed's
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry d9ea3ffe70 raise complement test timeout to 30 minutes from 10 minutes
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry ca8128b195 document commandline args for complement
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry eceef5efa2 add config option for allowing guests to auto join rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry d95c02f575 add config option for logging guest regs in admin room
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry e57051acd8 run all complement tests
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry f263630ac1 fix: use path_and_query() for "uri" in request_map for signatures
resolves X-Matrix signatures being invalid in some edge-cases,
and fixes Complement/Sytest federation tests

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 81f5492675 fix complement script
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry d717329448 cite banner image used by at least github repo
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 068a878260 partially update differences.md, at note at the top
this is hard to maintain now, and i think conduwuit is reaching a point that
it's way too different from upstream to simply "list all the differences" out

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 168858c8de port room directory auth to new auth stuff
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 9b82551e63 bump cargo.lock due to yanked jobserver
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
Matthias Ahouansou a0b65eda1e merge the huge authentication MR mess (reject requests with authentication when not used)
and (fix: allow invalid auth when no auth is required)

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 792a8ddb2f fix rustdoc lint
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
Matthias Ahouansou 8eda3be9ce disable federation at the router level too
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 0d21d70d4a remove two unnecessary matches
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry e5307d44ca log error for /publicRooms requests, simplify it a bit
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 9b5c8c124e fix example config well_known options
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry c2785038d8 add back default derive for WellKnownConfig
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry fdf523a93c bump conduwuit version to 0.1.15
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
Matthias Ahouansou 2d4877f9a5 feat(federation): implement /make_leave and /send_leave
also fixed some clippy lints, and added "event_id" field
removal check for room v1 and 2

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry bfa68e7bc5 refactor well-known stuff to use proper ruma types, config types, etc
this does deprecate the original `well_known_` prefixed config options
with a dedicated/proper config sub-block (`[config.well_known]`)

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 993c0102d9 add unstable support for MSC4125
from https://gitlab.com/famedly/conduit/-/merge_requests/626 with code fixes and clippy lint fixes

MSC4125: https://github.com/matrix-org/matrix-spec-proposals/pull/4125

Co-authored-by: Matthias Ahouansou <matthias@ahouansou.cz>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 46e945d571 bump ruma, deps, and add MSC4125 ruma feature
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry f9e6caef87 simplify getting event content in build_and_append_pdu
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 223f05c922 mark room version 11 as stable
there's nothing unstable about this, and per upstream only unstable
room versions are used if they are complex to support (versions <=5)

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry b7a2482e4d output jemalloc and hmalloc builds in CI, add back target check for cargo.toml
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry befdc29b1e bump deps, fix repo link on cargo.toml
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 593bad7780 remove unnecessary malloc imports, remove cargo.toml env check
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 9883444486 allow unset variables in nix-build-and-cache for unset ATTIC_TOKEN
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 89c22435d5 nix: simplify malloc outputs
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 354487fa10 nix: use HEAD commit's date for docker image creation and reproducible images
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry a94387dcdc maybe add multiple outputs support to nix flake for jemalloc and hardened_malloc
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry 10219a531b dual malloc feature check
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry f6e9c106aa use hardened_malloc by default only on supported targets
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-14 22:35:23 -04:00
strawberry ff0d4c98ee add hardened_malloc-rs feature and global_allocator
Signed-off-by: strawberry <strawberry@pupbrain.dev>
2024-04-14 22:35:23 -04:00
Jason Volk 7d92cad55f deactivate bloom filter
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-10 12:15:34 -04:00
Jason Volk 6345742e8b tweak compaction options
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
Jason Volk c42209c0b3 use Arc<[u64]> rather than Arc<HashSet<u64>> for auth_chain_cache value.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
Jason Volk 2cc72de80e fix lossy origin regression 12a8c9badd
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
Jason Volk 458e56818c polylogarithmic debodge
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
Jason Volk 345be5ba5e use rocksdb caches for a few of the lru_caches
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
strawberry fc44ba6ab3 bump ruma and cargo.lock
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 839a89c968 remove some unnecessary loops
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 40596634c4 respond with actual servers for /_matrix/federation/v1/query/directory requests instead of just us
aka be spec compliant

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 973fed155e config option to allow/disallow federation profile requests
allow_profile_lookup_federation_requests

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 85814e96e3 implement unstable MSC2666 support for querying mutual rooms
https://github.com/matrix-org/matrix-spec-proposals/pull/2666

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 0dc3acea71 build zstd_compression by default for tower-http
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 9be072181c remove unneeded url preview function
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 3438b340a9 remove comments, log channel errors
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 68321ec467 bump conduwuit version to 0.1.14
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
raizo 579d3ce865 replace tokio channels with loole (#256)
* rewrite admin handler to use loole channels

* apply correct formatting

* move all other services to loole channels

* fix ci
2024-04-09 15:26:45 -04:00
strawberry c82c548cbf bump ruma and cargo.lock
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 7f14c08c34 admin command to change tracing log level dynamically
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
Jason Volk a83da4f17b refactor rocksdb opts; split kvtree
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
Jason Volk bade4ed17f conf item to toggle periodic cleanup for rocksdb
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
Jason Volk 865b5d7241 reorganize database crate.
split database Cork into unit.

split database migrations from mod.rs

Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
Jason Volk fe91ce0601 add conf items for rocksdb repair and read-only modes.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
Jason Volk 5f11d68616 tracing instruments for ruma state res
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-09 15:26:45 -04:00
strawberry d92e8e170f list max cache capacity in memory-usage admin cmd
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 72d983d2ec add admin command to fetch /.well-known/matrix/support from server
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 39946beda8 add server-side support for /.well-known/matrix/support
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
Matthias Ahouansou c946352e7f fix(sync): send phoney leave event where room state is unknown on invite rejection
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
Matthias Ahouansou 3b5794b5bd fix(membership): check if server is in room to decide whether to do remote leaves
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
Matthias Ahouansou 6078b5ee9d fixup! feat: support /make_join and /send_join for restricted rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
Matthias Ahouansou d8949d55c4 refactor(state_accessor): add method to check if a user can invite another user
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 70ce9c299e bump ruma and cargo.lock
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-09 15:26:45 -04:00
strawberry 2516d44cb1 dont 404 and respond+update with default push rules if non-existent
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry e4a987cf80 bump ruma and declare support for unstable MSC3026 (busy presence state)
https://github.com/girlbossceo/ruma/commit/a938640491bf2bf98196cecd4102c5749f89a554

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry db8e7e5382 TEMP: remove user_is_invited stuff
this is clearly unfinished right now

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
Matthias Ahouansou f0b91461a0 refactor(state_accessor): add method to check if a user can invite another user
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
renovate[bot] a8452f3ae1 chore(deps): update nixos/nix docker tag to v2.21.2 2024-04-05 22:15:16 -04:00
Matthias Ahouansou 321a6ca0fe feat(membership): check if user already has the membership that is requested to be set
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry 0307cdf2b2 bump ruma
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry 1ccc777532 bump conduwuit version to 0.1.13
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
Jason Volk ebb71b7d7c add contains_url filter to /messages; also split out visibility filter.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-05 22:15:16 -04:00
Jason Volk cde06125b8 immutable cache-control for media
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-05 22:15:16 -04:00
strawberry bfd91c93e0 enable presence by default, remove presence warning
it is now very very good

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry 1b84f5a855 resolve wildcard_imports and checked_conversations lints
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry f0a0704a93 slight adjustments, remove some explicit annotations
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
Jason Volk 9cc4f3e929 split main
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-05 22:15:16 -04:00
Jason Volk 7f6c19f066 fix using same federation reqwest pool after sender deduplication.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-05 22:15:16 -04:00
Jason Volk ca1c77d76b refactor presence to not involve rooms.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-05 22:15:16 -04:00
Jason Volk 885224ab76 add tools for user-to-server and user-to-user visibility
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-05 22:15:16 -04:00
strawberry 3c2e8a5250 fix spaces test lints
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
Jason Volk 568136296f add granular conf items for all memory caches
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-05 22:15:16 -04:00
Matthias Ahouansou 5c30d2b2b0 fix(membership): perform stricter checks when choosing an authorized user
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
Matthias Ahouansou 68e64392f0 fix(membership): remove join_authorized_via_users_server field on state update
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
Matthias Ahouansou 172d71e365 check if user is joined in the room in user_can_invite
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry c803891634 better event_type checks for send_state_event_for_key_helper
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry 0214caeaea always allow count to be filled in search response
i fail to see any reason why we would always want
this to be None

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry a2ee6b410e add another element_hacks feature check
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry ab0182ace4 check if user is allowed to invite for join_authorized_via_users_server in join_room_by_id_helper
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry b9e442b694 use map_or in user_can_invite
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry ddcf43f1b8 replace ErrorKind::Forbidden with forbidden() non-exhaustive constructor
https://github.com/ruma/ruma/commit/917584e0cae4ae8642625f234f22f049bc159fee

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry 13cd9c4c38 bump cargo.lock due to RUSTSEC-2024-0332, and bump ruma
https://rustsec.org/advisories/RUSTSEC-2024-0332

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
Matthias Ahouansou 49eb418786 feat: support /make_join and /send_join for restricted rooms
from https://gitlab.com/famedly/conduit/-/merge_requests/618

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
Matthias Ahouansou ed960f41ac feat: recurse relationships (and fix some lints)
from https://gitlab.com/famedly/conduit/-/merge_requests/613

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry 661dba688a add trivially_copy_pass_by_ref lint
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry 3efb3a93ca sync hierarchy over federation MR
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-05 22:15:16 -04:00
strawberry bd69d9b565 move invalid 200 response log to info
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-03 12:52:46 -04:00
strawberry 6800f91949 remove some services() usage on startup for accessing config
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-03 12:52:46 -04:00
strawberry bd117bdf0d use config.allow_local_presence instead of services()
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-03 12:52:46 -04:00
strawberry d6651ab422 remove unused import
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-03 12:52:46 -04:00
K900 8134dd9151 Reduce number of separate sources of truth for presence disabled-ness
Instead of checking if we should update every time we want to update,
call the updater every time and decide internally.
2024-04-03 12:52:46 -04:00
strawberry 34fe7b7369 drop /hierarchy requests to debug
this is not helpful informational logging

```
2024-04-02T04:40:52.590444Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Asking thomcat.rocks for /hierarchy
2024-04-02T04:40:52.628248Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Asking hackingfor.eu for /hierarchy
2024-04-02T04:40:52.808526Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Asking matrix.org for /hierarchy
2024-04-02T04:40:52.920936Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Asking matrix.org for /hierarchy
2024-04-02T04:40:52.959362Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Got response from matrix.org for /hierarchy
Response { children: [], inaccessible_children: [], room: SpaceHierarchyParentSummary { canonical_alias: Some("#cybersec-whonix:matrix.org"), name: Some("Whonix"), num_joined_members: 329, room_id: "!OJFkLJksWastbfdRuf:matrix.org", topic: Some("| Part of the Cybersec matrix.org community (#cyber-space:matrix.org) | RULES: https://cybersec-rules.thomcat.rocks | Whonix-focused room | Off-topic chat is fine. Keep it brief and/or move it to #cybersec-offtopic:matrix.org"), world_readable: true, guest_can_join: false, avatar_url: Some("mxc://matrix.org/DMJtrQdhQHKxeODrSibtrczX"), join_rule: "public", room_type: None, children_state: [], allowed_room_ids: [] } }
2024-04-02T04:40:52.959762Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Asking matrix.org for /hierarchy
2024-04-02T04:40:53.109611Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Got response from matrix.org for /hierarchy
Response { children: [], inaccessible_children: [], room: SpaceHierarchyParentSummary { canonical_alias: Some("#lockpicking:matrix.org"), name: Some("Lockpicking"), num_joined_members: 284, room_id: "!uEYjSxQOZnHEkiurTP:matrix.org", topic: Some("| Part of the Cybersec matrix.org community (#cyber-space:matrix.org) | RULES: https://cybersec-rules.thomcat.rocks | Off-topic chat is fine. Keep it brief and/or move it to #cybersec-offtopic:matrix.org"), world_readable: false, guest_can_join: false, avatar_url: Some("mxc://thomcat.rocks/cSeFfMLUdjymKdkUmXtIQTjf"), join_rule: "public", room_type: None, children_state: [], allowed_room_ids: [] } }
2024-04-02T04:40:53.109880Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Asking matrix.org for /hierarchy
2024-04-02T04:40:53.261581Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Got response from matrix.org for /hierarchy
Response { children: [], inaccessible_children: [], room: SpaceHierarchyParentSummary { canonical_alias: Some("#cybersec-rss:matrix.org"), name: Some("Cybersecurity-RSS"), num_joined_members: 347, room_id: "!IVHnAZkhJOhdZxlHRA:matrix.org", topic: Some("|   Part of the Cybersec matrix.org community (#cyber-space:matrix.org)   |   Suggestions to our RSS feed list welcome at #cybersecurity:matrix.org"), world_readable: true, guest_can_join: false, avatar_url: Some("mxc://thomcat.rocks/ugdubBloOkVCYxqFzdVoPwcV"), join_rule: "public", room_type: None, children_state: [], allowed_room_ids: [] } }
2024-04-02T04:40:53.305166Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Got response from matrix.org for /hierarchy
Response { children: [], inaccessible_children: [], room: SpaceHierarchyParentSummary { canonical_alias: Some("#cybersec-whonix:matrix.org"), name: Some("Whonix"), num_joined_members: 329, room_id: "!OJFkLJksWastbfdRuf:matrix.org", topic: Some("| Part of the Cybersec matrix.org community (#cyber-space:matrix.org) | RULES: https://cybersec-rules.thomcat.rocks | Whonix-focused room | Off-topic chat is fine. Keep it brief and/or move it to #cybersec-offtopic:matrix.org"), world_readable: true, guest_can_join: false, avatar_url: Some("mxc://matrix.org/DMJtrQdhQHKxeODrSibtrczX"), join_rule: "public", room_type: None, children_state: [], allowed_room_ids: [] } }
2024-04-02T04:40:53.323257Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Asking thomcat.rocks for /hierarchy
2024-04-02T04:40:53.323672Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Asking matrix.org for /hierarchy
2024-04-02T04:40:53.369721Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Asking matrix.org for /hierarchy
2024-04-02T04:40:53.529250Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Got response from matrix.org for /hierarchy
Response { children: [], inaccessible_children: [], room: SpaceHierarchyParentSummary { canonical_alias: None, name: None, num_joined_members: 1463, room_id: "!aBXqGDWIxVYeYxVbRu:matrix.org", topic: Some("| Part of the Cybersec matrix.org community (#cyber-space:matrix.org) | The room needs urgent attention? @ all the mods! | RULES: https://cybersec-rules.thomcat.rocks | \"you seem to be completely in lack of basic knowledge of how a computer or any programming language operates, to the point that any attempt of discussing any security measures is a complete waste of time\""), world_readable: false, guest_can_join: false, avatar_url: Some("mxc://thomcat.rocks/DjRWzuYjLkScQYPySYNedlFr"), join_rule: "public", room_type: None, children_state: [], allowed_room_ids: [] } }
2024-04-02T04:40:53.546581Z  INFO http_request{path=/_matrix/client/v1/rooms/:room_id/hierarchy}: conduit::service::rooms::spaces: Got response from matrix.org for /hierarchy
Response { children: [], inaccessible_children: [], room: SpaceHierarchyParentSummary { canonical_alias: None, name: None, num_joined_members: 1463, room_id: "!aBXqGDWIxVYeYxVbRu:matrix.org", topic: Some("| Part of the Cybersec matrix.org community (#cyber-space:matrix.org) | The room needs urgent attention? @ all the mods! | RULES: https://cybersec-rules.thomcat.rocks | \"you seem to be completely in lack of basic knowledge of how a computer or any programming language operates, to the point that any attempt of discussing any security measures is a complete waste of time\""), world_readable: false, guest_can_join: false, avatar_url: Some("mxc://thomcat.rocks/DjRWzuYjLkScQYPySYNedlFr"), join_rule: "public", room_type: None, children_state: [], allowed_room_ids: [] } }
```

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-03 12:52:46 -04:00
strawberry 667db8e8a3 output error if sending to trusted key server failed
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-03 12:52:46 -04:00
strawberry 935202eaa3 move panic = "abort" to release-high-perf build profile
i don't really want to do this but broken dependencies
are making this unavoidable

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry a20b071a8a add manual_let_else lint
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
Matthias Ahouansou c31fb7134a fix: do not expect that all http requests are valid reqwest requests
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
Jason Volk 93a43a0eda add conf item for exact amount of startup netburst.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-02 00:32:41 -04:00
Jason Volk 0ba8d1318d move presence up two levels out of rooms.edus and rooms.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-02 00:32:41 -04:00
Jason Volk 9790477b0e move typing feature up one level out of rooms.edus.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-02 00:32:41 -04:00
Jason Volk 89a919ce75 move read_receipt feature up one level out of rooms.edus.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-02 00:32:41 -04:00
Jason Volk 22b123de7b improve tracing attributes in sending stack.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-02 00:32:41 -04:00
Jason Volk a87e7d8e17 split out, dedup, cleanup sending service methods
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-02 00:32:41 -04:00
Jason Volk 3c09313f79 move and reorganize sending codepaths; no functional changes
Signed-off-by: Jason Volk <jason@zemos.net>
2024-04-02 00:32:41 -04:00
strawberry a72ea54d11 update differences.md
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry e75fb17899 ci: dont run docker stuff if not a PR *and* both env variables are not empty
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry ed5be58f9f ci: only run dockerhub steps if username and token are not empty
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry 95ca7bc3e4 move complement dir to tests dir
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
Matthias Ahouansou 2a48e562e6 fix: return error when trying to unregister unknown appservice id
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry 51afde9e98 admin cmd to send a request/ping to /_matrix/federation/v1/version
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry 738878f6ff bump conduwuit version to 0.1.12
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry fec4b3c953 delete conduit_bin feature
i dont know what's the point of this

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry a0ad911688 stop sending make_join requests after 50 failures
this is a very generous number

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry af6c72fa84 stop sending make_join if 15 servers responded with unsupported/invalid room version
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry ce414023a4 default to None room topic if invalid/redacted for spaces too
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
Matthias Ahouansou c61aee4f1c fix: reject /register requests when there is no token and the type is appservice
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry 7a1a271518 dont allow m.call.invite timeline events in public rooms
also simplifies the encrypted event check (we dont
need to convert anything here)

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
renovate[bot] 71cea1c567 fix(deps): update rust crate image to 0.25.1 2024-04-02 00:32:41 -04:00
strawberry ff3bc3fb09 on new room creations: only allow moderators to call public rooms
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry 72b60c4770 add lockdown_public_room_directory config option
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-04-02 00:32:41 -04:00
strawberry 00ddc1c88e generalise and cleanup docs a bit
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
Jason Volk 114324e26c remove write_lock around rocksdb
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-30 22:06:18 -04:00
strawberry 141a6bc73e dont panic when failing to create admin room response/PDU
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 712cdef6c7 drop url_preview_max_spider_size to 384KB
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 9cd25db955 list resolver caches in memory-usage admin cmd
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 89e3d17e65 update differences.md
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
Jason Volk 18c34434bc add outgoing federation typing and conf items
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-30 22:06:18 -04:00
Jason Volk 4a57592378 add clamp util.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-30 22:06:18 -04:00
Jason Volk 4becbed2a7 refactor sending interface stack
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-30 22:06:18 -04:00
Jason Volk f956e8c3b5 move and deduplicate read receipt flusher.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-30 22:06:18 -04:00
strawberry 6fa2e0814c dont ignore all tracing logs for sentry
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 350d25a368 bump cargo.lock
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 2b3ee3bf0b set allow_incoming_presence to true by default
this is harmless and is a better UX anyways

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry f818c368c0 config options for HTTP compression on tower+reqwest
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 44435f76fe bump conduwuit version to 0.1.11
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry b437e47d8c partial tower/tower-http sentry and gzip/brotli compression
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
renovate[bot] 3103ad2205 chore(deps): update actions/configure-pages action to v5 2024-03-30 22:06:18 -04:00
strawberry b36c397702 mark msc2285 (private read receipts) as supported
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 60623cd14b dont return bad_config for private room directory requests
this would log as an error and as HTTP 500

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry b39aa00a9b add trusted keyservers to backfill from if in room
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry babf29d217 fix sentry features, add sentry_traces_sample_rate
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 835c2112c8 dont depend on openssl, add sentry_tracing
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 47889410eb use CONDUIT_VERSION_EXTRA in endpoints
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 87a7c8d9e8 add opt-in sentry logging, improve main function
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 93b03fe338 use true_fn for startup_netburst option
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 07135cc849 add two pedantic clippy lints
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
Jason Volk 125ff21c88 add conf item to toggle startup netburst (for developers).
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-30 22:06:18 -04:00
Jason Volk 3cf67f3993 disambiguate logging macros by locking log crate
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-30 22:06:18 -04:00
strawberry cf8727a5f8 only test long_file_names_works if using sha256_media feature
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 77475dacf5 bump rocksdb, switch to fork of rocksdb, bump flake
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
renovate[bot] 80f624c0fb fix(deps): update rust crate serde_html_form to 0.2.6 2024-03-30 22:06:18 -04:00
strawberry 98e480ddcd revert checking appserice destination against ip_range_denylist
this is the url field in the appservice registration file,
this is almost always localhost and the admin should
be vetting the appservice registration yaml file before
registering it anyways.

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
renovate[bot] e4d1d4e86d fix(deps): update rust crate tokio to 1.37.0 2024-03-30 22:06:18 -04:00
renovate[bot] 73bdf3c5cc chore(deps): update aquasecurity/trivy-action action to v0.19.0 2024-03-30 22:06:18 -04:00
strawberry ee3160dd1b allow manual_unwrap_or_default lint here
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 8915b6469d forbid admin room from being made public
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 38c2e5567e remove unwrap from admin room build_and_append_pdu
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 1893b45de3 propagate errors if we fail processing admin room subcommands
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 48d1a3af3c resolve the last few relevant pedantic clippy lints
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry fa71dd4b4c use body.dir for relations now
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 92dbe82675 remove unnecessary clone from into_iter
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 6aaf169c45 fix wrong order of logic, prefer room alias server first if available
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry e9793868ec add recursion_depth None for now
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 0d50dfd7cf bump ruma and cargo.lock
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 567b24e410 add /_conduwuit/server_version route
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 4f1f6fa56f drop -alpha from version string
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-30 22:06:18 -04:00
strawberry 051668b62b use rusqlite commit before c-strings were added
this is a 1.77.0 rust feature, this would require
bumping MSRV

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 4b4b63eda4 bump cargo.lock
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
renovate[bot] 50c870cc1d chore(deps): update docker docker tag to v26 2024-03-26 22:24:24 -04:00
renovate[bot] b252572db4 fix(deps): update rust crate clap to 4.5.4 2024-03-26 22:24:24 -04:00
renovate[bot] cf474d96f0 fix(deps): update rust crate serde_json to 1.0.115 2024-03-26 22:24:24 -04:00
renovate[bot] aa2af6bf93 chore(deps): update nixos/nix docker tag to v2.21.1 2024-03-26 22:24:24 -04:00
strawberry 53c0cfd70e docs: fix a few headlines
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 3d0f0cc1ce add query_all_nameservers config option
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
Jason Volk cb12f285e9 improve incoming http request and other logging
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-26 22:24:24 -04:00
Jason Volk 0df1f84cc8 set trust_negative_responses in nameserver config.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-26 22:24:24 -04:00
strawberry e6c34b982f fix git blame ignore revs
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 08a21b8ee2 better maximize_fd_limit test
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
Jason Volk edb4468771 clear destinations cache in clear_caches fn.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-26 22:24:24 -04:00
strawberry c31de51efc ignore rev 16294831 from blame
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 868976a149 use chain_width 60
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 9d6b070f35 Revert "update rustfmt"
This reverts commit e517f2bad8c8a4181f70126067ea49d8b3ad1635.
2024-03-26 22:24:24 -04:00
Jason Volk 07596d866f update rustfmt 2024-03-26 22:24:24 -04:00
Jason Volk 525379f8ac enable caching in hickory_dns w/ configurables.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-26 22:24:24 -04:00
Jason Volk 21874f8ab7 eliminate gai resolver.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-26 22:24:24 -04:00
Jason Volk f5da75e476 split structs from service/globals/mod.rs into separate units
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-26 22:24:24 -04:00
Jason Volk f3bc87c4e6 elaborate on RocksDB recovery modes in example-config.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-26 22:24:24 -04:00
strawberry 24faf4dd26 revert 0297cfe307
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 6f7113950b raise too-many-lines-threshold to 700 (for now?)
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 3f9825788e check URL preview requests against ip_range_denylist
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry bef0459fb8 bump conduwuit version to 0.1.10
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 4be37fbe8d only remove event_id field in room v1 and v2
no this doesnt make those rooms work,
just a why not thing

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 0863bec098 allow non-joined users to get aliases of world_readable rooms
`user_can_see_state_events` checks if user is joined,
or if room visibility is world_readable

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 380b61184d reduce high presence timeouts
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 32ab88e68a check the URL and response remote address for ip_range_denylist
the previous only checked the server_name

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry fbefbd57be implement include_state search criteria
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry c2e89b939c add element web search count hack (?)
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry f4146de17d add feature for smElement client hacks
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 55813e90bf add EditorConfig vs code extension to recommendations
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
Jason Volk d3c9f5595a split admin commands into modules.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-26 22:24:24 -04:00
Jason Volk 6b1933914d add file listing to database abstraction.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-26 22:24:24 -04:00
strawberry bdf3997de5 pin ruma rev
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 7bd56765ef fix some more pedantic clippy lints
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry a7e6fe8b60 fix infinite loop lint
this is actually better to do CPU-wise anyways

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 8dad4461b4 log if our trusted key server is broken for batch requests
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-26 22:24:24 -04:00
strawberry 101cb34f9a make rocksdb_recovery_mode a u8, document it
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Jason Volk 331c0b37cd add conf item for alternate rocksdb recovery modes. 2024-03-23 01:49:27 -04:00
strawberry a57f4db207 bump default_sender_timeout from 75 seconds to 180
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 27d6ce3cc5 log path parameters when try http request fails
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 6e0d6c78fb use BTreeMap again
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 27d83a51f2 remove unnecessary match arm for space invite join_rule
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
renovate[bot] 8fab2cd94a fix(deps): update rust crate regex to 1.10.4 2024-03-23 01:49:27 -04:00
strawberry 7fbbdf83ab forgot to fix these ones too
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 3bc2af7d26 resolve and add even more pedantic clippy lints
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 0bb5115bd1 resolve clippy match_bool
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 9d0b647911 resolve couple pedantic clippy lints, remove unnecessary qualifications
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 6d7ef80aba format cargo.toml
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 931e1cad06 ci: make docker username and GHCR variables
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 9832f11074 add zed to .gitignore
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry d8c6c2930e update differences.md
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 23ee479062 only allow up to info level logging on release builds
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry c5afc6bf98 bump ruma and bytes
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 0384b48b4a add main.rs test for unix maximize_fd_limit
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Charles Hall 74c34e885e allow including extra info in --version output
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 9f7431c08f remove rocksdb prefix extractor
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Timo Kösters 710a6b5c6f refactor: remove previous typing implementation and add sync wakeup for new one
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Matthias Ahouansou 60f2471f59 refactor appservice type stuff
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 7c9c5b1d78 log room for backfill_if_required requests
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry d7fc6874d1 Revert RocksDB 9.0.0 update
there seems to be a regression, likely from https://github.com/facebook/rocksdb/issues/12361 / https://github.com/facebook/rocksdb/pull/12309

```
[1/0/2 built] building rocksdb-9.0.0 (configurePhase): -- Detecting CXX compile features - donedirenv: ([/Users/strawberry/.nix-profile/bin/direnv export zsh]) is taking a while to execute. Use CTRL-C to give up.
error: builder for '/nix/store/9slwgpnardhn2vqzqhn361ic668n38wq-rocksdb-9.0.0.drv' failed with exit code 1;
       last 10 log lines:
       > -- Found lz4: /nix/store/cafwv4439qbm2ij04mpc7xz5m3f7mfix-lz4-1.9.4/lib/liblz4.dylib
       > CMake Error at /nix/store/bin32lqag7lx38994xpf9jvhk1xbd64c-cmake-3.28.2/share/cmake-3.28/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
       >   Could NOT find zstd (missing: ZSTD_INCLUDE_DIRS)
       > Call Stack (most recent call first):
       >   /nix/store/bin32lqag7lx38994xpf9jvhk1xbd64c-cmake-3.28.2/share/cmake-3.28/Modules/FindPackageHandleStandardArgs.cmake:600 (_FPHSA_FAILURE_MESSAGE)
       >   cmake/modules/Findzstd.cmake:17 (find_package_handle_standard_args)
       >   CMakeLists.txt:167 (find_package)
       >
       >
       > -- Configuring incomplete, errors occurred!
       For full logs, run 'nix log /nix/store/9slwgpnardhn2vqzqhn361ic668n38wq-rocksdb-9.0.0.drv'.
error: 1 dependencies of derivation '/nix/store/ir8jf2wic98iymjlk7d2i1kjjsgv15v2-nix-shell-env.drv' failed to build
```

happens in both rust-rocksdb and our fork of rust-rocksdb

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry ab5552ec6c Revert "bump rocksdb in nix flake"
This reverts commit 4475c1ba25.
2024-03-23 01:49:27 -04:00
strawberry fdb0ccc9dc bump rocksdb in nix flake
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 10e1801974 remove/update incorrect example config comment
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry f27a2bace8 bump conduwuit version to 0.1.9
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 37c040dc77 fix incorrect v1 URL path for URL previews
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 90b8ac0c64 follow 3 redirects for federation requests instead of 2
just in case

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 33dfa64963 follow 3 redirects for URL previews instead of 6
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 713b1b23c9 document new timeout config options
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 9ed3e64a60 oops forgot to commit these new files
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Jason Volk 9334f938ae refactor reqwest client suite w/ conf items.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-23 01:49:27 -04:00
Jason Volk 61b1d6d869 add corks to coalesce writes for several heavy calltrees.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-23 01:49:27 -04:00
Jason Volk 3f60365cc6 add write buffer corking using rocksdb manual_wal_flush.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-23 01:49:27 -04:00
Charles Hall 3969b667ba make chapter name reflect file name
Personally I think this makes more sense anyway.
2024-03-23 01:49:27 -04:00
Charles Hall 52fb4d9752 reduce scope of nixos documentation
There are so many ways to do this we realistically shouldn't bother
describing any of them, especially because people should be learning all
the options and choosing the one that suits them best anyway.

Co-authored-by: strawberry <strawberry@puppygock.gay>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 3059801ed8 rename Docker header
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Charles Hall ed96bd2053 rename "simple" deployment to "generic"
The main thing this section is really useful for is explaining how to
configure various reverse proxies, which applies to basically anything.

Also, remove all the language about this being "recommended", because
nothing in this documentation is actually tested in CI.

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Charles Hall 58f113451f remove section about cross compilation
It is very stale. Please just use Nix. Trying to do it outside of Nix
will be an exercise in frustration, I guarantee it.

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 2e713753d5 bump ruma, rust-rocksdb, and cargo.lock
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Charles Hall 831c452af9 avoid duplicating links in documentation
Because one might forget to update them. I did, initially, which is why
I'm making this change.
2024-03-23 01:49:27 -04:00
Charles Hall 2de47fc9c0 add mdbook to the devshell 2024-03-23 01:49:27 -04:00
renovate[bot] 99c38d2a5e fix(deps): update rust crate jsonwebtoken to 9.3.0 2024-03-23 01:49:27 -04:00
strawberry 66a36a5576 significantly drop URL preview timeouts
theres no reason for us to spend so long trying to get
a preview

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 2470fa91d8 raise connection pooling idle timeout to 50 seconds
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 1e07f417ba raise get_keys_helper timeout even more
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 4dfefda03b update book.toml for conduwuit
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 55708949cc slight request logging improvements
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 5ed55da0dd auto join rooms from admin room created users too
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry f06f30ca2a fix wrong error message about presence
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 9715b07b38 skip rooms we have not joined before for auto-join
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry dda3b0e7e2 default to None if "name" in m.room.name is empty
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 3e902836cc simplify heroes get_avatar
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 7066b7b428 feat: automatically join rooms on registration
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 2ca357e44c use unwrap_or_default if timestamp conversion fails
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 694986db29 check+clarify online backups are RocksDB only
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 7af78cf708 return helpful message instead of empty message if no backups
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry f9a60bf48b make database_backup_path a PathBuf
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
strawberry 5a434e7f3d make database_path a PathBuf
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
renovate[bot] ab420e8a90 chore(deps): update docker docker tag to v25.0.5 2024-03-23 01:49:27 -04:00
strawberry f7e8054a00 fix lints
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Jason Volk fa942aedd7 add database backup with admin commands
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-23 01:49:27 -04:00
strawberry ece817c562 db_cache_capacity_mb defaults to 256.0 now
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Jason Volk e9d67ecb53 reconfigure and optimize rocksdb options.
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Jason Volk 544c38341b add sync() to db abstraction for fsync(2). 2024-03-23 01:49:27 -04:00
Jason Volk d4cfee4e71 add rocksdb env to options. keep options in engine state.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-23 01:49:27 -04:00
Jason Volk af605a03b7 add abstract fallbacks for kv batch methods.
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-23 01:49:27 -04:00
strawberry 10e2eb5e08 bump rocksdb, deps, switch to hickory dns/resolver
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
renovate[bot] 5eb4010e03 fix(deps): update rust crate serde_yaml to 0.9.33 2024-03-23 01:49:27 -04:00
strawberry a405f10f82 fix docs
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-23 01:49:27 -04:00
Jason Volk 7b15f85c62 fix zealous client connection close (regression 809c9b4481)
Signed-off-by: Jason Volk <jason@zemos.net>
2024-03-23 01:49:27 -04:00
strawberry 7809f0a6ae bump ruma and cargo.lock
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 85cb559002 update DIFFERENCES.md
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 61f49ecf0e rename forbidden_room_names to forbidden_alias_names
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 5e880ac44a declare various missing server capabilities
this should fix FluffyChat password resets, and
other possible client issues that expose features
based on server capabilities.

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 7f7bd91e8a add comment for future org.matrix.msc2285.stable
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 96e1938616 remove unnecessary assert for test
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 694b926366 move docs/gh pages into separate workflow
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry c8c3a9ed43 docs: s/conduit-example/conduwuit-example
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 896c372cfe disable broken assertions_on_result_states lint
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 2be43d3712 fix failing to register new appservice accounts
this is such a terribly named enum field.

Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 0301c7c083 fix Appservice AccessTokenOptional authentication type endpoints
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry a2a7b81076 fix test
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry ea6425712a dont setup github pages if pull request
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 19f313b91d deploy book to github pages
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry e2827a1a79 build documentation/book in github actions
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry b1b88601ab docs: dont point everyone to element
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
Samuel Meenzen e9ce642795 docs: build docs using mdBook, build in CI, deploy to gitlab pages
squashed from https://gitlab.com/famedly/conduit/-/merge_requests/604

added differences.md

Co-authored-by: Charles Hall <charles@computer.surgery>
Co-authored-by: strawberry <strawberry@puppygock.gay>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry a7966b8f05 config option to allow incoming remote read receipts
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry b78d79a45a ignore deactivated users and remote user profiles wih forbidden_usernames
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 8c3f946e97 bump conduwuit version to 0.1.8
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
Jason Volk abceae26de add flush suite to sending service; trigger on read receipts.
Signed-off-by: Jason Volk <jason@zemos.net>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
Jason Volk 95ea665649 complete federation destination caching preempting getaddrinfo(3).
fixed some clippy lints and spacing adjusted

Signed-off-by: Jason Volk <jason@zemos.net>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
Jason Volk 6fe0ea05b8 add remove_batch with transaction to database abstraction.
adjusted to make building sqlite happy again

Signed-off-by: Jason Volk <jason@zemos.net>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
Jason Volk ba03d55879 clear dns and tls-override caches from !admin command.
Signed-off-by: Jason Volk <jason@zemos.net>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 9b5c4697bf bump async-trait and ruma
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 16572a868a slight inclusive wording changes
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry b079b94715 track media uploads by user
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 19135eaa58 document forbidden room aliases and usernames
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
Matthias Ahouansou e7c6b8c91b feat(spaces): hierarchy over federation
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 1ecbf55d68 check allow_federation in send_federation_request
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
Matthias Ahouansou 4c841cd909 refactor: check if federation is disabled inside the authcheck where possible
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
Matthias Ahouansou c48535ef32 fix: avoid panics when admin room is not available
Co-authored-by: strawberry <strawberry@puppygock.gay>
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry 5473631e1d admin command to see a room's full state from our database
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry de8f773620 slight wording updates
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
strawberry b4fa306a20 remove rocksdb optimize_level_style_compaction
Signed-off-by: strawberry <strawberry@puppygock.gay>
2024-03-19 00:17:41 -04:00
191 changed files with 20397 additions and 11496 deletions
+4
View File
@@ -1,3 +1,7 @@
# .git-blame-ignore-revs
# adds a proper rustfmt.toml and formats the entire codebase
1d1ac065141181438e744e7d8abd0e45f75a2f91
f419c64aca300a338096b4e0db4c73ace54f23d0
# use chain_width 60
162948313c212193965dece50b816ef0903172ba
5998a0d883d31b866f7c8c46433a8857eae51a89
+144 -128
View File
@@ -5,24 +5,30 @@ on:
push:
branches:
- main
- dev
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
env:
# Required to make some things output color
TERM: ansi
# Publishing to my nix binary cache
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
# Just in case incremental is still being set to true, speeds up CI
CARGO_INCREMENTAL: 0
# Custom nix binary cache if fork is being used
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
permissions:
packages: write
contents: read
jobs:
ci:
name: CI and Artifacts
setup:
name: CI Setup
runs-on: ubuntu-latest
steps:
- name: Sync repository
uses: actions/checkout@v4
@@ -86,165 +92,175 @@ jobs:
./bin/nix-build-and-cache .#devShells.x86_64-linux.default.inputDerivation
build-and-test:
name: CI and Artifacts
needs: setup
runs-on: ubuntu-latest
strategy:
matrix:
target: [
"static-x86_64-unknown-linux-musl",
"static-x86_64-unknown-linux-musl-jemalloc",
"static-x86_64-unknown-linux-musl-hmalloc",
"static-aarch64-unknown-linux-musl",
"static-aarch64-unknown-linux-musl-jemalloc",
"static-aarch64-unknown-linux-musl-hmalloc",
]
oci-target: [
"x86_64-unknown-linux-gnu",
"x86_64-unknown-linux-musl",
"x86_64-unknown-linux-musl-jemalloc",
"x86_64-unknown-linux-musl-hmalloc",
"aarch64-unknown-linux-musl",
"aarch64-unknown-linux-musl-jemalloc",
"aarch64-unknown-linux-musl-hmalloc",
]
steps:
- name: Perform continuous integration
run: direnv exec . engage
- name: Build static-x86_64-unknown-linux-musl and Create static deb-x86_64-unknown-linux-musl
- name: Build static artifacts
run: |
./bin/nix-build-and-cache .#static-x86_64-unknown-linux-musl
./bin/nix-build-and-cache .#${{ matrix.target }}
mkdir -p target/release
cp -v -f result/bin/conduit target/release
direnv exec . cargo deb --no-build
direnv exec . cargo deb --no-build --output target/debian/${{ matrix.target }}.deb
- name: Upload artifact static-x86_64-unknown-linux-musl
- name: Upload static artifacts
uses: actions/upload-artifact@v4
with:
name: static-x86_64-unknown-linux-musl
name: ${{ matrix.target }}
path: result/bin/conduit
if-no-files-found: error
- name: Upload artifact deb-x86_64-unknown-linux-musl
- name: Upload static deb artifacts
uses: actions/upload-artifact@v4
with:
name: x86_64-unknown-linux-musl.deb
path: target/debian/*.deb
name: ${{ matrix.target }}.deb
path: target/debian/${{ matrix.target }}.deb
if-no-files-found: error
- name: Build static-aarch64-unknown-linux-musl
- name: Build OCI images
run: |
./bin/nix-build-and-cache .#static-aarch64-unknown-linux-musl
./bin/nix-build-and-cache .#oci-image-${{ matrix.oci-target }}
cp -v -f result oci-image-${{ matrix.oci-target }}.tar.gz
- name: Upload artifact static-aarch64-unknown-linux-musl
- name: Upload OCI image artifacts
uses: actions/upload-artifact@v4
with:
name: static-aarch64-unknown-linux-musl
path: result/bin/conduit
if-no-files-found: error
- name: Build oci-image-x86_64-unknown-linux-gnu
run: |
./bin/nix-build-and-cache .#oci-image
cp -v -f result oci-image-amd64.tar.gz
- name: Upload artifact oci-image-x86_64-unknown-linux-gnu
uses: actions/upload-artifact@v4
with:
name: oci-image-x86_64-unknown-linux-gnu
path: oci-image-amd64.tar.gz
name: oci-image-${{ matrix.oci-target }}
path: oci-image-${{ matrix.oci-target }}.tar.gz
if-no-files-found: error
# don't compress again
compression-level: 0
- name: Build oci-image-aarch64-unknown-linux-musl
run: |
./bin/nix-build-and-cache .#oci-image-aarch64-unknown-linux-musl
cp -v -f result oci-image-arm64v8.tar.gz
- name: Upload artifact oci-image-aarch64-unknown-linux-musl
uses: actions/upload-artifact@v4
with:
name: oci-image-aarch64-unknown-linux-musl
path: oci-image-arm64v8.tar.gz
if-no-files-found: error
# don't compress again
compression-level: 0
- name: Extract metadata for Dockerhub
env:
REGISTRY: registry.hub.docker.com
IMAGE_NAME: ${{ github.repository }}
id: meta-dockerhub
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
publish:
needs: build-and-test
runs-on: ubuntu-latest
steps:
- name: Extract metadata for Dockerhub
env:
REGISTRY: registry.hub.docker.com
IMAGE_NAME: ${{ github.repository }}
id: meta-dockerhub
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Extract metadata for GitHub Container Registry
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
id: meta-ghcr
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Extract metadata for GitHub Container Registry
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
id: meta-ghcr
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Login to Dockerhub
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
username: girlbossceo
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to Dockerhub
env:
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
DOCKER_USERNAME: ${{ vars.DOCKER_USERNAME }}
if: ${{ (github.event_name != 'pull_request') && (env.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
uses: docker/login-action@v3
with:
# username is not really a secret
username: ${{ vars.DOCKER_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
env:
REGISTRY: ghcr.io
with:
registry: ${{ env.REGISTRY }}
username: girlbossceo
password: ${{ secrets.GITHUB_TOKEN }}
- name: Login to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
env:
REGISTRY: ghcr.io
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Publish to Dockerhub
if: github.event_name != 'pull_request'
env:
IMAGE_NAME: docker.io/${{ github.repository }}
IMAGE_SUFFIX_AMD64: amd64
IMAGE_SUFFIX_ARM64V8: arm64v8
run: |
docker load -i oci-image-amd64.tar.gz
IMAGE_ID_AMD64=$(docker images -q conduit:main)
docker load -i oci-image-arm64v8.tar.gz
IMAGE_ID_ARM64V8=$(docker images -q conduit:main)
- name: Publish to Dockerhub
env:
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
DOCKER_USERNAME: ${{ vars.DOCKER_USERNAME }}
IMAGE_NAME: docker.io/${{ github.repository }}
IMAGE_SUFFIX_AMD64: amd64
IMAGE_SUFFIX_ARM64V8: arm64v8
if: ${{ (github.event_name != 'pull_request') && (env.DOCKER_USERNAME != '') && (env.DOCKERHUB_TOKEN != '') }}
run: |
docker load -i oci-image-amd64.tar.gz
IMAGE_ID_AMD64=$(docker images -q conduit:main)
docker load -i oci-image-arm64v8.tar.gz
IMAGE_ID_ARM64V8=$(docker images -q conduit:main)
# Tag and push the architecture specific images
docker tag $IMAGE_ID_AMD64 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker tag $IMAGE_ID_ARM64V8 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
# Tag the multi-arch image
docker manifest create $IMAGE_NAME:$GITHUB_SHA --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_SHA
# Tag and push the git ref
docker manifest create $IMAGE_NAME:$GITHUB_REF_NAME --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_REF_NAME
# Tag git tags as 'latest'
if [[ -n "$GITHUB_REF_NAME" ]]; then
docker manifest create $IMAGE_NAME:latest --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:latest
fi
# Tag and push the architecture specific images
docker tag $IMAGE_ID_AMD64 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker tag $IMAGE_ID_ARM64V8 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
# Tag the multi-arch image
docker manifest create $IMAGE_NAME:$GITHUB_SHA --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_SHA
# Tag and push the git ref
docker manifest create $IMAGE_NAME:$GITHUB_REF_NAME --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_REF_NAME
# Tag "main" as latest (stable branch)
if [[ "$GITHUB_REF_NAME" = "main" ]]; then
docker manifest create $IMAGE_NAME:latest --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:latest
fi
- name: Publish to GitHub Container Registry
if: github.event_name != 'pull_request'
env:
IMAGE_NAME: ghcr.io/${{ github.repository }}
IMAGE_SUFFIX_AMD64: amd64
IMAGE_SUFFIX_ARM64V8: arm64v8
run: |
docker load -i oci-image-amd64.tar.gz
IMAGE_ID_AMD64=$(docker images -q conduit:main)
docker load -i oci-image-arm64v8.tar.gz
IMAGE_ID_ARM64V8=$(docker images -q conduit:main)
- name: Publish to GitHub Container Registry
if: github.event_name != 'pull_request'
env:
IMAGE_NAME: ghcr.io/${{ github.repository }}
IMAGE_SUFFIX_AMD64: amd64
IMAGE_SUFFIX_ARM64V8: arm64v8
run: |
docker load -i oci-image-amd64.tar.gz
IMAGE_ID_AMD64=$(docker images -q conduit:main)
docker load -i oci-image-arm64v8.tar.gz
IMAGE_ID_ARM64V8=$(docker images -q conduit:main)
# Tag and push the architecture specific images
docker tag $IMAGE_ID_AMD64 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker tag $IMAGE_ID_ARM64V8 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
# Tag the multi-arch image
docker manifest create $IMAGE_NAME:$GITHUB_SHA --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_SHA
# Tag and push the git ref
docker manifest create $IMAGE_NAME:$GITHUB_REF_NAME --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_REF_NAME
# Tag git tags as 'latest'
if [[ -n "$GITHUB_REF_NAME" ]]; then
docker manifest create $IMAGE_NAME:latest --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:latest
fi
# Tag and push the architecture specific images
docker tag $IMAGE_ID_AMD64 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker tag $IMAGE_ID_ARM64V8 $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64
docker push $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
# Tag the multi-arch image
docker manifest create $IMAGE_NAME:$GITHUB_SHA --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_SHA
# Tag and push the git ref
docker manifest create $IMAGE_NAME:$GITHUB_REF_NAME --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:$GITHUB_REF_NAME
# Tag "main" as latest (stable branch)
if [[ "$GITHUB_REF_NAME" = "main" ]]; then
docker manifest create $IMAGE_NAME:latest --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_AMD64 --amend $IMAGE_NAME:$GITHUB_SHA-$IMAGE_SUFFIX_ARM64V8
docker manifest push $IMAGE_NAME:latest
fi
+117
View File
@@ -0,0 +1,117 @@
name: Documentation and GitHub Pages
on:
pull_request:
push:
branches:
- main
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
env:
# Required to make some things output color
TERM: ansi
# Publishing to my nix binary cache
ATTIC_TOKEN: ${{ secrets.ATTIC_TOKEN }}
# Custom nix binary cache if fork is being used
ATTIC_ENDPOINT: ${{ vars.ATTIC_ENDPOINT }}
ATTIC_PUBLIC_KEY: ${{ vars.ATTIC_PUBLIC_KEY }}
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
docs:
name: Documentation and GitHub Pages
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Sync repository
uses: actions/checkout@v4
- name: Setup GitHub Pages
if: github.event_name != 'pull_request'
uses: actions/configure-pages@v5
- name: Install Nix (with flakes and nix-command enabled)
uses: cachix/install-nix-action@v26
with:
nix_path: nixpkgs=channel:nixos-unstable
# Add `nix-community`, Crane, upstream Conduit, and conduwuit binary caches
extra_nix_config: |
experimental-features = nix-command flakes
extra-substituters = https://nix-community.cachix.org
extra-trusted-public-keys = nix-community.cachix.org-1:mB9FSh9qf2dCimDSUo8Zy7bkq5CX+/rkCWyvRCYg3Fs=
extra-substituters = https://crane.cachix.org
extra-trusted-public-keys = crane.cachix.org-1:8Scfpmn9w+hGdXH/Q9tTLiYAE/2dnJYRJP7kl80GuRk=
extra-substituters = https://nix.computer.surgery/conduit
extra-trusted-public-keys = conduit:ZGAf6P6LhNvnoJJ3Me3PRg7tlLSrPxcQ2RiE5LIppjo=
extra-substituters = https://attic.kennel.juneis.dog/conduit
extra-trusted-public-keys = conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
extra-substituters = https://attic.kennel.juneis.dog/conduwuit
extra-trusted-public-keys = conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
- name: Add alternative Nix binary caches if specified
if: ${{ (env.ATTIC_ENDPOINT != '') && (env.ATTIC_PUBLIC_KEY != '') }}
run: |
echo "extra-substituters = ${{ env.ATTIC_ENDPOINT }}" >> /etc/nix/nix.conf
echo "extra-trusted-public-keys = ${{ env.ATTIC_PUBLIC_KEY }}" >> /etc/nix/nix.conf
- name: Pop/push Magic Nix Cache
uses: DeterminateSystems/magic-nix-cache-action@main
- name: Configure `nix-direnv`
run: |
echo 'source $HOME/.nix-profile/share/nix-direnv/direnvrc' > "$HOME/.direnvrc"
- name: Install `direnv` and `nix-direnv`
run: nix-env -f "<nixpkgs>" -iA direnv -iA nix-direnv
# Do this to shorten the logs for the real CI step
- name: Populate `/nix/store`
run: nix develop --command true
- name: Allow direnv
run: direnv allow
- name: Cache x86_64 inputs for devShell
run: |
./bin/nix-build-and-cache .#devShells.x86_64-linux.default.inputDerivation
- name: Build documentation (book)
run: |
./bin/nix-build-and-cache .#book
cp -r --dereference result public
- name: Upload generated documentation (book) as normal artifact
uses: actions/upload-artifact@v4
with:
name: public
path: public
if-no-files-found: error
# don't compress again
compression-level: 0
- name: Upload generated documentation (book) as GitHub Pages artifact
if: github.event_name != 'pull_request'
uses: actions/upload-pages-artifact@v3
with:
path: public
- name: Deploy to GitHub Pages
if: github.event_name != 'pull_request'
id: deployment
uses: actions/deploy-pages@v4
+2 -2
View File
@@ -24,7 +24,7 @@ jobs:
uses: actions/checkout@v4
- name: Run Trivy code and vulnerability scanner on repo
uses: aquasecurity/trivy-action@0.18.0
uses: aquasecurity/trivy-action@0.19.0
with:
scan-type: repo
format: sarif
@@ -32,7 +32,7 @@ jobs:
severity: CRITICAL,HIGH,MEDIUM,LOW
- name: Run Trivy code and vulnerability scanner on filesystem
uses: aquasecurity/trivy-action@0.18.0
uses: aquasecurity/trivy-action@0.19.0
with:
scan-type: fs
format: sarif
+6
View File
@@ -75,5 +75,11 @@ test-conduit.toml
# Gitlab CI cache
/.gitlab-ci.d
# mdbook output
public/
# macOS
.DS_Store
# Zed
.zed/
+22 -5
View File
@@ -30,7 +30,7 @@ before_script:
# Add upstream Conduit binary cache
- if command -v nix > /dev/null; then echo "extra-substituters = https://nix.computer.surgery/conduit" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null; then echo "extra-trusted-public-keys = conduit:ZGAf6P6LhNvnoJJ3Me3PRg7tlLSrPxcQ2RiE5LIppjo=" >> /etc/nix/nix.conf; fi
# Add alternate binary cache
- if command -v nix > /dev/null && [ -n "$ATTIC_ENDPOINT" ]; then echo "extra-substituters = $ATTIC_ENDPOINT" >> /etc/nix/nix.conf; fi
- if command -v nix > /dev/null && [ -n "$ATTIC_PUBLIC_KEY" ]; then echo "extra-trusted-public-keys = $ATTIC_PUBLIC_KEY" >> /etc/nix/nix.conf; fi
@@ -54,7 +54,7 @@ before_script:
ci:
stage: ci
image: nixos/nix:2.21.0
image: nixos/nix:2.21.2
script:
# Cache the inputs required for the devShell
- ./bin/nix-build-and-cache .#devShells.x86_64-linux.default.inputDerivation
@@ -79,7 +79,7 @@ ci:
artifacts:
stage: artifacts
image: nixos/nix:2.21.0
image: nixos/nix:2.21.2
script:
- ./bin/nix-build-and-cache .#static-x86_64-unknown-linux-musl
- cp result/bin/conduit x86_64-unknown-linux-musl
@@ -105,6 +105,10 @@ artifacts:
- ./bin/nix-build-and-cache .#oci-image-aarch64-unknown-linux-musl
- cp result oci-image-arm64v8.tar.gz
- ./bin/nix-build-and-cache .#book
# We can't just copy the symlink, we need to dereference it https://gitlab.com/gitlab-org/gitlab/-/issues/19746
- cp -r --dereference result public
artifacts:
paths:
- x86_64-unknown-linux-musl
@@ -112,6 +116,7 @@ artifacts:
- x86_64-unknown-linux-musl.deb
- oci-image-amd64.tar.gz
- oci-image-arm64v8.tar.gz
- public
rules:
# CI required for all MRs
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
@@ -124,9 +129,9 @@ artifacts:
.push-oci-image:
stage: publish
image: docker:25.0.4
image: docker:26.0.1
services:
- docker:25.0.4-dind
- docker:26.0.1-dind
variables:
IMAGE_SUFFIX_AMD64: amd64
IMAGE_SUFFIX_ARM64V8: arm64v8
@@ -164,3 +169,15 @@ oci-image:push-gitlab:
IMAGE_NAME: $CI_REGISTRY_IMAGE/conduwuit
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
pages:
stage: publish
dependencies:
- artifacts
only:
- next
script:
- "true"
artifacts:
paths:
- public
+3
View File
@@ -0,0 +1,3 @@
# Docs: Map markdown to html files
- source: /docs/(.+)\.md/
public: '\1.html'
+2 -1
View File
@@ -1,10 +1,11 @@
{
"recommendations": [
"rust-lang.rust-analyzer",
"editorconfig.editorconfig",
"ms-azuretools.vscode-docker",
"eamodio.gitlens",
"serayuzgur.crates",
"vadimcn.vscode-lldb",
"timonwong.shellcheck"
]
}
}
+4 -4
View File
@@ -23,11 +23,11 @@
"args": [],
"env": {
"RUST_BACKTRACE": "1",
"CONDUIT_CONFIG": "",
"CONDUIT_SERVER_NAME": "localhost",
"CONDUIT_DATABASE_PATH": "/tmp",
"CONDUIT_DATABASE_PATH": "/tmp/awawawa",
"CONDUIT_ADDRESS": "0.0.0.0",
"CONDUIT_PORT": "6167"
"CONDUIT_PORT": "55551",
"CONDUIT_SERVER_NAME": "your.server.name",
"CONDUIT_LOG": "debug"
},
"cwd": "${workspaceFolder}"
}
Generated
+824 -289
View File
File diff suppressed because it is too large Load Diff
+219 -129
View File
@@ -2,11 +2,14 @@
name = "conduit"
description = "a cool fork of Conduit, a Matrix homeserver written in Rust"
license = "Apache-2.0"
authors = ["strawberry <strawberry@puppygock.gay>", "timokoesters <timo@koesters.xyz>"]
authors = [
"strawberry <strawberry@puppygock.gay>",
"timokoesters <timo@koesters.xyz>",
]
homepage = "https://puppygock.gay/conduwuit"
repository = "https://gitlab.com/girlbossceo/conduwuit"
repository = "https://github.com/girlbossceo/conduwuit"
readme = "README.md"
version = "0.7.0-alpha+conduwuit-0.1.8"
version = "0.7.0+conduwuit-0.2.0"
edition = "2021"
# See also `rust-toolchain.toml`
@@ -26,29 +29,28 @@ base64 = "0.22.0"
# Used when hashing the state
ring = "0.17.8"
# Used when querying the SRV record of other servers
trust-dns-resolver = "0.23.2"
# Used to find matching events for appservices
regex = "1.10.3"
regex = "1.10.4"
# Used to load forbidden room/user regex from config
serde_regex = "1.1.0"
# Used to make working with iterators easier, was already a transitive depdendency
itertools = "0.12.1"
# jwt jsonwebtokens
jsonwebtoken = "9.2.0"
jsonwebtoken = "9.3.0"
lru-cache = "0.1.2"
# Used for ruma wrapper
serde_html_form = "0.2.5"
serde_html_form = "0.2.6"
# used for TURN server authentication
hmac = "0.12.1"
sha-1 = "0.10.1"
async-trait = "0.1.78"
async-trait = "0.1.80"
# used for checking if an IP is in specific subnets / CIDR ranges easier
ipaddress = "0.1.3"
@@ -64,15 +66,26 @@ cyborgtime = "2.1.1"
# all the web/HTTP dependencies
# Used for the http request / response body type for Ruma endpoints used with reqwest
bytes = "1.5.0"
bytes = "1.6.0"
http = "0.2.12"
# used to replace the channels of the tokio runtime
loole = "0.3.0"
# Validating urls in config, was already a transitive dependency
url = { version = "2", features = ["serde"] }
# standard date and time tools
[dependencies.chrono]
version = "0.4.38"
features = ["alloc"]
default-features = false
# Web framework
[dependencies.axum]
version = "0.6.20"
default-features = false
features = ["form", "headers", "http1", "http2", "json", "matched-path"]
optional = true
[dependencies.axum-server]
version = "0.5.1"
@@ -84,30 +97,18 @@ features = ["util"]
[dependencies.tower-http]
version = "0.4.4"
features = [
"add-extension",
"cors",
"sensitive-headers",
"trace",
"util",
]
features = ["add-extension", "cors", "sensitive-headers", "trace", "util"]
[dependencies.hyper]
version = "0.14"
features = [
"server",
"http1",
"http2",
]
features = ["server", "http1", "http2"]
[dependencies.reqwest]
version = "0.11.26"
#version = "0.11.27"
git = "https://github.com/girlbossceo/reqwest"
rev = "319335e000fdea2e3d01f44245c8a21864d0c1c3"
default-features = false
features = [
"rustls-tls-native-roots",
"socks",
"trust-dns",
]
features = ["rustls-tls-native-roots", "socks", "hickory-dns"]
# all the serde stuff
# Used for pdu definition
@@ -116,37 +117,34 @@ version = "1.0.197"
features = ["rc"]
# Used for appservice registration files
[dependencies.serde_yaml]
version = "0.9.32"
version = "0.9.34"
# Used for ruma wrapper
[dependencies.serde_json]
version = "1.0.114"
version = "1.0.116"
features = ["raw_value"]
# Used for password hashing
[dependencies.argon2]
version = "0.5.3"
features = [
"alloc",
"rand",
]
features = ["alloc", "rand"]
default-features = false
# Used to generate thumbnails for images
[dependencies.image]
version = "0.25.0"
version = "0.25.1"
default-features = false
features = [
"jpeg",
"png",
"gif",
"webp",
]
features = ["jpeg", "png", "gif", "webp"]
# logging
[dependencies.log]
version = "0.4.21"
default-features = false
features = ["max_level_trace", "release_max_level_info"]
[dependencies.tracing]
version = "0.1.40"
default-features = false
features = ["max_level_trace", "release_max_level_info"]
[dependencies.tracing-subscriber]
version = "0.3.18"
features = ["env-filter"]
@@ -175,6 +173,30 @@ version = "0.20.0"
optional = true
features = ["rt-tokio"]
# optional sentry metrics for crash/panic reporting
[dependencies.sentry]
version = "0.32.3"
optional = true
default-features = false
features = [
"backtrace",
"contexts",
"debug-images",
"panic",
"rustls",
"tower",
"tower-http",
"tracing",
"reqwest",
"log",
]
[dependencies.sentry-tracing]
version = "0.32.3"
optional = true
[dependencies.sentry-tower]
version = "0.32.3"
optional = true
# optional jemalloc usage
[dependencies.tikv-jemallocator]
version = "0.5.4"
@@ -194,7 +216,7 @@ default-features = false
# to support multiple variations of setting a config option
[dependencies.either]
version = "1.10.0"
version = "1.11.0"
features = ["serde"]
# to listen on both HTTP and HTTPS if listening on TLS dierctly from conduwuit for complement or sytest
@@ -204,15 +226,9 @@ optional = true
# used for conduit's CLI and admin room command parsing
[dependencies.clap]
version = "4.5.3"
version = "4.5.4"
default-features = false
features = [
"std",
"derive",
"help",
"usage",
"error-context",
]
features = ["std", "derive", "help", "usage", "error-context", "string"]
[dependencies.futures-util]
version = "0.3.30"
@@ -220,11 +236,8 @@ default-features = false
# Used for reading the configuration from conduit.toml & environment variables
[dependencies.figment]
version = "0.10.15"
features = [
"env",
"toml",
]
version = "0.10.17"
features = ["env", "toml"]
# Used for matrix spec type definitions and helpers
#ruma = { version = "0.4.0", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
@@ -232,41 +245,48 @@ features = [
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-msc3575", "unstable-exhaustive-types", "ring-compat", "unstable-unspecified" ] }
[dependencies.ruma]
git = "https://github.com/girlbossceo/ruma"
#rev = "c988b5ff158ede9c10aeffc76ad5e31604f19ddb"
branch = "conduwuit-changes"
#path = "../ruma/crates/ruma"
features = [
"compat",
"rand",
"appservice-api-c",
"client-api",
"federation-api",
"push-gateway-api-c",
"state-res",
"unstable-msc2448",
"unstable-msc3575",
"unstable-exhaustive-types",
"ring-compat",
"unstable-unspecified",
"unstable-msc2870",
"unstable-msc3061",
"unstable-msc2867",
"unstable-extensible-events",
"compat",
"rand",
"appservice-api-c",
"client-api",
"federation-api",
"push-gateway-api-c",
"state-res",
"unstable-exhaustive-types",
"ring-compat",
"unstable-unspecified",
"unstable-msc2448",
"unstable-msc2666",
"unstable-msc2867",
"unstable-msc2870",
"unstable-msc3026",
"unstable-msc3061",
"unstable-msc3575",
"unstable-msc4121",
"unstable-msc4125",
"unstable-extensible-events",
]
[dependencies.hickory-resolver]
git = "https://github.com/hickory-dns/hickory-dns"
rev = "94ac564c3f677e038f7255ddb762e9301d0f2c5d"
[dependencies.rust-rocksdb]
git = "https://github.com/zaidoon1/rust-rocksdb"
#branch = "master"
rev = "3e4a0f632a8c0c2839c7d183725c53895110d907"
branch = "master"
#rev = "60f783b06b49d2f6fcf1d3dda66c7194e49095d4"
optional = true
default-features = true
features = [
"multi-threaded-cf",
"zstd",
]
features = ["multi-threaded-cf", "zstd"]
[dependencies.rusqlite]
git = "https://github.com/rusqlite/rusqlite"
branch = "master"
#rev = "def8e9460d8376a5c0c9f4f9846d413a9cd4581a"
#branch = "master"
rev = "e00b626e2b1c67347d789fb7f600281705c89381"
optional = true
features = ["bundled"]
@@ -286,49 +306,71 @@ version = "1.16.0"
optional = true
[dependencies.tokio]
version = "1.36.0"
features = [
"fs",
"macros",
"sync",
"signal",
]
version = "1.37.0"
features = ["fs", "macros", "sync", "signal"]
# *nix-specific dependencies
[target.'cfg(unix)'.dependencies]
nix = { version = "0.28.0", features = ["resource"] }
sd-notify = { version = "0.4.1", optional = true } # systemd is only available/relevant on *nix platforms
hyperlocal = { git = "https://github.com/softprops/hyperlocal", rev = "2ee4d149644600d326559af0d2b235c945b05c04", features = ["server"] } # unix socket support
hyperlocal = { git = "https://github.com/softprops/hyperlocal", rev = "2ee4d149644600d326559af0d2b235c945b05c04", features = [
"server",
] } # unix socket support
[target.'cfg(all(not(target_env = "msvc"), not(target_os = "macos"), target_os = "linux"))'.dependencies]
hardened_malloc-rs = { version = "0.1", optional = true, features = [
"static",
"clang",
"light",
], default-features = false }
#hardened_malloc-rs = { optional = true, features = ["static","clang","light"], path = "../hardened_malloc-rs", default-features = false }
[features]
default = ["conduit_bin", "backend_rocksdb", "systemd"]
conduit_bin = ["axum"]
default = [
"backend_rocksdb",
"systemd",
"element_hacks",
"sentry_telemetry",
"gzip_compression",
"brotli_compression",
"zstd_compression",
]
backend_sqlite = ["sqlite"]
backend_rocksdb = ["rocksdb"]
rocksdb = ["rust-rocksdb", "num_cpus"]
jemalloc = ["tikv-jemalloc-ctl", "tikv-jemallocator"]
jemalloc = ["tikv-jemalloc-ctl", "tikv-jemallocator", "rust-rocksdb/jemalloc"]
sqlite = ["rusqlite", "parking_lot", "thread_local", "num_cpus"]
systemd = ["sd-notify"]
sentry_telemetry = ["sentry", "sentry-tracing", "sentry-tower"]
#gzip_compression = ["tower-http/compression-gzip"]
gzip_compression = ["tower-http/compression-gzip", "reqwest/gzip"]
zstd_compression = ["tower-http/compression-zstd"]
#brotli_compression = ["tower-http/compression-br"]
#all_compression = ["tower-http/compression-full"] # all compression algos
brotli_compression = ["tower-http/compression-br", "reqwest/brotli"]
sha256_media = ["sha2"]
io_uring = ["rust-rocksdb/io-uring"]
axum_dual_protocol = ["axum-server-dual-protocol"]
perf_measurements = ["opentelemetry", "tracing-flame", "tracing-opentelemetry", "opentelemetry_sdk", "opentelemetry-jaeger"]
perf_measurements = [
"opentelemetry",
"tracing-flame",
"tracing-opentelemetry",
"opentelemetry_sdk",
"opentelemetry-jaeger",
]
hardened_malloc = ["hardened_malloc-rs"]
# client/server interopability hacks
#
## element has various non-spec compliant behaviour
element_hacks = []
[[bin]]
name = "conduit"
path = "src/main.rs"
required-features = ["conduit_bin"]
[lib]
name = "conduit"
@@ -345,19 +387,32 @@ a cool fork of Conduit, a Matrix homeserver written in Rust"""
section = "net"
priority = "optional"
assets = [
["debian/README.md", "usr/share/doc/matrix-conduit/README.Debian", "644"],
["README.md", "usr/share/doc/matrix-conduit/", "644"],
["target/release/conduit", "usr/sbin/matrix-conduit", "755"],
["conduwuit-example.toml", "etc/matrix-conduit/conduit.toml", "640"],
]
conf-files = [
"/etc/matrix-conduit/conduit.toml"
[
"debian/README.md",
"usr/share/doc/matrix-conduit/README.Debian",
"644",
],
[
"README.md",
"usr/share/doc/matrix-conduit/",
"644",
],
[
"target/release/conduit",
"usr/sbin/matrix-conduit",
"755",
],
[
"conduwuit-example.toml",
"etc/matrix-conduit/conduit.toml",
"640",
],
]
conf-files = ["/etc/matrix-conduit/conduit.toml"]
maintainer-scripts = "debian/"
systemd-units = { unit-name = "matrix-conduit" }
[profile.dev]
debug = 0
lto = 'off'
@@ -378,7 +433,6 @@ incremental = false
opt-level = 3
overflow-checks = true
strip = "symbols"
panic = "abort"
control-flow-guard = true # Windows only
debug = 0
@@ -387,6 +441,7 @@ debug = 0
inherits = "release"
lto = 'fat'
codegen-units = 1
panic = "abort"
# For releases also try to max optimizations for dependencies:
[profile.release-high-perf.build-override]
@@ -400,17 +455,14 @@ opt-level = 3
codegen-units = 1
[lints]
workspace = true
[workspace.lints.rust]
missing_abi = "warn"
# missing_docs = "warn"
noop_method_call = "warn"
pointer_structural_match = "warn"
explicit_outlives_requirements = "warn"
# unreachable_pub = "warn"
unused_extern_crates = "warn"
unused_import_braces = "warn"
unused_lifetimes = "warn"
@@ -428,11 +480,16 @@ unit_bindings = "warn"
# this seems to suggest broken code and is not working correctly
unused_braces = "allow"
# some sadness
unreachable_pub = "allow"
missing_docs = "allow"
[workspace.lints.clippy]
# pedantic = "warn"
suspicious = "warn" # assume deny in practice
perf = "warn" # assume deny in practice
perf = "warn" # assume deny in practice
redundant_clone = "warn"
cloned_instead_of_copied = "warn"
@@ -445,51 +502,36 @@ char_lit_as_u8 = "warn"
dbg_macro = "warn"
empty_structs_with_brackets = "warn"
get_unwrap = "warn"
# if_then_some_else_none = "warn"
# let_underscore_must_use = "warn"
# map_err_ignore = "warn"
# missing_docs_in_private_items = "warn"
negative_feature_names = "warn"
pub_without_shorthand = "warn"
rc_buffer = "warn"
rc_mutex = "warn"
redundant_feature_names = "warn"
redundant_type_annotations = "warn"
# ref_patterns = "warn"
rest_pat_in_fully_bound_structs = "warn"
str_to_string = "warn"
# string_add = "warn"
# string_slice = "warn"
string_to_string = "warn"
tests_outside_test_module = "warn"
undocumented_unsafe_blocks = "warn"
unneeded_field_pattern = "warn"
unseparated_literal_suffix = "warn"
# unwrap_used = "warn"
# expect_used = "warn"
wildcard_dependencies = "warn"
or_fun_call = "warn"
unnecessary_lazy_evaluations = "warn"
# as_conversions = "warn"
assertions_on_result_states = "warn"
default_union_representation = "warn"
deref_by_slicing = "warn"
empty_drop = "warn"
# error_impl_error = "warn"
exit = "warn"
filetype_is_file = "warn"
float_cmp_const = "warn"
format_push_string = "warn"
impl_trait_in_params = "warn"
ref_to_mut = "warn"
# let_underscore_untyped = "warn"
lossy_float_literal = "warn"
mem_forget = "warn"
missing_assert_message = "warn"
# mod_module_files = "warn"
# multiple_inherent_impl = "warn"
mutex_atomic = "warn"
# same_name_method = "warn"
semicolon_outside_block = "warn"
fn_to_numeric_cast = "warn"
fn_to_numeric_cast_with_truncation = "warn"
@@ -500,11 +542,59 @@ unnecessary_safety_comment = "warn"
unnecessary_safety_doc = "warn"
unnecessary_self_imports = "warn"
verbose_file_reads = "warn"
# cast_precision_loss = "warn"
cast_possible_wrap = "warn"
# cast_possible_truncation = "warn"
redundant_closure_for_method_calls = "warn"
large_futures = "warn"
semicolon_if_nothing_returned = "warn"
match_bool = "warn"
struct_excessive_bools = "warn"
must_use_candidate = "warn"
collapsible_else_if = "warn"
inconsistent_struct_constructor = "warn"
manual_string_new = "warn"
zero_sized_map_values = "warn"
unnecessary_box_returns = "warn"
map_unwrap_or = "warn"
implicit_clone = "warn"
match_wildcard_for_single_variants = "warn"
unnecessary_wraps = "warn"
match_same_arms = "warn"
ignored_unit_patterns = "warn"
redundant_else = "warn"
explicit_into_iter_loop = "warn"
used_underscore_binding = "warn"
needless_pass_by_value = "warn"
too_many_lines = "warn"
let_underscore_untyped = "warn"
single_match = "warn"
single_match_else = "warn"
explicit_deref_methods = "warn"
explicit_iter_loop = "warn"
manual_let_else = "warn"
trivially_copy_pass_by_ref = "warn"
wildcard_imports = "warn"
checked_conversions = "warn"
# not in rust 1.75.0 (breaks CI)
# infinite_loop = "warn"
# some sadness
missing_errors_doc = "allow"
missing_panics_doc = "allow"
module_name_repetitions = "allow"
if_not_else = "allow"
doc_markdown = "allow"
cast_possible_truncation = "allow"
cast_precision_loss = "allow"
cast_sign_loss = "allow"
same_name_method = "allow"
mod_module_files = "allow"
unwrap_used = "allow"
expect_used = "allow"
if_then_some_else_none = "allow"
let_underscore_must_use = "allow"
map_err_ignore = "allow"
missing_docs_in_private_items = "allow"
multiple_inherent_impl = "allow"
error_impl_error = "allow"
as_conversions = "allow"
string_add = "allow"
string_slice = "allow"
ref_patterns = "allow"
-307
View File
@@ -1,307 +0,0 @@
# Deploying Conduit
### Please note that this documentation is not fully representative of conduwuit at the moment. Assume majority of it is outdated.
> ## Getting help
>
> If you run into any problems while setting up conduwuit, ask us
> in `#conduwuit:puppygock.gay` or [open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new).
## Installing conduwuit
You may simply download the binary that fits your machine. Run `uname -m` to see what you need.
Prebuilt binaries can be downloaded from the latest successful CI workflow on the main branch here: https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml?query=branch%3Amain+actor%3Agirlbossceo
```bash
$ sudo wget -O /usr/local/bin/matrix-conduit <url>
$ sudo chmod +x /usr/local/bin/matrix-conduit
```
Alternatively, you may compile the binary yourself. First, install any dependencies:
```bash
# Debian
$ sudo apt install libclang-dev build-essential
# RHEL
$ sudo dnf install clang
```
Then, `cd` into the source tree of conduit-next and run:
```bash
$ cargo build --release
```
If you want to cross compile Conduit to another architecture, read the guide below.
<details>
<summary>Cross compilation</summary>
As easiest way to compile conduit for another platform [cross-rs](https://github.com/cross-rs/cross) is recommended, so install it first.
In order to use RockDB as storage backend append `-latomic` to linker flags.
For example, to build a binary for Raspberry Pi Zero W (ARMv6) you need `arm-unknown-linux-gnueabihf` as compilation
target.
```bash
git clone https://gitlab.com/famedly/conduit.git
cd conduit
export RUSTFLAGS='-C link-arg=-lgcc -Clink-arg=-latomic -Clink-arg=-static-libgcc'
cross build --release --no-default-features --features conduit_bin,backend_rocksdb --target=arm-unknown-linux-gnueabihf
```
</details>
## Adding a Conduit user
While Conduit can run as any user it is usually better to use dedicated users for different services. This also allows
you to make sure that the file permissions are correctly set up.
In Debian or RHEL, you can use this command to create a Conduit user:
```bash
sudo adduser --system conduit --group --disabled-login --no-create-home
```
## Forwarding ports in the firewall or the router
Conduit uses the ports 443 and 8448 both of which need to be open in the firewall.
If Conduit runs behind a router or in a container and has a different public IP address than the host system these public ports need to be forwarded directly or indirectly to the port mentioned in the config.
## Optional: Avoid port 8448
If Conduit runs behind Cloudflare reverse proxy, which doesn't support port 8448 on free plans, [delegation](https://matrix-org.github.io/synapse/latest/delegate.html) can be set up to have federation traffic routed to port 443:
```apache
# .well-known delegation on Apache
<Files "/.well-known/matrix/server">
ErrorDocument 200 '{"m.server": "your.server.name:443"}'
Header always set Content-Type application/json
Header always set Access-Control-Allow-Origin *
</Files>
```
[SRV DNS record](https://spec.matrix.org/latest/server-server-api/#resolving-server-names) delegation is also [possible](https://www.cloudflare.com/en-gb/learning/dns/dns-records/dns-srv-record/).
## Setting up a systemd service
Now we'll set up a systemd service for Conduit, so it's easy to start/stop Conduit and set it to autostart when your
server reboots. Simply paste the default systemd service you can find below into
`/etc/systemd/system/conduit.service`.
```systemd
[Unit]
Description=Conduit Matrix Server
After=network.target
[Service]
Environment="CONDUIT_CONFIG=/etc/matrix-conduit/conduit.toml"
User=conduit
Group=conduit
RuntimeDirectory=conduit
RuntimeDirectoryMode=0750
Restart=always
ExecStart=/usr/local/bin/matrix-conduit
[Install]
WantedBy=multi-user.target
```
Finally, run
```bash
$ sudo systemctl daemon-reload
```
## Creating the Conduit configuration file
Now we need to create the Conduit's config file in `/etc/conduwuit/conduwuit.toml`. Paste this in **and take a moment
to read it. You need to change at least the server name.**
You can also choose to use a different database backend, but right now only `rocksdb` and `sqlite` are recommended.
See the following example config at [conduwuit-example.toml](conduwuit-example.toml)
## Setting the correct file permissions
As we are using a Conduit specific user we need to allow it to read the config. To do that you can run this command on
Debian or RHEL:
```bash
sudo chown -R root:root /etc/matrix-conduit
sudo chmod 755 /etc/matrix-conduit
```
If you use the default database path you also need to run this:
```bash
sudo mkdir -p /var/lib/matrix-conduit/
sudo chown -R conduit:conduit /var/lib/matrix-conduit/
sudo chmod 700 /var/lib/matrix-conduit/
```
## Setting up the Reverse Proxy
This depends on whether you use Apache, Caddy, Nginx or another web server.
### Apache
Create `/etc/apache2/sites-enabled/050-conduit.conf` and copy-and-paste this:
```apache
# Requires mod_proxy and mod_proxy_http
#
# On Apache instance compiled from source,
# paste into httpd-ssl.conf or httpd.conf
Listen 8448
<VirtualHost *:443 *:8448>
ServerName your.server.name # EDIT THIS
AllowEncodedSlashes NoDecode
# TCP
ProxyPass /_matrix/ http://127.0.0.1:6167/_matrix/ timeout=300 nocanon
ProxyPassReverse /_matrix/ http://127.0.0.1:6167/_matrix/
# UNIX socket
#ProxyPass /_matrix/ unix:/run/conduit/conduit.sock|http://127.0.0.1:6167/_matrix/ nocanon
#ProxyPassReverse /_matrix/ unix:/run/conduit/conduit.sock|http://127.0.0.1:6167/_matrix/
</VirtualHost>
```
**You need to make some edits again.** When you are done, run
```bash
# Debian
$ sudo systemctl reload apache2
# Installed from source
$ sudo apachectl -k graceful
```
### Caddy
Create `/etc/caddy/conf.d/conduit_caddyfile` and enter this (substitute for your server name).
```caddy
your.server.name, your.server.name:8448 {
# TCP
reverse_proxy /_matrix/* 127.0.0.1:6167
# UNIX socket
#reverse_proxy /_matrix/* unix//run/conduit/conduit.sock
}
```
That's it! Just start or enable the service and you're set.
```bash
$ sudo systemctl enable caddy
```
### Nginx
If you use Nginx and not Apache, add the following server section inside the http section of `/etc/nginx/nginx.conf`
```nginx
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
listen 8448 ssl http2;
listen [::]:8448 ssl http2;
server_name your.server.name; # EDIT THIS
merge_slashes off;
# Nginx defaults to only allow 1MB uploads
# Increase this to allow posting large files such as videos
client_max_body_size 20M;
# UNIX socket
#upstream backend {
# server unix:/run/conduit/conduit.sock;
#}
location /_matrix/ {
# TCP
proxy_pass http://127.0.0.1:6167;
# UNIX socket
#proxy_pass http://backend;
proxy_set_header Host $http_host;
proxy_buffering off;
proxy_read_timeout 5m;
}
ssl_certificate /etc/letsencrypt/live/your.server.name/fullchain.pem; # EDIT THIS
ssl_certificate_key /etc/letsencrypt/live/your.server.name/privkey.pem; # EDIT THIS
ssl_trusted_certificate /etc/letsencrypt/live/your.server.name/chain.pem; # EDIT THIS
include /etc/letsencrypt/options-ssl-nginx.conf;
}
```
**You need to make some edits again.** When you are done, run
```bash
$ sudo systemctl reload nginx
```
## SSL Certificate
If you chose Caddy as your web proxy SSL certificates are handled automatically and you can skip this step.
The easiest way to get an SSL certificate, if you don't have one already, is to [install](https://certbot.eff.org/instructions) `certbot` and run this:
```bash
# To use ECC for the private key,
# paste into /etc/letsencrypt/cli.ini:
# key-type = ecdsa
# elliptic-curve = secp384r1
$ sudo certbot -d your.server.name
```
[Automated renewal](https://eff-certbot.readthedocs.io/en/stable/using.html#automated-renewals) is usually preconfigured.
If using Cloudflare, configure instead the edge and origin certificates in dashboard. In case youre already running a website on the same Apache server, you can just copy-and-paste the SSL configuration from your main virtual host on port 443 into the above-mentioned vhost.
## You're done!
Now you can start Conduit with:
```bash
$ sudo systemctl start conduit
```
Set it to start automatically when your system boots with:
```bash
$ sudo systemctl enable conduit
```
## How do I know it works?
You can open <https://app.element.io>, enter your homeserver and try to register.
You can also use these commands as a quick health check.
```bash
$ curl https://your.server.name/_matrix/client/versions
# If using port 8448
$ curl https://your.server.name:8448/_matrix/client/versions
```
- To check if your server can talk with other homeservers, you can use the [Matrix Federation Tester](https://federationtester.matrix.org/).
If you can register but cannot join federated rooms check your config again and also check if the port 8448 is open and forwarded correctly.
# What's next?
## Audio/Video calls
For Audio/Video call functionality see the [TURN Guide](TURN.md).
## Appservices
If you want to set up an appservice, take a look at the [Appservice Guide](APPSERVICES.md).
+21 -27
View File
@@ -1,9 +1,17 @@
# conduwuit
### a well maintained fork of [Conduit](https://conduit.rs/)
[![CI and Artifacts](https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml)
<!-- ANCHOR: catchphrase -->
### a well maintained fork of [Conduit](https://conduit.rs/)
<!-- ANCHOR_END: catchphrase -->
Visit the [Conduwuit documentation](https://conduwuit.puppyirl.gay/) for more information.
Alternatively you can open [docs/introduction.md](docs/introduction.md) in this repository.
<!-- ANCHOR: body -->
#### What is Matrix?
[Matrix](https://matrix.org) is an open network for secure and decentralized
communication. Users from every Matrix homeserver can chat with users from all
other Matrix servers. You can even use bridges (also called Matrix Appservices)
@@ -25,14 +33,6 @@ conduwuit is a fork of Conduit which is in beta, meaning you can join and partic
Matrix rooms, but not all features are supported and you might run into bugs
from time to time.
There are still a few nice to have features missing that some users may notice:
- Outgoing read receipts and typing indicators (receiving works)
#### What's different about your fork than upstream Conduit?
See [DIFFERENCES.md](DIFFERENCES.md)
#### Why does this fork exist? Why don't you contribute back upstream?
I now intend on contributing back as time and mental energy sees fit, but my fork still exists as a way to:
@@ -45,16 +45,9 @@ I now intend on contributing back as time and mental energy sees fit, but my for
- Have a **stable** testing ground for some MRs or new features and bug fixes
And various other reasons that may not be listed here.
<!-- ANCHOR_END: body -->
#### How can I deploy my own?
conduwuit officially supports Linux, macOS, BSD, and Windows.
- Simple install (this was tested the most): [DEPLOY.md](DEPLOY.md)
- Nix/NixOS (and binary cache): [nix/README.md](nix/README.md)
If you want to connect an Appservice to Conduit, take a look at [APPSERVICES.md](APPSERVICES.md).
<!-- ANCHOR: footer -->
#### How can I contribute?
1. Look for an issue you would like to work on and make sure it's not assigned
@@ -72,13 +65,13 @@ If you run into any question, feel free to
#### Donate
Liberapay: <https://liberapay.com/girlbossceo>\
Ko-fi: <https://ko-fi.com/puppygock>\
GitHub Sponsors: <https://github.com/sponsors/girlbossceo>
- Liberapay: <https://liberapay.com/girlbossceo>
- Ko-fi: <https://ko-fi.com/puppygock>
- GitHub Sponsors: <https://github.com/sponsors/girlbossceo>
#### Logo
No official conduwuit logo exists. Repo and Matrix room picture is from bran (<3).
No official conduwuit logo exists. Repo and Matrix room picture is from bran (<3). Banner image is directly from [this cohost post](https://cohost.org/RatBaby/post/1028290-finally-a-flag-for).
#### Is it conduwuit or Conduwuit?
@@ -86,8 +79,9 @@ Both.
#### Mirrors of conduwuit
GitHub: <https://github.com/girlbossceo/conduwuit>\
GitLab: <https://gitlab.com/girlbossceo/conduwuit>\
git.gay: <https://git.gay/june/conduwuit>\
Codeberg: <https://codeberg.org/girlbossceo/conduwuit>\
sourcehut: <https://git.sr.ht/~girlbossceo/conduwuit>
- GitHub: <https://github.com/girlbossceo/conduwuit>
- GitLab: <https://gitlab.com/girlbossceo/conduwuit>
- git.gay: <https://git.gay/june/conduwuit>
- Codeberg: <https://codeberg.org/girlbossceo/conduwuit>
- sourcehut: <https://git.sr.ht/~girlbossceo/conduwuit>
<!-- ANCHOR_END: footer -->
+2 -2
View File
@@ -17,7 +17,7 @@ env \
-C "$(git rev-parse --show-toplevel)" \
docker build \
--tag "$OCI_IMAGE" \
--file complement/Dockerfile \
--file tests/complement/Dockerfile \
.
# It's okay (likely, even) that `go test` exits nonzero
@@ -25,7 +25,7 @@ set +o pipefail
env \
-C "$COMPLEMENT_SRC" \
COMPLEMENT_BASE_IMAGE="$OCI_IMAGE" \
go test -json ./tests | tee "$LOG_FILE"
go test -vet=all -timeout 30m -json ./tests | tee "$LOG_FILE"
set -o pipefail
# Post-process the results into an easy-to-compare format
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
set -euo pipefail
set -eo pipefail
# The first argument must be the desired installable
INSTALLABLE="$1"
+18
View File
@@ -0,0 +1,18 @@
[book]
title = "conduwuit"
description = "conduwuit, which is a fork of Conduit, is a simple, fast and reliable chat server for the Matrix protocol"
language = "en"
multilingual = false
src = "docs"
[build]
build-dir = "public"
create-missing = true
[output.html]
git-repository-url = "https://github.com/girlbossceo/conduwuit"
edit-url-template = "https://github.com/girlbossceo/conduwuit/edit/main/{path}"
git-repository-icon = "fa-github-square"
[output.html.search]
limit-results = 15
+1
View File
@@ -0,0 +1 @@
too-many-lines-threshold = 700
-12
View File
@@ -1,12 +0,0 @@
# Complement
## What's that?
Have a look at [its repository](https://github.com/matrix-org/complement).
## How do I use it with Conduit?
The script at [`../bin/complement`](../bin/complement) has automation for this.
It takes a few command line arguments, you can read the script to find out what
those are.
+287 -30
View File
@@ -2,6 +2,8 @@
# This is the official example config for conduwuit.
# If you use it for your server, you will need to adjust it to your own needs.
# At the very least, change the server_name field!
#
# This documentation can also be found at https://conduwuit.puppyirl.gay/configuration.html
# =============================================================================
[global]
@@ -32,6 +34,23 @@
# Defaults to `matrix.org`
# trusted_servers = ["matrix.org"]
# Sentry.io crash/panic reporting, performance monitoring/metrics, etc.
# Conduwuit's Sentry reporting endpoint is o4506996327251968.ingest.us.sentry.io
#
# Defaults to false
#sentry = false
# Report your Conduwuit server_name in Sentry.io crash reports and metrics
#
# Defaults to false
#sentry_send_server_name = false
# Performance monitoring/tracing sample rate for Sentry.io
#
# Note that too high values may impact performance, and can be disabled by setting it to 0.0
#
# Defaults to 0.15
#sentry_traces_sample_rate = 0.15
### Database configuration
@@ -45,7 +64,6 @@ database_path = "/var/lib/matrix-conduit/"
database_backend = "rocksdb"
### Network
# The port(s) conduwuit will be running on. You need to set up a reverse proxy such as
@@ -57,7 +75,7 @@ port = 6167
# default address (IPv4 or IPv6) conduwuit will listen on. Generally you want this to be
# localhost (127.0.0.1 / ::1). If you are using Docker or a container NAT networking setup, you
# likely need this to be 0.0.0.0.
# likely need this to be 0.0.0.0.
address = "127.0.0.1"
# How many requests conduwuit sends to other servers at the same time concurrently. Default is 500
@@ -86,11 +104,25 @@ max_request_size = 20_000_000 # in bytes
# Set this to true for conduwuit to compress HTTP response bodies using zstd.
# This option does nothing if conduwuit was not built with `zstd_compression` feature.
# Please be aware that enabling HTTP compression may weaken or even defeat TLS.
# Please be aware that enabling HTTP compression may weaken TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
zstd_compression = false
# Set this to true for conduwuit to compress HTTP response bodies using gzip.
# This option does nothing if conduwuit was not built with `gzip_compression` feature.
# Please be aware that enabling HTTP compression may weaken TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
gzip_compression = false
# Set this to true for conduwuit to compress HTTP response bodies using brotli.
# This option does nothing if conduwuit was not built with `brotli_compression` feature.
# Please be aware that enabling HTTP compression may weaken TLS.
# Most users should not need to enable this.
# See https://breachattack.com/ and https://wikipedia.org/wiki/BREACH before deciding to enable this.
brotli_compression = false
# Vector list of IPv4 and IPv6 CIDR ranges / subnets *in quotes* that you do not want conduwuit to send outbound requests to.
# Defaults to RFC1918, unroutable, loopback, multicast, and testnet addresses for security.
#
@@ -121,13 +153,20 @@ ip_range_denylist = [
]
### Moderation / Privacy / Security
# Set to true to allow user type "guest" registrations. Element attempts to register guest users automatically.
# For private homeservers, this is best at false.
# Defaults to false
allow_guest_registration = false
# Set to true to log guest registrations in the admin room.
# Defaults to false as it may be noisy or unnecessary.
log_guest_registrations = false
# Set to true to allow guest registrations/users to auto join any rooms specified in `auto_join_rooms`
# Defaults to false
allow_guests_auto_join_rooms = false
# Vector list of servers that conduwuit will refuse to download remote media from.
# No default.
# prevent_media_downloads_from = ["example.com", "example.local"]
@@ -173,7 +212,16 @@ registration_token = "change this token for something specific to your server"
# This is checked upon room alias creation, custom room ID creation if used, and startup as warnings if any room aliases
# in your database have a forbidden room alias/ID.
# No default.
# forbidden_room_names = []
# forbidden_alias_names = []
# List of forbidden server names that we will block all client room joins, incoming federated room directory requests, incoming federated invites for, and incoming federated joins. This check is applied on the room ID, room alias, sender server name, and sender user's server name.
# Basically "global" ACLs. For our user (client) checks, admin users are allowed.
# No default.
# forbidden_remote_server_names = []
# List of forbidden server names that we will block all outgoing federated room directory requests for. Useful for preventing our users from wandering into bad servers or spaces.
# No default.
# forbidden_remote_room_directory_server_names = []
# Set this to true to allow your server's public room directory to be federated.
# Set this to false to protect against /publicRooms spiders, but will forbid external users
@@ -185,6 +233,12 @@ allow_public_room_directory_over_federation = false
# authentication (access token) through the Client APIs. Set this to false to protect against /publicRooms spiders.
allow_public_room_directory_without_auth = false
# Set this to true to lock down your server's public room directory and only allow admins to publish rooms to the room directory.
# Unpublishing is still allowed by all users with this enabled.
#
# Defaults to false
lockdown_public_room_directory = false
# Set this to true to allow federating device display names / allow external users to see your device display name.
# If federation is disabled entirely (`allow_federation`), this is inherently false. For privacy, this is best disabled.
allow_device_name_federation = false
@@ -195,7 +249,7 @@ allow_device_name_federation = false
url_preview_domain_contains_allowlist = []
# Vector list of explicit domains allowed to send requests to for URL previews. Defaults to none.
# Note: This is an *explicit* match, not a ccontains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com"
# Note: This is an *explicit* match, not a contains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com"
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_domain_explicit_allowlist = []
@@ -204,20 +258,36 @@ url_preview_domain_explicit_allowlist = []
# Setting this to "*" will allow all URL previews. Please note that this opens up significant attack surface to your server, you are expected to be aware of the risks by doing so.
url_preview_url_contains_allowlist = []
# Maximum amount of bytes allowed in a URL preview body size when spidering. Defaults to 1MB (1_000_000 bytes)
url_preview_max_spider_size = 1_000_000
# Vector list of explicit domains not allowed to send requests to for URL previews. Defaults to none.
# Note: This is an *explicit* match, not a contains match. Putting "google.com" will match "https://google.com", "http://google.com", but not "https://mymaliciousdomainexamplegoogle.com"
# The denylist is checked first before allowlist. Setting this to "*" will not do anything.
url_preview_domain_explicit_denylist = []
# Maximum amount of bytes allowed in a URL preview body size when spidering. Defaults to 384KB (384_000 bytes)
url_preview_max_spider_size = 384_000
# Option to decide whether you would like to run the domain allowlist checks (contains and explicit) on the root domain or not. Does not apply to URL contains allowlist. Defaults to false.
# Example: If this is enabled and you have "wikipedia.org" allowed in the explicit and/or contains domain allowlist, it will allow all subdomains under "wikipedia.org" such as "en.m.wikipedia.org" as the root domain is checked and matched.
# Useful if the domain contains allowlist is still too broad for you but you still want to allow all the subdomains under a root domain.
url_preview_check_root_domain = false
# Config option to allow or disallow incoming federation requests that obtain the profiles
# of our local users from `/_matrix/federation/v1/query/profile`
#
# This is inherently false if `allow_federation` is disabled
#
# Defaults to true
allow_profile_lookup_federation_requests = true
### Misc
# max log level for conduwuit. allows debug, info, warn, or error
# see also: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
# **Caveat**:
# For release builds, the tracing crate is configured to only implement levels higher than error to avoid unnecessary overhead in the compiled binary from trace macros.
# For debug builds, this restriction is not applied.
#
# Defaults to "warn"
#log = "warn"
@@ -230,12 +300,6 @@ url_preview_check_root_domain = false
# Defaults to false.
#allow_check_for_updates = false
# If you are using delegation via well-known files and you cannot serve them from your reverse proxy, you can
# uncomment these to serve them directly from conduwuit. This requires proxying all requests to conduwuit, not just `/_matrix` to work.
#well_known_server = "matrix.example.com:443"
#well_known_client = "https://matrix.example.com"
# Note that whatever you put will show up in the well-known JSON values.
# Set to false to disable users from joining or creating room versions that aren't 100% officially supported by conduwuit.
# conduwuit officially supports room versions 6 - 10. conduwuit has experimental/unstable support for 3 - 5, and 11.
# Defaults to true.
@@ -263,6 +327,24 @@ url_preview_check_root_domain = false
# Defaults to true as this is the fastest option for federation.
#query_trusted_key_servers_first = true
# List/vector of room **IDs** that conduwuit will make newly registered users join.
# The room IDs specified must be rooms that you have joined at least once on the server, and must be public.
#
# No default.
#auto_join_rooms = []
# Retry failed and incomplete messages to remote servers immediately upon startup. This is called bursting.
# If this is disabled, said messages may not be delivered until more messages are queued for that server.
# Do not change this option unless server resources are extremely limited or the scale of the server's
# deployment is huge. Do not disable this unless you know what you are doing.
#startup_netburst = true
# Limit the startup netburst to the most recent (default: 50) messages queued for each remote server. All older
# messages are dropped and not reattempted. The `startup_netburst` option must be enabled for this value to have
# any effect. Do not change this value unless you know what you are doing. Set this value to -1 to reattempt
# every message without trimming the queues; this may consume significant disk. Set this value to 0 to drop all
# messages without any attempt at redelivery.
#startup_netburst_keep = 50
### Generic database options
@@ -274,8 +356,8 @@ url_preview_check_root_domain = false
# Set this to any float value in megabytes for conduwuit to tell the database engine that this much memory is available for database-related caches.
# May be useful if you have significant memory to spare to increase performance.
# Defaults to 300.0
#db_cache_capacity_mb = 300.0
# Defaults to 256.0
#db_cache_capacity_mb = 256.0
# Interval in seconds when conduwuit will run database cleanup operations.
#
@@ -287,7 +369,6 @@ url_preview_check_root_domain = false
#cleanup_second_interval = 1800
### RocksDB options
# Set this to true to use RocksDB config options that are tailored to HDDs (slower device storage)
@@ -311,10 +392,9 @@ url_preview_check_root_domain = false
# Time in seconds before RocksDB will forcibly rotate logs. Defaults to 0.
#rocksdb_log_time_to_roll = 0
# Amount of threads that RocksDB will use for parallelism. Set to 0 to use all your physical cores.
# Conduit eagerly spawns threads mainly for federation, so it may not be desirable to use all your cores / logical threads.
# Amount of threads that RocksDB will use for parallelism on database operatons such as cleanup, sync, flush, compaction, etc. Set to 0 to use all your physical cores.
#
# Defaults to your CPU physical core count (not logical threads) count divided by 2 (half)
# Defaults to your CPU physical core count (not logical threads).
#rocksdb_parallelism_threads = 0
# Maximum number of LOG files RocksDB will keep. This must *not* be set to 0. It must be at least 1.
@@ -355,29 +435,169 @@ url_preview_check_root_domain = false
# Defaults to false as this uses more CPU when compressing.
#rocksdb_bottommost_compression = false
# Database recovery mode (for RocksDB WAL corruption)
#
# Use this option when the server reports corruption and refuses to start. Set mode 2 (PointInTime)
# to cleanly recover from this corruption. The server will continue from the last good state,
# several seconds or minutes prior to the crash. Clients may have to run "clear-cache & reload" to
# account for the rollback. Upon success, you may reset the mode back to default and restart again.
# Please note in some cases the corruption error may not be cleared for at least 30 minutes of
# operation in PointInTime mode.
#
# As a very last ditch effort, if PointInTime does not fix or resolve anything, you can try mode
# 3 (SkipAnyCorruptedRecord) but this will leave the server in a potentially inconsistent state.
#
# The default mode 1 (TolerateCorruptedTailRecords) will automatically drop the last entry in the
# database if corrupted during shutdown, but nothing more. It is extraordinarily unlikely this will
# desynchronize clients. To disable any form of silent rollback set mode 0 (AbsoluteConsistency).
#
# The options are:
# 0 = AbsoluteConsistency
# 1 = TolerateCorruptedTailRecords (default)
# 2 = PointInTime (use me if trying to recover)
# 3 = SkipAnyCorruptedRecord (you now voided your Conduwuit warranty)
#
# See https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes for more information
#
# Defaults to 1 (TolerateCorruptedTailRecords)
#rocksdb_recovery_mode = 1
# Controls whether memory buffers are written to storage at the fixed interval set by `cleanup_period_interval`
# even when they are not full. Setting this will increase load on the storage backplane and is never advised
# under normal circumstances.
#rocksdb_periodic_cleanup = false
### Domain Name Resolution and Caching
# Maximum entries stored in DNS memory-cache. The size of an entry may vary so please take care if
# raising this value excessively. Only decrease this when using an external DNS cache. Please note
# that systemd does *not* count as an external cache, even when configured to do so.
#dns_cache_entries = 12288
# Minimum time-to-live in seconds for entries in the DNS cache. The default may appear high to most
# administrators; this is by design. Only decrease this if you are using an external DNS cache.
#dns_min_ttl = 10800
# Minimum time-to-live in seconds for NXDOMAIN entries in the DNS cache. This value is critical for
# the server to federate efficiently. NXDOMAIN's are assumed to not be returning to the federation
# and aggressively cached rather than constantly rechecked.
#dns_min_ttl_nxdomain = 86400
# The number of seconds to wait for a reply to a DNS query. Please note that recursive queries can
# take up to several seconds for some domains, so this value should not be too low.
#dns_timeout = 10
# Number of retries after a timeout.
#dns_attempts = 10
# Fallback to TCP on DNS errors. Set this to false if unsupported by nameserver.
#dns_tcp_fallback = true
# Enable to query all nameservers until the domain is found. Referred to as "trust_negative_responses" in hickory_resolver.
# This can avoid useless DNS queries if the first nameserver responds with NXDOMAIN or an empty NOERROR response.
#
# The default is to query one nameserver and stop (false).
#query_all_nameservers = true
### Request Timeouts, Connection Timeouts, and Connection Pooling
## Request Timeouts are HTTP response timeouts
## Connection Timeouts are TCP connection timeouts
##
## Connection Pooling Timeouts are timeouts for keeping an open idle connection alive.
## Connection pooling and keepalive is very useful for federation or other places where for performance reasons,
## we want to keep connections open that we will re-use frequently due to TCP and TLS 1.3 overhead/expensiveness.
##
## Generally these defaults are the best, but if you find a reason to need to change these they are here.
# Default/base connection timeout
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 10 seconds
#request_conn_timeout = 10
# Default/base request timeout
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 35 seconds
#request_timeout = 35
# Default/base max idle connections per host
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 1 as generally the same open connection can be re-used
#request_idle_per_host = 1
# Default/base idle connection pool timeout
# This is used only by URL previews and update/news endpoint checks
#
# Defaults to 5 seconds
#request_idle_timeout = 5
# Federation well-known resolution connection timeout
#
# Defaults to 6 seconds
#well_known_conn_timeout = 6
# Federation HTTP well-known resolution request timeout
#
# Defaults to 10 seconds
#well_known_timeout = 10
# Federation client/server request timeout
# You most definitely want this to be high to account for extremely large room joins, slow homeservers, your own resources etc.
#
# Defaults to 300 seconds
#federation_timeout = 300
# Federation client/sender max idle connections per host
#
# Defaults to 1 as generally the same open connection can be re-used
#federation_idle_per_host = 1
# Federation client/sender idle connection pool timeout
#
# Defaults to 25 seconds
#federation_idle_timeout = 25
# Appservice URL request connection timeout
#
# Defaults to 120 seconds
#appservice_timeout = 120
# Appservice URL idle connection pool timeout
#
# Defaults to 300 seconds
#appservice_idle_timeout = 300
# Notification gateway pusher idle connection pool timeout
#
# Defaults to 15 seconds
#pusher_idle_timeout = 15
### Presence / Typing Indicators / Read Receipts
# Config option to control local (your server only) presence updates/requests. Defaults to false.
# Config option to control local (your server only) presence updates/requests. Defaults to true.
# Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, this MUST be enabled.
#allow_local_presence = false
#
#allow_local_presence = true
# Config option to control incoming federated presence updates/requests. Defaults to false.
# Config option to control incoming federated presence updates/requests. Defaults to true.
# This option receives presence updates from other servers, but does not send any unless `allow_outgoing_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's.
#allow_incoming_presence = false
#
#allow_incoming_presence = true
# Config option to control outgoing presence updates/requests. Defaults to false.
# Config option to control outgoing presence updates/requests. Defaults to true.
# This option sends presence updates to other servers, but does not receive any unless `allow_incoming_presence` is true.
# Note that presence on conduwuit is very fast unlike Synapse's.
# If using outgoing presence, you MUST enable `allow_local_presence` as well.
#
# Warning: Outgoing federated presence is not spec compliant due to relying on PDUs and EDUs combined.
# Outgoing presence will not be very reliable due to this and any issues with federated outgoing presence are very likely attributed to this issue.
# Incoming presence and local presence are unaffected.
#allow_outgoing_presence = false
#allow_outgoing_presence = true
# Config option to control how many seconds before presence updates that you are idle. Defaults to 5 minutes.
#presence_idle_timeout_s = 300
@@ -389,6 +609,26 @@ url_preview_check_root_domain = false
# Defaults to true.
#allow_incoming_read_receipts = true
# Config option to control whether we should send read receipts to remote servers.
# Defaults to true.
#allow_outgoing_read_receipts = true
# Config option to control outgoing typing updates to federation. Defaults to true.
#allow_outgoing_typing = true
# Config option to control incoming typing updates from federation. Defaults to true.
#allow_incoming_typing = true
# Config option to control maximum time federation user can indicate typing.
#typing_federation_timeout_s = 30
# Config option to control minimum time local client can indicate typing. This does not override
# a client's request to stop typing. It only enforces a minimum value in case of no stop request.
#typing_client_timeout_min_s = 15
# Config option to control maximum time local client can indicate typing.
#typing_client_timeout_max_s = 45
# Other options not in [global]:
#
@@ -403,3 +643,20 @@ url_preview_check_root_domain = false
# This config option is only available if conduwuit was built with `axum_dual_protocol` feature (not default feature)
# Defaults to false
#dual_protocol = false
# If you are using delegation via well-known files and you cannot serve them from your reverse proxy, you can
# uncomment these to serve them directly from conduwuit. This requires proxying all requests to conduwuit, not just `/_matrix` to work.
#
#[global.well_known]
#server = "matrix.example.com:443"
#client = "https://matrix.example.com"
#
# A single contact and/or support page for /.well-known/matrix/support
# All options here are strings. Currently only supports 1 single contact.
# No default.
#
#support_page = ""
#support_role = ""
#support_email = ""
#support_mxid = ""
+1 -1
View File
@@ -5,7 +5,7 @@ Installation
------------
Information about downloading, building and deploying the Debian package, see
the "Installing Conduit" section in [DEPLOY.md](../DEPLOY.md).
the "Installing Conduit" section in the Deploying docs.
All following sections until "Setting up the Reverse Proxy" be ignored because
this is handled automatically by the packaging.
+13
View File
@@ -0,0 +1,13 @@
# Summary
- [Introduction](introduction.md)
- [Differences from upstream Conduit](differences.md)
- [Example configuration](configuration.md)
- [Deploying](deploying.md)
- [Generic](deploying/generic.md)
- [Debian](deploying/debian.md)
- [Docker](deploying/docker.md)
- [NixOS](deploying/nixos.md)
- [TURN](turn.md)
- [Appservices](appservices.md)
+5 -5
View File
@@ -2,7 +2,7 @@
## Getting help
If you run into any problems while setting up an Appservice, write an email to `timo@koesters.xyz`, ask us in [#conduit:fachschaften.org](https://matrix.to/#/#conduit:fachschaften.org) or [open an issue on GitLab](https://gitlab.com/famedly/conduit/-/issues/new).
If you run into any problems while setting up an Appservice: ask us in [#conduwuit:puppygock.gay](https://matrix.to/#/#conduwuit:puppygock.gay) or [open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new).
## Set up the appservice - general instructions
@@ -31,9 +31,9 @@ the room like this:
```
You can confirm it worked by sending a message like this:
`@conduit:your.server.name: list-appservices`
`@conduit:your.server.name: appservices list`
The @conduit bot should answer with `Appservices (1): your-bridge`
The `@conduit` bot should answer with `Appservices (1): your-bridge`
Then you are done. Conduit will send messages to the appservices and the
appservice can send requests to the homeserver. You don't need to restart
@@ -46,9 +46,9 @@ could help.
To remove an appservice go to your admin room and execute
`@conduit:your.server.name: unregister-appservice <name>`
`@conduit:your.server.name: appservices unregister <name>`
where `<name>` one of the output of `list-appservices`.
where `<name>` one of the output of `appservices list`.
### Tested appservices
+5
View File
@@ -0,0 +1,5 @@
# Example configuration
``` toml
{{#include ../conduwuit-example.toml}}
```
+3
View File
@@ -0,0 +1,3 @@
# Deploying
This chapter describes various ways to deploy Conduwuit.
+1
View File
@@ -0,0 +1 @@
{{#include ../../debian/README.md}}
@@ -1,6 +1,4 @@
# Deploy using Docker
> **Note:** To run and use Conduit you should probably use it with a Domain or Subdomain behind a reverse proxy (like Nginx, Traefik, Apache, ...) with a Lets Encrypt certificate.
# Conduwuit for Docker
## Docker
@@ -9,7 +7,7 @@ To run conduwuit with Docker you can either build the image yourself or pull it
### Use a registry
OCI images for conduwuit are available in the registries listed below. We recommend using the image tagged as `latest` from GitLab's own registry.
OCI images for conduwuit are available in the registries listed below.
| Registry | Image | Size | Notes |
| --------------- | --------------------------------------------------------------- | ----------------------------- | ---------------------- |
@@ -33,7 +31,7 @@ to pull it to your machine.
### Build using a dockerfile
### Build using a Dockerfile
The Dockerfile provided by Conduit has two stages, each of which creates an image.
@@ -70,7 +68,7 @@ docker run -d -p 8448:6167 \
or you can use [docker-compose](#docker-compose).
The `-d` flag lets the container run in detached mode. You now need to supply a `conduit.toml` config file, an example can be found [here](../conduwuit-example.toml).
The `-d` flag lets the container run in detached mode. You now need to supply a `conduit.toml` config file, an example can be found [here](../configuration.md).
You can pass in different env vars to change config values on the fly. You can even configure Conduit completely by using env vars, but for that you need
to pass `-e CONDUIT_CONFIG=""` into your container. For an overview of possible values, please take a look at the `docker-compose.yml` file.
@@ -89,7 +87,7 @@ When picking the traefik-related compose file, rename it so it matches `docker-c
rename the override file to `docker-compose.override.yml`. Edit the latter with the values you want
for your server.
Additional info about deploying Conduit can be found [here](../DEPLOY.md).
Additional info about deploying Conduit can be found [here](generic.md).
### Build
@@ -131,7 +129,7 @@ So...step by step:
1. Copy [`docker-compose.for-traefik.yml`](docker-compose.for-traefik.yml) (or
[`docker-compose.with-traefik.yml`](docker-compose.with-traefik.yml)) and [`docker-compose.override.yml`](docker-compose.override.yml) from the repository and remove `.for-traefik` (or `.with-traefik`) from the filename.
2. Open both files and modify/adjust them to your needs. Meaning, change the `CONDUIT_SERVER_NAME` and the volume host mappings according to your needs.
3. Create the `conduit.toml` config file, an example can be found [here](../conduwuit-example.toml), or set `CONDUIT_CONFIG=""` and configure Conduit per env vars.
3. Create the `conduit.toml` config file, an example can be found [here](../configuration.md), or set `CONDUIT_CONFIG=""` and configure Conduit per env vars.
4. Uncomment the `element-web` service if you want to host your own Element Web Client and create a `element_config.json`.
5. Create the files needed by the `well-known` service.
+165
View File
@@ -0,0 +1,165 @@
# Generic deployment documentation
### Please note that this documentation is not fully representative of conduwuit at the moment. Assume majority of it is outdated.
> ## Getting help
>
> If you run into any problems while setting up conduwuit, ask us
> in `#conduwuit:puppygock.gay` or [open an issue on GitHub](https://github.com/girlbossceo/conduwuit/issues/new).
## Installing conduwuit
You may simply download the binary that fits your machine. Run `uname -m` to see what you need.
Prebuilt binaries can be downloaded from the latest successful CI workflow on the main branch here: https://github.com/girlbossceo/conduwuit/actions/workflows/ci.yml?query=branch%3Amain+actor%3Agirlbossceo+is%3Asuccess+event%3Apush
Alternatively, you may compile the binary yourself. First, install any dependencies:
```bash
# Debian
$ sudo apt install libclang-dev build-essential
# RHEL
$ sudo dnf install clang
```
Then, `cd` into the source tree of conduit-next and run:
```bash
$ cargo build --release
```
## Adding a Conduit user
While Conduit can run as any user it is usually better to use dedicated users for different services. This also allows
you to make sure that the file permissions are correctly set up.
In Debian or RHEL, you can use this command to create a Conduit user:
```bash
sudo adduser --system conduit --group --disabled-login --no-create-home
```
## Forwarding ports in the firewall or the router
Conduit uses the ports 443 and 8448 both of which need to be open in the firewall.
If Conduit runs behind a router or in a container and has a different public IP address than the host system these public ports need to be forwarded directly or indirectly to the port mentioned in the config.
## Setting up a systemd service
Now we'll set up a systemd service for Conduit, so it's easy to start/stop Conduit and set it to autostart when your
server reboots. Simply paste the default systemd service you can find below into
`/etc/systemd/system/conduit.service`.
```systemd
[Unit]
Description=Conduwuit Matrix Server
After=network.target
[Service]
Environment="CONDUIT_CONFIG=/etc/matrix-conduit/conduit.toml"
User=conduit
Group=conduit
RuntimeDirectory=conduit
RuntimeDirectoryMode=0750
Restart=always
ExecStart=/usr/local/bin/matrix-conduit
[Install]
WantedBy=multi-user.target
```
Finally, run
```bash
$ sudo systemctl daemon-reload
```
## Creating the Conduit configuration file
Now we need to create the Conduit's config file in `/etc/conduwuit/conduwuit.toml`. Paste this in **and take a moment
to read it. You need to change at least the server name.**
RocksDB (`rocksdb`) is the only supported database backend. SQLite only exists for historical reasons and is not recommended. Any performance issues, storage issues, database issues, etc will not be assisted if using SQLite and you will be asked to migrate to RocksDB first.
See the following example config at [conduwuit-example.toml](../configuration.md)
## Setting the correct file permissions
As we are using a Conduit specific user we need to allow it to read the config. To do that you can run this command on
Debian or RHEL:
```bash
sudo chown -R root:root /etc/matrix-conduit
sudo chmod 755 /etc/matrix-conduit
```
If you use the default database path you also need to run this:
```bash
sudo mkdir -p /var/lib/matrix-conduit/
sudo chown -R conduit:conduit /var/lib/matrix-conduit/
sudo chmod 700 /var/lib/matrix-conduit/
```
## Setting up the Reverse Proxy
Refer to the documentation or various guides online of your chosen reverse proxy software. A Caddy example will be provided as this is the recommended reverse proxy for new users and is very trivial.
### Caddy
Create `/etc/caddy/conf.d/conduwuit_caddyfile` and enter this (substitute for your server name).
```caddy
your.server.name, your.server.name:8448 {
# TCP
reverse_proxy 127.0.0.1:6167
# UNIX socket
#reverse_proxy unix//run/conduit/conduit.sock
}
```
That's it! Just start or enable the service and you're set.
```bash
$ sudo systemctl enable caddy
```
## You're done!
Now you can start Conduit with:
```bash
$ sudo systemctl start conduit
```
Set it to start automatically when your system boots with:
```bash
$ sudo systemctl enable conduit
```
## How do I know it works?
You can open [a Matrix client](https://matrix.org/ecosystem/clients), enter your homeserver and try to register.
You can also use these commands as a quick health check.
```bash
$ curl https://your.server.name/_conduwuit/server_version
# If using port 8448
$ curl https://your.server.name:8448/_conduwuit/server_version
```
- To check if your server can talk with other homeservers, you can use the [Matrix Federation Tester](https://federationtester.matrix.org/).
If you can register but cannot join federated rooms check your config again and also check if the port 8448 is open and forwarded correctly.
# What's next?
## Audio/Video calls
For Audio/Video call functionality see the [TURN Guide](../turn.md).
## Appservices
If you want to set up an appservice, take a look at the [Appservice Guide](../appservices.md).
+30
View File
@@ -0,0 +1,30 @@
# Conduwuit for NixOS
Conduwuit can be acquired by Nix from various places:
* The `flake.nix` at the root of the repo
* The `default.nix` at the root of the repo
* From Conduwuit's binary cache
A binary cache for conduwuit that the CI/CD publishes to is available at the
following places (both are the same just different names):
```
https://attic.kennel.juneis.dog/conduit
conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
https://attic.kennel.juneis.dog/conduwuit
conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
```
If specifying a URL in your flake, please use the GitHub remote: `github:girlbossceo/conduwuit`
The `flake.nix` and `default.nix` do not (currently) provide a NixOS module, so
(for now) [`services.matrix-conduit`][module] from Nixpkgs should be used to
configure Conduit.
If you want to run the latest code, you should get Conduwuit from the `flake.nix`
or `default.nix` and set [`services.matrix-conduit.package`][package]
appropriately.
[module]: https://search.nixos.org/options?channel=unstable&query=services.matrix-conduit
[package]: https://search.nixos.org/options?channel=unstable&query=services.matrix-conduit.package
+36 -11
View File
@@ -1,3 +1,5 @@
#### **Note: This list is not up to date. There are rapidly more and more improvements, fixes, changes, etc being made that it is becoming more difficult to maintain this list. I recommend that you give Conduwuit a try and see the differences for yourself. If you have any concerns, feel free to join the Conduwuit Matrix room and ask any pre-usage questions.**
### list of features, bug fixes, etc that conduwuit does that upstream does not:
- GitLab CI ported to GitHub Actions
@@ -9,18 +11,15 @@
- Attempts and interest in removing extreme and unnecessary panics/unwraps/expects that can lead to denial of service or such (upstream and upstream contributors want this unusual behaviour for some reason)
- Merged and cleaned up upstream MRs that have been sitting for 6-12 months
- Configurable RocksDB logging (`LOG` files) with proper defaults (rotate, max size, verbosity, etc) to stop LOG files from accumulating so much
- Federated presence support and configurable local presence (via upstream MR)
- Concurrency support for key fetching for faster remote room joins and room joins that will error less frequently (via upstream MR)
- Room version 11 support (via upstream MR)
- Config option to allow guest registrations
- Explicit startup error/warning if your configuration allows open registration without a token or such like Synapse
- Improved RocksDB defaults to use new features that help with performance significantly, uses settings tailored to SSDs, various ways to tweak RocksDB, and a conduwuit setting to tell RocksDB to use settings that are tailored to HDDs or slow spinning rust storage.
- Updated Ruma to latest commit where possible, and add some unstable MSCs (some still require an implementation though)
- Revamped admin room infrastructure and commands (via upstream MR)
- Admin room commands to delete room aliases and unpublish rooms from our room directory (via upstream MR)
- Make spaces/hierarchy cache use cache_capacity_modifier instead of hardcoded small value
- Add *optional* feature flag to use SHA256 key names for media instead of base64 to overcome filesystem file name length limitations (OS error file name too long) (via upstream MR)
- Add *optional* feature flag to enable zstd HTTP body compression
- Add *optional* feature flag to use SHA256 key names for media instead of base64 to overcome filesystem file name length limitations (OS error file name too long) (via upstream MR)
- Add feature flags and config options to enable/build with zstd, brotli, and/or gzip HTTP body compression (response and request)
- Add support for querying both Matrix SRV records, the deprecated `_matrix` record and `_matrix-fed` record if necessary
- Add config option for device name federation with a privacy-friendly default (disabled)
- Add config option for requiring authentication to the `/publicRooms` endpoint (room directory) with a default enabled for privacy
@@ -32,7 +31,6 @@
- Add debug admin command to force update user device lists (could potentially resolve some E2EE flukes) (`ForceDeviceListUpdates`)
- Declare various missing Matrix versions and features at `/_matrix/client/versions`
- Add support for serving server and client well-known files from conduwuit using `well_known_client` and `well_known_server` options
- Add non-standard sliding sync proxy health check (?) endpoint at `/client/server.json` that some clients such as Element Web query using the `well_known_client` or `well_known_server` config options
- Send a User-Agent on all of our requests (`conduwuit/0.7.0-alpha+conduwuit-0.1.1`) which strangely was not done upstream since forever. Some providers consider no User-Agent suspicious and block said requests.
- Safer and cleaner shutdowns on both database side as we run cleanup on shutdown and exits database loop better (no potential hanging issues in database loop), overall cleaner shutdown logic
- Allow HEAD HTTP requests in CORS for clients (despite not being explicity mentioned in Matrix spec, HTTP spec says all HEAD requests need to behave the same as GET requests, Synapse supports HEAD requests)
@@ -42,7 +40,6 @@
- Prevent admin credential commands like reset password and deactivate user from modifying non-local users (https://gitlab.com/famedly/conduit/-/issues/377)
- Fixed spec compliance issue with room version 8 - 11 joins (https://github.com/matrix-org/synapse/issues/16717 / https://github.com/matrix-org/matrix-spec/issues/1708)
- Add basic cache eviction for true destinations when requests fail if we use a cached destination (e.g. a server has modified their well-known and we're still connecting to the old destination)
- Only follow 6 redirects total in our default reqwest ClientBuilder
- Generate passwords with 25 characters instead of 15
- Add missing `reason` field to user ban events (`/ban`)
- For all [`/report`](https://spec.matrix.org/v1.9/client-server-api/#post_matrixclientv3roomsroomidreporteventid) requests: check if the reported event ID belongs to the reported room ID, raise report reasoning character limit to 750, fix broken formatting, make a small delayed random response per spec suggestion on privacy, and check if the sender user is in the reported room.
@@ -57,11 +54,8 @@
- Assume well-knowns are broken if they exceed past 10000 characters.
- Basic validation/checks on user-specified room aliases and custom room ID creations
- Warn on unknown config options specified
- Add support for preventing certain room alias names and usernames using regex (via upstream MR) and extended to custom room IDs
- Revamp appservice registration to ruma's `Registration` type which fixes various appservice registration issues, including fixing crashing upon no URL specified (via upstream MR)
- URL preview support (via upstream MR) with various improvements
- Increased graceful shutdown timeout from a low 60 seconds to 180 seconds to avoid killing connections and let the remaining ones finish processing, and ask systemd for more time to shutdown if needed to prevent systemd's default [`TimeoutStopSec=`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#TimeoutStopSec=) of 90 seconds from killing conduwuit
- Bumped default max_concurrent_requests to 500
- Increased graceful shutdown timeout from a low 60 seconds to 180 seconds to avoid killing connections and let the remaining ones finish processing
- Query parameter `?format=event|content` for returning either the room state event's content (default) for the full room state event on ` /_matrix/client/v3/rooms/{roomId}/state/{eventType}[/{stateKey}]` requests (see https://github.com/matrix-org/matrix-spec/issues/1047)
- Add admin commands for banning (blocking) room IDs from our local users joining (admins are always allowed) and evicts all our local users from that room, in addition to bulk room banning support, and blocks room invites (remote and local) to the banned room, as a moderation feature
- Add admin command to delete media via a specific MXC. This deletes the MXC from our database, and the file locally.
@@ -82,3 +76,34 @@
- Admin debug command to fetch a PDU from a remote server and inserts it into our database/timeline
- Update rusqlite/sqlite (not that you should be using it)
- Disable update check by default as it's not useful for conduwuit
- Config option to disable incoming remote read receipts if desired
- Extend clear cache admin command to support clearing DNS and TLS name override caches
- Responsive outgoing read receipt EDU support
- Eliminate all usage of the thread-blocking `getaddrinfo(3)` call upon DNS queries, significantly improving federation latency/ping and cache DNS results using hickory-dns / hickory-resolver
- Store the sender user with the MXC URL for all media uploads (`/upload`) (not for thumbnails or media requests which are unauthenticated)
- Perform connection pooling and keepalives where necessary to significantly improve federation performance and latency
- Implement RocksDB online backups via admin command
- Implement RocksDB write buffer corking and coalescing in database write-heavy areas
- Various config options to tweak connection pooling, request timeouts, connection timeouts, DNS timeouts and settings, etc with good defaults
- Implement config option to auto join rooms upon registration
- Overall significant database, Client-Server, and federation performance and latency improvements
- Outgoing read receipt and private read receipt support (EDU)
- Outgoing typing indicator support (EDU)
- Outgoing and local presence support (EDU)
- **Opt-in** Sentry.io telemetry and metrics, mainly used for crash reporting
- Add `/_conduwuit/server_version` route to return the version of Conduwuit without relying on the federation API `/_matrix/federation/v1/version`
- Add configurable RocksDB recovery modes to aid in recovering corrupte RocksDB database
- Config option to forbid publishing rooms to the room directory (`lockdown_public_room_directory`) except for admins
- Don't allow `m.call.invite` events to be sent in public rooms (prevents calling the entire room)
- On new public room creations, only allow moderators to send `m.call.invite`, `org.matrix.msc3401.call`, and `org.matrix.msc3401.call.member` events
- Stop sending `make_join` requests on room joins if 15 servers respond with `M_UNSUPPORTED_ROOM_VERSION` or `M_INVALID_ROOM_VERSION`
- Stop sending `make_join` requests if 50 servers cannot provide `make_join` for us
- Admin debug command to send a federation request/ping to a server's `/_matrix/federation/v1/version` endpoint and measures the latency it took
- Implement building Conduwuit with jemalloc or hardened_malloc light variant, and produce CI builds with jemalloc or hardened_malloc, for performance and/or security
- Significant RocksDB tuning and improvements tailored to maximising Conduwuit performance with RocksDB
- Implement unstable MSC2666 support for querying mutual rooms with a user
- Add admin command to fetch a server's `/.well-known/matrix/support` file
- Send `Cache-Control` response header with immutable and 1 year cache length for all media requests to instruct clients to cache media, and reduce server load from media requests that could be otherwise cached
- Forbid the admin room from being made public
- Fix admin room handler to not panic/crash if the admin room command response fails (e.g. too large message)
- Implement `include_state` search criteria support for `/search` requests (response now can include room states)
+17
View File
@@ -0,0 +1,17 @@
# Conduwuit
{{#include ../README.md:catchphrase}}
{{#include ../README.md:body}}
#### What's different about your fork than upstream Conduit?
See [differences.md](differences.md)
#### How can I deploy my own?
- [Deployment options](deploying.md)
If you want to connect an Appservice to Conduwuit, take a look at the [appservices documentation](appservices.md).
{{#include ../README.md:footer}}
View File
+10
View File
@@ -50,6 +50,11 @@ name = "cargo-deb"
group = "versions"
script = "cargo deb --version"
[[task]]
name = "lychee"
group = "versions"
script = "lychee --version"
[[task]]
name = "cargo-audit"
group = "security"
@@ -77,6 +82,11 @@ name = "cargo-clippy"
group = "lints"
script = "cargo clippy --workspace --all-targets --all-features --color=always -- -D warnings"
[[task]]
name = "lychee"
group = "lints"
script = "lychee --offline docs"
[[task]]
name = "cargo"
group = "tests"
Generated
+15 -15
View File
@@ -73,11 +73,11 @@
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1709619709,
"narHash": "sha256-l6EPVJfwfelWST7qWQeP6t/TDK3HHv5uUB1b2vw4mOQ=",
"lastModified": 1711606966,
"narHash": "sha256-nTaO7ZDL4D02dVC5ktqnXNiNuODBUHyE4qEcFjAUCQY=",
"owner": "nix-community",
"repo": "fenix",
"rev": "c8943ea9e98d41325ff57d4ec14736d330b321b2",
"rev": "aa45c3e901ea42d6633af083c0c555efaf948b17",
"type": "github"
},
"original": {
@@ -138,11 +138,11 @@
"systems": "systems"
},
"locked": {
"lastModified": 1709126324,
"narHash": "sha256-q6EQdSeUZOG26WelxqkmR7kArjgWCdw5sfJVHPH/7j8=",
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "d465f4819400de7c8d874d50b982301f28a84605",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
@@ -153,11 +153,11 @@
},
"nix-filter": {
"locked": {
"lastModified": 1705332318,
"narHash": "sha256-kcw1yFeJe9N4PjQji9ZeX47jg0p9A0DuU4djKvg1a7I=",
"lastModified": 1710156097,
"narHash": "sha256-1Wvk8UP7PXdf8bCCaEoMnOT1qe5/Duqgj+rL8sRQsSM=",
"owner": "numtide",
"repo": "nix-filter",
"rev": "3449dc925982ad46246cfc36469baf66e1b64f17",
"rev": "3342559a24e85fc164b295c3444e8a139924675b",
"type": "github"
},
"original": {
@@ -200,11 +200,11 @@
},
"nixpkgs_2": {
"locked": {
"lastModified": 1709479366,
"narHash": "sha256-n6F0n8UV6lnTZbYPl1A9q1BS0p4hduAv1mGAP17CVd0=",
"lastModified": 1711523803,
"narHash": "sha256-UKcYiHWHQynzj6CN/vTcix4yd1eCu1uFdsuarupdCQQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "b8697e57f10292a6165a20f03d2f42920dfaf973",
"rev": "2726f127c15a4cc9810843b96cad73c7eb39e443",
"type": "github"
},
"original": {
@@ -228,11 +228,11 @@
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1709571018,
"narHash": "sha256-ISFrxHxE0J5g7lDAscbK88hwaT5uewvWoma9TlFmRzM=",
"lastModified": 1711562745,
"narHash": "sha256-s/YOyBM0vumhkqCFi8CnV5imFlC5JJrGia8CmEXyQkM=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "9f14343f9ee24f53f17492c5f9b653427e2ad15e",
"rev": "ad51a17c627b4ca57f83f0dc1f3bb5f3f17e6d0b",
"type": "github"
},
"original": {
+99 -14
View File
@@ -36,20 +36,21 @@
}: flake-utils.lib.eachDefaultSystem (system:
let
pkgsHost = nixpkgs.legacyPackages.${system};
allocator = null;
rocksdb' = pkgs:
let
version = "8.11.3";
version = "9.0.0";
in
pkgs.rocksdb.overrideAttrs (old: {
(pkgs.rocksdb.overrideAttrs (old: {
inherit version;
src = pkgs.fetchFromGitHub {
owner = "facebook";
owner = "girlbossceo";
repo = "rocksdb";
rev = "v${version}";
hash = "sha256-OpEiMwGxZuxb9o3RQuSrwZMQGLhe9xLT1aa3HpI4KPs=";
rev = "449768a833b79c267c584b5ab1d50e73db6faf9d";
hash = "sha256-MjmGfAlZ5WC2+hFH6nEUprqBjO8xiTQh2HJIqQ5mIg8=";
};
});
}));
# Nix-accessible `Cargo.toml`
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
@@ -73,6 +74,7 @@
];
env = pkgs: {
CONDUIT_VERSION_EXTRA = self.shortRev or self.dirtyShortRev;
ROCKSDB_INCLUDE_DIR = "${rocksdb' pkgs}/include";
ROCKSDB_LIB_DIR = "${rocksdb' pkgs}/lib";
}
@@ -165,7 +167,7 @@
)
);
package = pkgs: builder pkgs {
mkPackage = pkgs: allocator: builder pkgs {
src = nix-filter {
root = ./.;
include = [
@@ -175,6 +177,13 @@
];
};
buildFeatures = [ ]
++ (if allocator == "jemalloc" then [ "jemalloc" ] else [ ])
++ (if allocator == "hmalloc" then [ "hardened_malloc" ] else [ ])
;
rocksdb' = (if allocator == "jemalloc" then (pkgs.rocksdb.override { enableJemalloc = true; }) else (rocksdb' pkgs));
# This is redundant with CI
doCheck = false;
@@ -184,11 +193,13 @@
meta.mainProgram = cargoToml.package.name;
};
mkOciImage = pkgs: package:
pkgs.dockerTools.buildImage {
mkOciImage = pkgs: package: allocator:
pkgs.dockerTools.buildLayeredImage {
name = package.pname;
tag = "main";
copyToRoot = [
# Debian makes builds reproducible through using the HEAD commit's date
created = "@${toString self.lastModified}";
contents = [
pkgs.dockerTools.caCertificates
];
config = {
@@ -206,8 +217,41 @@
in
{
packages = {
default = package pkgsHost;
oci-image = mkOciImage pkgsHost self.packages.${system}.default;
default = mkPackage pkgsHost null;
jemalloc = mkPackage pkgsHost "jemalloc";
hmalloc = mkPackage pkgsHost "hmalloc";
oci-image = mkOciImage pkgsHost self.packages.${system}.default null;
oci-image-jemalloc = mkOciImage pkgsHost self.packages.${system}.default "jemalloc";
oci-image-hmalloc = mkOciImage pkgsHost self.packages.${system}.default "hmalloc";
book =
let
package = self.packages.${system}.default;
in
pkgsHost.stdenv.mkDerivation {
pname = "${package.pname}-book";
version = package.version;
src = nix-filter {
root = ./.;
include = [
"book.toml"
"conduwuit-example.toml"
"README.md"
"debian/README.md"
"docs"
];
};
nativeBuildInputs = (with pkgsHost; [
mdbook
]);
buildPhase = ''
mdbook build
mv public $out
'';
};
}
//
builtins.listToAttrs
@@ -228,7 +272,19 @@
# An output for a statically-linked binary
{
name = binaryName;
value = package pkgsCrossStatic;
value = mkPackage pkgsCrossStatic null;
}
# An output for a statically-linked binary with jemalloc
{
name = "${binaryName}-jemalloc";
value = mkPackage pkgsCrossStatic "jemalloc";
}
# An output for a statically-linked binary with hardened_malloc
{
name = "${binaryName}-hmalloc";
value = mkPackage pkgsCrossStatic "hmalloc";
}
# An output for an OCI image based on that binary
@@ -236,13 +292,36 @@
name = "oci-image-${crossSystem}";
value = mkOciImage
pkgsCrossStatic
self.packages.${system}.${binaryName};
self.packages.${system}.${binaryName}
null;
}
# An output for an OCI image based on that binary with jemalloc
{
name = "oci-image-${crossSystem}-jemalloc";
value = mkOciImage
pkgsCrossStatic
self.packages.${system}.${binaryName}
"jemalloc";
}
# An output for an OCI image based on that binary with hardened_malloc
{
name = "oci-image-${crossSystem}-hmalloc";
value = mkOciImage
pkgsCrossStatic
self.packages.${system}.${binaryName}
"hmalloc";
}
]
)
[
"x86_64-unknown-linux-musl"
"x86_64-unknown-linux-musl-jemalloc"
"x86_64-unknown-linux-musl-hmalloc"
"aarch64-unknown-linux-musl"
"aarch64-unknown-linux-musl-jemalloc"
"aarch64-unknown-linux-musl-hmalloc"
]
)
);
@@ -276,6 +355,12 @@
# Needed for our script for Complement
jq
# Needed for finding broken markdown links
lychee
# Useful for editing the book locally
mdbook
]);
};
});
-208
View File
@@ -1,208 +0,0 @@
# Conduit for Nix/NixOS
This guide assumes you have a recent version of Nix (^2.4) installed.
Since Conduit ships as a Nix flake, you'll first need to [enable
flakes][enable_flakes].
A binary cache for conduwuit that the CI/CD publishes to is available at the
following places (both are the same just different names):
```
https://attic.kennel.juneis.dog/conduit
conduit:Isq8FGyEC6FOXH6nD+BOeAA+bKp6X6UIbupSlGEPuOg=
https://attic.kennel.juneis.dog/conduwuit
conduwuit:lYPVh7o1hLu1idH4Xt2QHaRa49WRGSAqzcfFd94aOTw=
```
You can now use the usual Nix commands to interact with conduwuit's flake. For
example, `nix run github:girlbossceo/conduwuit` will run conduwuit (though you'll need
to provide configuration and such manually as usual).
If your NixOS configuration is defined as a flake, you can depend on this flake
to provide a more up-to-date version than provided by `nixpkgs`. In your flake,
add the following to your `inputs`:
```nix
conduit = {
url = "github:girlbossceo/conduwuit";
# Assuming you have an input for nixpkgs called `nixpkgs`. If you experience
# build failures while using this, try commenting/deleting this line. This
# will probably also require you to always build from source.
inputs.nixpkgs.follows = "nixpkgs";
};
```
Next, make sure you're passing your flake inputs to the `specialArgs` argument
of `nixpkgs.lib.nixosSystem` [as explained here][specialargs]. This guide will
assume you've named the group `flake-inputs`.
Now you can configure conduwuit and a reverse proxy for it. Add the following to
a new Nix file and include it in your configuration:
```nix
{ config
, pkgs
, flake-inputs
, ...
}:
let
# You'll need to edit these values
# The hostname that will appear in your user and room IDs
server_name = "example.com";
# The hostname that Conduit actually runs on
#
# This can be the same as `server_name` if you want. This is only necessary
# when Conduit is running on a different machine than the one hosting your
# root domain. This configuration also assumes this is all running on a single
# machine, some tweaks will need to be made if this is not the case.
matrix_hostname = "matrix.${server_name}";
# An admin email for TLS certificate notifications
admin_email = "admin@${server_name}";
# These ones you can leave alone
# Build a dervation that stores the content of `${server_name}/.well-known/matrix/server`
well_known_server = pkgs.writeText "well-known-matrix-server" ''
{
"m.server": "${matrix_hostname}"
}
'';
# Build a dervation that stores the content of `${server_name}/.well-known/matrix/client`
well_known_client = pkgs.writeText "well-known-matrix-client" ''
{
"m.homeserver": {
"base_url": "https://${matrix_hostname}"
}
}
'';
in
{
# Configure Conduit itself
services.matrix-conduit = {
enable = true;
# This causes NixOS to use the flake defined in this repository instead of
# the build of Conduit built into nixpkgs.
package = flake-inputs.conduit.packages.${pkgs.system}.default;
settings.global = {
inherit server_name;
};
};
# Configure automated TLS acquisition/renewal
security.acme = {
acceptTerms = true;
defaults = {
email = admin_email;
};
};
# ACME data must be readable by the NGINX user
users.users.nginx.extraGroups = [
"acme"
];
# Configure NGINX as a reverse proxy
services.nginx = {
enable = true;
recommendedProxySettings = true;
virtualHosts = {
"${matrix_hostname}" = {
forceSSL = true;
enableACME = true;
listen = [
{
addr = "0.0.0.0";
port = 443;
ssl = true;
}
{
addr = "[::]";
port = 443;
ssl = true;
} {
addr = "0.0.0.0";
port = 8448;
ssl = true;
}
{
addr = "[::]";
port = 8448;
ssl = true;
}
];
locations."/_matrix/" = {
proxyPass = "http://backend_conduit";
proxyWebsockets = true;
extraConfig = ''
proxy_set_header Host $host;
proxy_buffering off;
'';
};
extraConfig = ''
merge_slashes off;
'';
};
"${server_name}" = {
forceSSL = true;
enableACME = true;
locations."=/.well-known/matrix/server" = {
# Use the contents of the derivation built previously
alias = "${well_known_server}";
extraConfig = ''
# Set the header since by default NGINX thinks it's just bytes
default_type application/json;
'';
};
locations."=/.well-known/matrix/client" = {
# Use the contents of the derivation built previously
alias = "${well_known_client}";
extraConfig = ''
# Set the header since by default NGINX thinks it's just bytes
default_type application/json;
# https://matrix.org/docs/spec/client_server/r0.4.0#web-browser-clients
add_header Access-Control-Allow-Origin "*";
'';
};
};
};
upstreams = {
"backend_conduit" = {
servers = {
"[::1]:${toString config.services.matrix-conduit.settings.global.port}" = { };
};
};
};
};
# Open firewall ports for HTTP, HTTPS, and Matrix federation
networking.firewall.allowedTCPPorts = [ 80 443 8448 ];
networking.firewall.allowedUDPPorts = [ 80 443 8448 ];
}
```
Now you can rebuild your system configuration and you should be good to go!
[enable_flakes]: https://nixos.wiki/wiki/Flakes#Enable_flakes
[specialargs]: https://nixos.wiki/wiki/Flakes#Using_nix_flakes_with_NixOS
+2 -1
View File
@@ -24,4 +24,5 @@ group_imports = "StdExternalCrate"
newline_style = "Unix"
use_field_init_shorthand = true
use_small_heuristics = "Off"
use_try_shorthand = true
use_try_shorthand = true
chain_width = 60
-94
View File
@@ -1,94 +0,0 @@
use std::{fmt::Debug, mem, time::Duration};
use bytes::BytesMut;
use ruma::api::{appservice::Registration, IncomingResponse, MatrixVersion, OutgoingRequest, SendAccessToken};
use tracing::warn;
use crate::{services, utils, Error, Result};
/// Sends a request to an appservice
///
/// Only returns None if there is no url specified in the appservice
/// registration file
pub(crate) async fn send_request<T>(registration: Registration, request: T) -> Option<Result<T::IncomingResponse>>
where
T: OutgoingRequest + Debug,
{
if let Some(destination) = registration.url {
let hs_token = registration.hs_token.as_str();
let mut http_request = request
.try_into_http_request::<BytesMut>(
&destination,
SendAccessToken::IfRequired(hs_token),
&[MatrixVersion::V1_0],
)
.map_err(|e| {
warn!("Failed to find destination {}: {}", destination, e);
Error::BadServerResponse("Invalid destination")
})
.unwrap()
.map(BytesMut::freeze);
let mut parts = http_request.uri().clone().into_parts();
let old_path_and_query = parts.path_and_query.unwrap().as_str().to_owned();
let symbol = if old_path_and_query.contains('?') {
"&"
} else {
"?"
};
parts.path_and_query = Some((old_path_and_query + symbol + "access_token=" + hs_token).parse().unwrap());
*http_request.uri_mut() = parts.try_into().expect("our manipulation is always valid");
let mut reqwest_request =
reqwest::Request::try_from(http_request).expect("all http requests are valid reqwest requests");
*reqwest_request.timeout_mut() = Some(Duration::from_secs(120));
let url = reqwest_request.url().clone();
let mut response = match services().globals.default_client().execute(reqwest_request).await {
Ok(r) => r,
Err(e) => {
warn!(
"Could not send request to appservice {} at {}: {}",
registration.id, destination, e
);
return Some(Err(e.into()));
},
};
// reqwest::Response -> http::Response conversion
let status = response.status();
let mut http_response_builder = http::Response::builder().status(status).version(response.version());
mem::swap(
response.headers_mut(),
http_response_builder.headers_mut().expect("http::response::Builder is usable"),
);
let body = response.bytes().await.unwrap_or_else(|e| {
warn!("server error: {}", e);
Vec::new().into()
}); // TODO: handle timeout
if !status.is_success() {
warn!(
"Appservice returned bad response {} {}\n{}\n{:?}",
destination,
status,
url,
utils::string_from_bytes(&body)
);
}
let response = T::IncomingResponse::try_from_http_response(
http_response_builder.body(body).expect("reqwest body is valid http body"),
);
Some(response.map_err(|_| {
warn!("Appservice returned invalid response bytes {}\n{}", destination, url);
Error::BadServerResponse("Server returned bad response.")
}))
} else {
None
}
}
+147 -38
View File
@@ -2,7 +2,8 @@ use register::RegistrationKind;
use ruma::{
api::client::{
account::{
change_password, deactivate, get_3pids, get_username_availability, register,
change_password, deactivate, get_3pids, get_username_availability,
register::{self, LoginType},
request_3pid_management_token_via_email, request_3pid_management_token_via_msisdn, whoami,
ThirdPartyIdRemovalStatus,
},
@@ -12,10 +13,13 @@ use ruma::{
events::{room::message::RoomMessageEventContent, GlobalAccountDataEventType},
push, UserId,
};
use tracing::{info, warn};
use tracing::{error, info, warn};
use super::{DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH};
use crate::{api::client_server, services, utils, Error, Result, Ruma};
use crate::{
api::client_server::{self, join_room_by_id_helper},
service, services, utils, Error, Result, Ruma,
};
const RANDOM_USER_ID_LENGTH: usize = 10;
@@ -44,7 +48,11 @@ pub async fn get_register_available_route(
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken."));
}
if services().globals.forbidden_usernames().is_match(user_id.localpart()) {
if services()
.globals
.forbidden_usernames()
.is_match(user_id.localpart())
{
return Err(Error::BadRequest(ErrorKind::Unknown, "Username is forbidden."));
}
@@ -73,14 +81,15 @@ pub async fn get_register_available_route(
/// - Creates a new account and populates it with default account data
/// - If `inhibit_login` is false: Creates a device and returns device id and
/// access_token
#[allow(clippy::doc_markdown)]
pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<register::v3::Response> {
if !services().globals.allow_registration() && !body.from_appservice {
if !services().globals.allow_registration() && body.appservice_info.is_none() {
info!(
"Registration disabled and request not from known appservice, rejecting registration attempt for username \
{:?}",
body.username
);
return Err(Error::BadRequest(ErrorKind::Forbidden, "Registration has been disabled."));
return Err(Error::BadRequest(ErrorKind::forbidden(), "Registration has been disabled."));
}
let is_guest = body.kind == RegistrationKind::Guest;
@@ -108,7 +117,7 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
registration. Guest's initial device name: {:?}",
body.initial_device_display_name
);
return Err(Error::BadRequest(ErrorKind::Forbidden, "Registration temporarily disabled."));
return Err(Error::BadRequest(ErrorKind::forbidden(), "Registration temporarily disabled."));
}
let user_id = match (&body.username, is_guest) {
@@ -125,7 +134,11 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
return Err(Error::BadRequest(ErrorKind::UserInUse, "Desired user ID is already taken."));
}
if services().globals.forbidden_usernames().is_match(proposed_user_id.localpart()) {
if services()
.globals
.forbidden_usernames()
.is_match(proposed_user_id.localpart())
{
return Err(Error::BadRequest(ErrorKind::Unknown, "Username is forbidden."));
}
@@ -143,6 +156,18 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
},
};
if body.body.login_type == Some(LoginType::ApplicationService) {
if let Some(ref info) = body.appservice_info {
if !info.is_user_match(&user_id) {
return Err(Error::BadRequest(ErrorKind::Exclusive, "User is not in namespace."));
}
} else {
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing appservice token."));
}
} else if services().appservice.is_exclusive_user_id(&user_id).await {
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice."));
}
// UIAA
let mut uiaainfo;
let skip_auth;
@@ -157,7 +182,7 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
session: None,
auth_error: None,
};
skip_auth = body.from_appservice;
skip_auth = body.appservice_info.is_some();
} else {
// No registration token necessary, but clients must still go through the flow
uiaainfo = UiaaInfo {
@@ -169,7 +194,7 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
session: None,
auth_error: None,
};
skip_auth = body.from_appservice || is_guest;
skip_auth = body.appservice_info.is_some() || is_guest;
}
if !skip_auth {
@@ -216,7 +241,10 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
displayname.push_str(&(" ".to_owned() + services().globals.new_user_displayname_suffix()));
}
services().users.set_displayname(&user_id, Some(displayname.clone())).await?;
services()
.users
.set_displayname(&user_id, Some(displayname.clone()))
.await?;
// Initial account data
services().account_data.update(
@@ -254,37 +282,104 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
let token = utils::random_string(TOKEN_LENGTH);
// Create device for this account
services().users.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?;
services()
.users
.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?;
info!("New user \"{}\" registered on this server.", user_id);
// log in conduit admin channel if a non-guest user registered
if !body.from_appservice && !is_guest {
services().admin.send_message(RoomMessageEventContent::notice_plain(format!(
"New user \"{user_id}\" registered on this server."
)));
if body.appservice_info.is_none() && !is_guest {
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"New user \"{user_id}\" registered on this server."
)));
}
// log in conduit admin channel if a guest registered
if !body.from_appservice && is_guest {
services().admin.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with device display name `{:?}` registered on this server.",
body.initial_device_display_name
)));
if body.appservice_info.is_none() && is_guest && services().globals.log_guest_registrations() {
if let Some(device_display_name) = &body.initial_device_display_name {
if body
.initial_device_display_name
.as_ref()
.is_some_and(|device_display_name| !device_display_name.is_empty())
{
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with device display name `{device_display_name}` registered on this \
server."
)));
} else {
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with no device display name registered on this server.",
)));
}
} else {
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"Guest user \"{user_id}\" with no device display name registered on this server.",
)));
}
}
// If this is the first real user, grant them admin privileges except for guest
// users Note: the server user, @conduit:servername, is generated first
if !is_guest {
if let Some(admin_room) = services().admin.get_admin_room()? {
if services().rooms.state_cache.room_joined_count(&admin_room)? == Some(1) {
services().admin.make_user_admin(&user_id, displayname).await?;
if let Some(admin_room) = service::admin::Service::get_admin_room()? {
if services()
.rooms
.state_cache
.room_joined_count(&admin_room)?
== Some(1)
{
services()
.admin
.make_user_admin(&user_id, displayname)
.await?;
warn!("Granting {} admin privileges as the first user", user_id);
}
}
}
if body.appservice_info.is_none()
&& !services().globals.config.auto_join_rooms.is_empty()
&& (services().globals.allow_guests_auto_join_rooms() || !is_guest)
{
for room in &services().globals.config.auto_join_rooms {
if !services()
.rooms
.state_cache
.server_in_room(services().globals.server_name(), room)?
{
warn!("Skipping room {room} to automatically join as we have never joined before.");
continue;
}
if let Some(room_id_server_name) = room.server_name() {
if let Err(e) = join_room_by_id_helper(
Some(&user_id),
room,
Some("Automatically joining this room upon registration".to_owned()),
&[room_id_server_name.to_owned(), services().globals.server_name().to_owned()],
None,
)
.await
{
// don't return this error so we don't fail registrations
error!("Failed to automatically join room {room} for user {user_id}: {e}");
} else {
info!("Automatically joined room {room} for user {user_id}");
};
}
}
}
Ok(register::v3::Response {
access_token: Some(token),
user_id,
@@ -326,27 +421,33 @@ pub async fn change_password_route(body: Ruma<change_password::v3::Request>) ->
};
if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
let (worked, uiaainfo) = services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked {
return Err(Error::Uiaa(uiaainfo));
}
// Success!
} else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?;
services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo));
} else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
services().users.set_password(sender_user, Some(&body.new_password))?;
services()
.users
.set_password(sender_user, Some(&body.new_password))?;
if body.logout_devices {
// Logout all devices except the current one
for id in services()
.users
.all_device_ids(sender_user)
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.filter(|id| id != sender_device)
{
services().users.remove_device(sender_user, &id)?;
@@ -354,16 +455,18 @@ pub async fn change_password_route(body: Ruma<change_password::v3::Request>) ->
}
info!("User {} changed their password.", sender_user);
services().admin.send_message(RoomMessageEventContent::notice_plain(format!(
"User {sender_user} changed their password."
)));
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"User {sender_user} changed their password."
)));
Ok(change_password::v3::Response {})
}
/// # `GET _matrix/client/r0/account/whoami`
///
/// Get user_id of the sender user.
/// Get `user_id` of the sender user.
///
/// Note: Also works for Application Services
pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3::Response> {
@@ -373,7 +476,7 @@ pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3:
Ok(whoami::v3::Response {
user_id: sender_user.clone(),
device_id,
is_guest: services().users.is_deactivated(sender_user)? && !body.from_appservice,
is_guest: services().users.is_deactivated(sender_user)? && body.appservice_info.is_none(),
})
}
@@ -403,14 +506,18 @@ pub async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Result<dea
};
if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
let (worked, uiaainfo) = services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked {
return Err(Error::Uiaa(uiaainfo));
}
// Success!
} else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?;
services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo));
} else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
@@ -423,9 +530,11 @@ pub async fn deactivate_route(body: Ruma<deactivate::v3::Request>) -> Result<dea
services().users.deactivate_account(sender_user)?;
info!("User {} deactivated their account.", sender_user);
services().admin.send_message(RoomMessageEventContent::notice_plain(format!(
"User {sender_user} deactivated their account."
)));
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"User {sender_user} deactivated their account."
)));
Ok(deactivate::v3::Response {
id_server_unbind_result: ThirdPartyIdRemovalStatus::NoSupport,
+109 -47
View File
@@ -21,15 +21,41 @@ pub async fn create_alias_route(body: Ruma<create_alias::v3::Request>) -> Result
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server."));
}
if services().globals.forbidden_room_names().is_match(body.room_alias.alias()) {
if services()
.globals
.forbidden_alias_names()
.is_match(body.room_alias.alias())
{
return Err(Error::BadRequest(ErrorKind::Unknown, "Room alias is forbidden."));
}
if services().rooms.alias.resolve_local_alias(&body.room_alias)?.is_some() {
if let Some(ref info) = body.appservice_info {
if !info.aliases.is_match(body.room_alias.as_str()) {
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias is not in namespace."));
}
} else if services()
.appservice
.is_exclusive_alias(&body.room_alias)
.await
{
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias reserved by appservice."));
}
if services()
.rooms
.alias
.resolve_local_alias(&body.room_alias)?
.is_some()
{
return Err(Error::Conflict("Alias already exists."));
}
if services().rooms.alias.set_alias(&body.room_alias, &body.room_id).is_err() {
if services()
.rooms
.alias
.set_alias(&body.room_alias, &body.room_id)
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid room alias. Alias must be in the form of '#localpart:server_name'",
@@ -50,11 +76,33 @@ pub async fn delete_alias_route(body: Ruma<delete_alias::v3::Request>) -> Result
return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server."));
}
if services().rooms.alias.resolve_local_alias(&body.room_alias)?.is_none() {
if services()
.rooms
.alias
.resolve_local_alias(&body.room_alias)?
.is_none()
{
return Err(Error::BadRequest(ErrorKind::NotFound, "Alias does not exist."));
}
if services().rooms.alias.remove_alias(&body.room_alias).is_err() {
if let Some(ref info) = body.appservice_info {
if !info.aliases.is_match(body.room_alias.as_str()) {
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias is not in namespace."));
}
} else if services()
.appservice
.is_exclusive_alias(&body.room_alias)
.await
{
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias reserved by appservice."));
}
if services()
.rooms
.alias
.remove_alias(&body.room_alias)
.is_err()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Invalid room alias. Alias must be in the form of '#localpart:server_name'",
@@ -89,18 +137,17 @@ pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get
let mut servers = response.servers;
// find active servers in room state cache to suggest
for extra_servers in services().rooms.state_cache.room_servers(&room_id).filter_map(std::result::Result::ok) {
servers.push(extra_servers);
}
// since the room alias server_name responded, insert it into the list
servers.push(room_alias.server_name().into());
// insert our server as the very first choice if in list
if let Some(server_index) =
servers.clone().into_iter().position(|server| server == services().globals.server_name())
{
servers.remove(server_index);
servers.insert(0, services().globals.server_name().to_owned());
}
// find active servers in room state cache to suggest
servers.extend(
services()
.rooms
.state_cache
.room_servers(&room_id)
.filter_map(Result::ok),
);
servers.sort_unstable();
servers.dedup();
@@ -108,6 +155,22 @@ pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get
// shuffle list of servers randomly after sort and dedupe
servers.shuffle(&mut rand::thread_rng());
// prefer the very first server to be ourselves if available, else prefer the
// room alias server first
if let Some(server_index) = servers
.iter()
.position(|server| server == services().globals.server_name())
{
servers.remove(server_index);
servers.insert(0, services().globals.server_name().to_owned());
} else if let Some(alias_server_index) = servers
.iter()
.position(|server| server == room_alias.server_name())
{
servers.remove(alias_server_index);
servers.insert(0, room_alias.server_name().into());
}
return Ok(get_alias::v3::Response::new(room_id, servers));
}
@@ -115,22 +178,20 @@ pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get
match services().rooms.alias.resolve_local_alias(&room_alias)? {
Some(r) => room_id = Some(r),
None => {
for appservice in services().appservice.registration_info.read().await.values() {
for appservice in services().appservice.read().await.values() {
if appservice.aliases.is_match(room_alias.as_str())
&& if let Some(opt_result) = services()
.sending
.send_appservice_request(
appservice.registration.clone(),
appservice::query::query_room_alias::v1::Request {
room_alias: room_alias.clone(),
},
)
.await
{
opt_result.is_ok()
} else {
false
} {
&& matches!(
services()
.sending
.send_appservice_request(
appservice.registration.clone(),
appservice::query::query_room_alias::v1::Request {
room_alias: room_alias.clone(),
},
)
.await,
Ok(Some(_opt_result))
) {
room_id = Some(
services()
.rooms
@@ -144,25 +205,17 @@ pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get
},
};
let room_id = match room_id {
Some(room_id) => room_id,
None => return Err(Error::BadRequest(ErrorKind::NotFound, "Room with alias not found.")),
let Some(room_id) = room_id else {
return Err(Error::BadRequest(ErrorKind::NotFound, "Room with alias not found."));
};
let mut servers: Vec<OwnedServerName> = Vec::new();
// find active servers in room state cache to suggest
for extra_servers in services().rooms.state_cache.room_servers(&room_id).filter_map(std::result::Result::ok) {
servers.push(extra_servers);
}
// insert our server as the very first choice if in list
if let Some(server_index) =
servers.clone().into_iter().position(|server| server == services().globals.server_name())
{
servers.remove(server_index);
servers.insert(0, services().globals.server_name().to_owned());
}
let mut servers: Vec<OwnedServerName> = services()
.rooms
.state_cache
.room_servers(&room_id)
.filter_map(Result::ok)
.collect();
servers.sort_unstable();
servers.dedup();
@@ -170,5 +223,14 @@ pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get
// shuffle list of servers randomly after sort and dedupe
servers.shuffle(&mut rand::thread_rng());
// insert our server as the very first choice if in list
if let Some(server_index) = servers
.iter()
.position(|server| server == services().globals.server_name())
{
servers.remove(server_index);
servers.insert(0, services().globals.server_name().to_owned());
}
Ok(get_alias::v3::Response::new(room_id, servers))
}
+104 -31
View File
@@ -17,7 +17,9 @@ pub async fn create_backup_version_route(
body: Ruma<create_backup_version::v3::Request>,
) -> Result<create_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let version = services().key_backups.create_backup(sender_user, &body.algorithm)?;
let version = services()
.key_backups
.create_backup(sender_user, &body.algorithm)?;
Ok(create_backup_version::v3::Response {
version,
@@ -32,7 +34,9 @@ pub async fn update_backup_version_route(
body: Ruma<update_backup_version::v3::Request>,
) -> Result<update_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.update_backup(sender_user, &body.version, &body.algorithm)?;
services()
.key_backups
.update_backup(sender_user, &body.version, &body.algorithm)?;
Ok(update_backup_version::v3::Response {})
}
@@ -70,8 +74,13 @@ pub async fn get_backup_info_route(body: Ruma<get_backup_info::v3::Request>) ->
Ok(get_backup_info::v3::Response {
algorithm,
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(),
etag: services().key_backups.get_etag(sender_user, &body.version)?,
count: (services()
.key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
version: body.version.clone(),
})
}
@@ -87,7 +96,9 @@ pub async fn delete_backup_version_route(
) -> Result<delete_backup_version::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.delete_backup(sender_user, &body.version)?;
services()
.key_backups
.delete_backup(sender_user, &body.version)?;
Ok(delete_backup_version::v3::Response {})
}
@@ -103,7 +114,12 @@ pub async fn delete_backup_version_route(
pub async fn add_backup_keys_route(body: Ruma<add_backup_keys::v3::Request>) -> Result<add_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if Some(&body.version) != services().key_backups.get_latest_backup_version(sender_user)?.as_ref() {
if Some(&body.version)
!= services()
.key_backups
.get_latest_backup_version(sender_user)?
.as_ref()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.",
@@ -112,13 +128,20 @@ pub async fn add_backup_keys_route(body: Ruma<add_backup_keys::v3::Request>) ->
for (room_id, room) in &body.rooms {
for (session_id, key_data) in &room.sessions {
services().key_backups.add_key(sender_user, &body.version, room_id, session_id, key_data)?;
services()
.key_backups
.add_key(sender_user, &body.version, room_id, session_id, key_data)?;
}
}
Ok(add_backup_keys::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(),
etag: services().key_backups.get_etag(sender_user, &body.version)?,
count: (services()
.key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
})
}
@@ -135,7 +158,12 @@ pub async fn add_backup_keys_for_room_route(
) -> Result<add_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if Some(&body.version) != services().key_backups.get_latest_backup_version(sender_user)?.as_ref() {
if Some(&body.version)
!= services()
.key_backups
.get_latest_backup_version(sender_user)?
.as_ref()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.",
@@ -143,12 +171,19 @@ pub async fn add_backup_keys_for_room_route(
}
for (session_id, key_data) in &body.sessions {
services().key_backups.add_key(sender_user, &body.version, &body.room_id, session_id, key_data)?;
services()
.key_backups
.add_key(sender_user, &body.version, &body.room_id, session_id, key_data)?;
}
Ok(add_backup_keys_for_room::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(),
etag: services().key_backups.get_etag(sender_user, &body.version)?,
count: (services()
.key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
})
}
@@ -165,18 +200,30 @@ pub async fn add_backup_keys_for_session_route(
) -> Result<add_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if Some(&body.version) != services().key_backups.get_latest_backup_version(sender_user)?.as_ref() {
if Some(&body.version)
!= services()
.key_backups
.get_latest_backup_version(sender_user)?
.as_ref()
{
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"You may only manipulate the most recently created version of the backup.",
));
}
services().key_backups.add_key(sender_user, &body.version, &body.room_id, &body.session_id, &body.session_data)?;
services()
.key_backups
.add_key(sender_user, &body.version, &body.room_id, &body.session_id, &body.session_data)?;
Ok(add_backup_keys_for_session::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(),
etag: services().key_backups.get_etag(sender_user, &body.version)?,
count: (services()
.key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
})
}
@@ -201,7 +248,9 @@ pub async fn get_backup_keys_for_room_route(
) -> Result<get_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sessions = services().key_backups.get_room(sender_user, &body.version, &body.room_id)?;
let sessions = services()
.key_backups
.get_room(sender_user, &body.version, &body.room_id)?;
Ok(get_backup_keys_for_room::v3::Response {
sessions,
@@ -216,10 +265,13 @@ pub async fn get_backup_keys_for_session_route(
) -> Result<get_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let key_data =
services().key_backups.get_session(sender_user, &body.version, &body.room_id, &body.session_id)?.ok_or(
Error::BadRequest(ErrorKind::NotFound, "Backup key not found for this user's session."),
)?;
let key_data = services()
.key_backups
.get_session(sender_user, &body.version, &body.room_id, &body.session_id)?
.ok_or(Error::BadRequest(
ErrorKind::NotFound,
"Backup key not found for this user's session.",
))?;
Ok(get_backup_keys_for_session::v3::Response {
key_data,
@@ -234,11 +286,18 @@ pub async fn delete_backup_keys_route(
) -> Result<delete_backup_keys::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.delete_all_keys(sender_user, &body.version)?;
services()
.key_backups
.delete_all_keys(sender_user, &body.version)?;
Ok(delete_backup_keys::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(),
etag: services().key_backups.get_etag(sender_user, &body.version)?,
count: (services()
.key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
})
}
@@ -250,11 +309,18 @@ pub async fn delete_backup_keys_for_room_route(
) -> Result<delete_backup_keys_for_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.delete_room_keys(sender_user, &body.version, &body.room_id)?;
services()
.key_backups
.delete_room_keys(sender_user, &body.version, &body.room_id)?;
Ok(delete_backup_keys_for_room::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(),
etag: services().key_backups.get_etag(sender_user, &body.version)?,
count: (services()
.key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
})
}
@@ -266,10 +332,17 @@ pub async fn delete_backup_keys_for_session_route(
) -> Result<delete_backup_keys_for_session::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().key_backups.delete_room_key(sender_user, &body.version, &body.room_id, &body.session_id)?;
services()
.key_backups
.delete_room_key(sender_user, &body.version, &body.room_id, &body.session_id)?;
Ok(delete_backup_keys_for_session::v3::Response {
count: (services().key_backups.count_keys(sender_user, &body.version)? as u32).into(),
etag: services().key_backups.get_etag(sender_user, &body.version)?,
count: (services()
.key_backups
.count_keys(sender_user, &body.version)? as u32)
.into(),
etag: services()
.key_backups
.get_etag(sender_user, &body.version)?,
})
}
+20 -2
View File
@@ -1,12 +1,13 @@
use std::collections::BTreeMap;
use ruma::api::client::discovery::get_capabilities::{
self, Capabilities, RoomVersionStability, RoomVersionsCapability,
self, Capabilities, ChangePasswordCapability, RoomVersionStability, RoomVersionsCapability, SetAvatarUrlCapability,
SetDisplayNameCapability, ThirdPartyIdChangesCapability,
};
use crate::{services, Result, Ruma};
/// # `GET /_matrix/client/r0/capabilities`
/// # `GET /_matrix/client/v3/capabilities`
///
/// Get information on the supported feature set and other relevent capabilities
/// of this server.
@@ -27,6 +28,23 @@ pub async fn get_capabilities_route(
available,
};
capabilities.change_password = ChangePasswordCapability {
enabled: true,
};
capabilities.set_avatar_url = SetAvatarUrlCapability {
enabled: true,
};
capabilities.set_displayname = SetDisplayNameCapability {
enabled: true,
};
// conduit does not implement 3PID stuff
capabilities.thirdparty_id_changes = ThirdPartyIdChangesCapability {
enabled: false,
};
Ok(get_capabilities::v3::Response {
capabilities,
})
+53 -29
View File
@@ -42,9 +42,13 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
let room_id = base_event.room_id.clone();
if !services().rooms.state_accessor.user_can_see_event(sender_user, &room_id, &body.event_id)? {
if !services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &room_id, &body.event_id)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
ErrorKind::forbidden(),
"You don't have permission to view this event.",
));
}
@@ -69,7 +73,7 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
.timeline
.pdus_until(sender_user, &room_id, base_token)?
.take(limit / 2)
.filter_map(std::result::Result::ok) // Remove buggy events
.filter_map(Result::ok) // Remove buggy events
.filter(|(_, pdu)| {
services()
.rooms
@@ -91,17 +95,21 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
}
}
let start_token =
events_before.last().map(|(count, _)| count.stringify()).unwrap_or_else(|| base_token.stringify());
let start_token = events_before
.last()
.map_or_else(|| base_token.stringify(), |(count, _)| count.stringify());
let events_before: Vec<_> = events_before.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect();
let events_before: Vec<_> = events_before
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
let events_after: Vec<_> = services()
.rooms
.timeline
.pdus_after(sender_user, &room_id, base_token)?
.take(limit / 2)
.filter_map(std::result::Result::ok) // Remove buggy events
.filter_map(Result::ok) // Remove buggy events
.filter(|(_, pdu)| {
services()
.rooms
@@ -123,43 +131,59 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
}
}
let shortstatehash = match services()
let shortstatehash = services()
.rooms
.state_accessor
.pdu_shortstatehash(events_after.last().map_or(&*body.event_id, |(_, e)| &*e.event_id))?
{
Some(s) => s,
None => services().rooms.state.get_room_shortstatehash(&room_id)?.expect("All rooms have state"),
};
.pdu_shortstatehash(
events_after
.last()
.map_or(&*body.event_id, |(_, e)| &*e.event_id),
)?
.map_or(
services()
.rooms
.state
.get_room_shortstatehash(&room_id)?
.expect("All rooms have state"),
|hash| hash,
);
let state_ids = services().rooms.state_accessor.state_full_ids(shortstatehash).await?;
let state_ids = services()
.rooms
.state_accessor
.state_full_ids(shortstatehash)
.await?;
let end_token = events_after.last().map(|(count, _)| count.stringify()).unwrap_or_else(|| base_token.stringify());
let end_token = events_after
.last()
.map_or_else(|| base_token.stringify(), |(count, _)| count.stringify());
let events_after: Vec<_> = events_after.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect();
let events_after: Vec<_> = events_after
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
let mut state = Vec::new();
for (shortstatekey, id) in state_ids {
let (event_type, state_key) = services().rooms.short.get_statekey_from_short(shortstatekey)?;
let (event_type, state_key) = services()
.rooms
.short
.get_statekey_from_short(shortstatekey)?;
if event_type != StateEventType::RoomMember {
let pdu = match services().rooms.timeline.get_pdu(&id)? {
Some(pdu) => pdu,
None => {
error!("Pdu in state not found: {}", id);
continue;
},
let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else {
error!("Pdu in state not found: {}", id);
continue;
};
state.push(pdu.to_state_event());
} else if !lazy_load_enabled || lazy_loaded.contains(&state_key) {
let pdu = match services().rooms.timeline.get_pdu(&id)? {
Some(pdu) => pdu,
None => {
error!("Pdu in state not found: {}", id);
continue;
},
let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else {
error!("Pdu in state not found: {}", id);
continue;
};
state.push(pdu.to_state_event());
}
}
+19 -7
View File
@@ -16,7 +16,7 @@ pub async fn get_devices_route(body: Ruma<get_devices::v3::Request>) -> Result<g
let devices: Vec<device::Device> = services()
.users
.all_devices_metadata(sender_user)
.filter_map(std::result::Result::ok) // Filter out buggy devices
.filter_map(Result::ok) // Filter out buggy devices
.collect();
Ok(get_devices::v3::Response {
@@ -53,7 +53,9 @@ pub async fn update_device_route(body: Ruma<update_device::v3::Request>) -> Resu
device.display_name.clone_from(&body.display_name);
services().users.update_device_metadata(sender_user, &body.device_id, &device)?;
services()
.users
.update_device_metadata(sender_user, &body.device_id, &device)?;
Ok(update_device::v3::Response {})
}
@@ -84,20 +86,26 @@ pub async fn delete_device_route(body: Ruma<delete_device::v3::Request>) -> Resu
};
if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
let (worked, uiaainfo) = services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked {
return Err(Error::Uiaa(uiaainfo));
}
// Success!
} else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?;
services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo));
} else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
}
services().users.remove_device(sender_user, &body.device_id)?;
services()
.users
.remove_device(sender_user, &body.device_id)?;
Ok(delete_device::v3::Response {})
}
@@ -130,14 +138,18 @@ pub async fn delete_devices_route(body: Ruma<delete_devices::v3::Request>) -> Re
};
if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
let (worked, uiaainfo) = services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked {
return Err(Error::Uiaa(uiaainfo));
}
// Success!
} else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?;
services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo));
} else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
+61 -12
View File
@@ -34,11 +34,20 @@ use crate::{services, Error, Result, Ruma};
pub async fn get_public_rooms_filtered_route(
body: Ruma<get_public_rooms_filtered::v3::Request>,
) -> Result<get_public_rooms_filtered::v3::Response> {
if !services().globals.config.allow_public_room_directory_without_auth {
let _sender_user = body.sender_user.as_ref().expect("user is authenticated");
if let Some(server) = &body.server {
if services()
.globals
.forbidden_remote_room_directory_server_names()
.contains(server)
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
}
get_public_rooms_filtered_helper(
let response = get_public_rooms_filtered_helper(
body.server.as_deref(),
body.limit,
body.since.as_deref(),
@@ -46,6 +55,12 @@ pub async fn get_public_rooms_filtered_route(
&body.room_network,
)
.await
.map_err(|e| {
warn!("Failed to return our /publicRooms: {e}");
Error::BadRequest(ErrorKind::Unknown, "Failed to return this server's public room list.")
})?;
Ok(response)
}
/// # `GET /_matrix/client/v3/publicRooms`
@@ -56,8 +71,17 @@ pub async fn get_public_rooms_filtered_route(
pub async fn get_public_rooms_route(
body: Ruma<get_public_rooms::v3::Request>,
) -> Result<get_public_rooms::v3::Response> {
if !services().globals.config.allow_public_room_directory_without_auth {
let _sender_user = body.sender_user.as_ref().expect("user is authenticated");
if let Some(server) = &body.server {
if services()
.globals
.forbidden_remote_room_directory_server_names()
.contains(server)
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Server is banned on this homeserver.",
));
}
}
let response = get_public_rooms_filtered_helper(
@@ -67,7 +91,11 @@ pub async fn get_public_rooms_route(
&Filter::default(),
&RoomNetwork::Matrix,
)
.await?;
.await
.map_err(|e| {
warn!("Failed to return our /publicRooms: {e}");
Error::BadRequest(ErrorKind::Unknown, "Failed to return this server's public room list.")
})?;
Ok(get_public_rooms::v3::Response {
chunk: response.chunk,
@@ -94,8 +122,21 @@ pub async fn set_room_visibility_route(
match &body.visibility {
room::Visibility::Public => {
if services().globals.config.lockdown_public_room_directory && !services().users.is_admin(sender_user)? {
info!(
"Non-admin user {sender_user} tried to publish {0} to the room directory while \
\"lockdown_public_room_directory\" is enabled",
body.room_id
);
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Publishing rooms to the room directory is not allowed",
));
}
services().rooms.directory.set_public(&body.room_id)?;
info!("{} made {} public", sender_user, body.room_id);
info!("{sender_user} made {0} public", body.room_id);
},
room::Visibility::Private => services().rooms.directory.set_not_public(&body.room_id)?,
_ => {
@@ -213,8 +254,8 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.map_or(Ok(None), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomTopicEventContent| Some(c.topic))
.map_err(|_| {
error!("Invalid room topic event in database for room {}", room_id);
.map_err(|e| {
error!("Invalid room topic event in database for room {room_id}: {e}");
Error::bad_database("Invalid room topic event in database.")
})
})
@@ -228,8 +269,12 @@ pub(crate) async fn get_public_rooms_filtered_helper(
.map(|c: RoomHistoryVisibilityEventContent| {
c.history_visibility == HistoryVisibility::WorldReadable
})
.map_err(|_| Error::bad_database("Invalid room history visibility event in database."))
})?,
.map_err(|e| {
error!(
"Invalid room history visibility event in database for room {room_id}, assuming is \"shared\": {e}",
);
Error::bad_database("Invalid room history visibility event in database.")
})}).unwrap_or(false),
guest_can_join: services()
.rooms
.state_accessor
@@ -320,7 +365,11 @@ pub(crate) async fn get_public_rooms_filtered_helper(
let total_room_count_estimate = (all_rooms.len() as u32).into();
let chunk: Vec<_> = all_rooms.into_iter().skip(num_since as usize).take(limit as usize).collect();
let chunk: Vec<_> = all_rooms
.into_iter()
.skip(num_since as usize)
.take(limit as usize)
.collect();
let prev_batch = if num_since == 0 {
None
+2 -3
View File
@@ -12,9 +12,8 @@ use crate::{services, Error, Result, Ruma};
/// - A user can only access their own filters
pub async fn get_filter_route(body: Ruma<get_filter::v3::Request>) -> Result<get_filter::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let filter = match services().users.get_filter(sender_user, &body.filter_id)? {
Some(filter) => filter,
None => return Err(Error::BadRequest(ErrorKind::NotFound, "Filter not found.")),
let Some(filter) = services().users.get_filter(sender_user, &body.filter_id)? else {
return Err(Error::BadRequest(ErrorKind::NotFound, "Filter not found."));
};
Ok(get_filter::v3::Response::new(filter))
+115 -54
View File
@@ -34,19 +34,29 @@ pub async fn upload_keys_route(body: Ruma<upload_keys::v3::Request>) -> Result<u
let sender_device = body.sender_device.as_ref().expect("user is authenticated");
for (key_key, key_value) in &body.one_time_keys {
services().users.add_one_time_key(sender_user, sender_device, key_key, key_value)?;
services()
.users
.add_one_time_key(sender_user, sender_device, key_key, key_value)?;
}
if let Some(device_keys) = &body.device_keys {
// TODO: merge this and the existing event?
// This check is needed to assure that signatures are kept
if services().users.get_device_keys(sender_user, sender_device)?.is_none() {
services().users.add_device_keys(sender_user, sender_device, device_keys)?;
if services()
.users
.get_device_keys(sender_user, sender_device)?
.is_none()
{
services()
.users
.add_device_keys(sender_user, sender_device, device_keys)?;
}
}
Ok(upload_keys::v3::Response {
one_time_key_counts: services().users.count_one_time_keys(sender_user, sender_device)?,
one_time_key_counts: services()
.users
.count_one_time_keys(sender_user, sender_device)?,
})
}
@@ -104,14 +114,18 @@ pub async fn upload_signing_keys_route(
};
if let Some(auth) = &body.auth {
let (worked, uiaainfo) = services().uiaa.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
let (worked, uiaainfo) = services()
.uiaa
.try_auth(sender_user, sender_device, auth, &uiaainfo)?;
if !worked {
return Err(Error::Uiaa(uiaainfo));
}
// Success!
} else if let Some(json) = body.json_body {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
services().uiaa.create(sender_user, sender_device, &uiaainfo, &json)?;
services()
.uiaa
.create(sender_user, sender_device, &uiaainfo, &json)?;
return Err(Error::Uiaa(uiaainfo));
} else {
return Err(Error::BadRequest(ErrorKind::NotJson, "Not json."));
@@ -151,7 +165,6 @@ pub async fn upload_signatures_route(
.as_object()
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid signature."))?
.clone()
.into_iter()
{
// Signature validation?
let signature = (
@@ -162,7 +175,9 @@ pub async fn upload_signatures_route(
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid signature value."))?
.to_owned(),
);
services().users.sign_key(user_id, key_id, signature, sender_user)?;
services()
.users
.sign_key(user_id, key_id, signature, sender_user)?;
}
}
}
@@ -188,22 +203,39 @@ pub async fn get_key_changes_route(body: Ruma<get_key_changes::v3::Request>) ->
.users
.keys_changed(
sender_user.as_str(),
body.from.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?,
Some(body.to.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?),
body.from
.parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?,
Some(
body.to
.parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?,
),
)
.filter_map(std::result::Result::ok),
.filter_map(Result::ok),
);
for room_id in services().rooms.state_cache.rooms_joined(sender_user).filter_map(std::result::Result::ok) {
for room_id in services()
.rooms
.state_cache
.rooms_joined(sender_user)
.filter_map(Result::ok)
{
device_list_updates.extend(
services()
.users
.keys_changed(
room_id.as_ref(),
body.from.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?,
Some(body.to.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?),
body.from
.parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`."))?,
Some(
body.to
.parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?,
),
)
.filter_map(std::result::Result::ok),
.filter_map(Result::ok),
);
}
Ok(get_key_changes::v3::Response {
@@ -227,7 +259,10 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
let user_id: &UserId = user_id;
if user_id.server_name() != services().globals.server_name() {
get_over_federation.entry(user_id.server_name()).or_insert_with(Vec::new).push((user_id, device_ids));
get_over_federation
.entry(user_id.server_name())
.or_insert_with(Vec::new)
.push((user_id, device_ids));
continue;
}
@@ -252,9 +287,13 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
for device_id in device_ids {
let mut container = BTreeMap::new();
if let Some(mut keys) = services().users.get_device_keys(user_id, device_id)? {
let metadata = services().users.get_device_metadata(user_id, device_id)?.ok_or(
Error::BadRequest(ErrorKind::InvalidParam, "Tried to get keys for nonexistent device."),
)?;
let metadata = services()
.users
.get_device_metadata(user_id, device_id)?
.ok_or(Error::BadRequest(
ErrorKind::InvalidParam,
"Tried to get keys for nonexistent device.",
))?;
add_unsigned_device_display_name(&mut keys, metadata, include_display_names)
.map_err(|_| Error::bad_database("invalid device keys in database"))?;
@@ -264,11 +303,16 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
}
}
if let Some(master_key) = services().users.get_master_key(sender_user, user_id, &allowed_signatures)? {
if let Some(master_key) = services()
.users
.get_master_key(sender_user, user_id, &allowed_signatures)?
{
master_keys.insert(user_id.to_owned(), master_key);
}
if let Some(self_signing_key) =
services().users.get_self_signing_key(sender_user, user_id, &allowed_signatures)?
services()
.users
.get_self_signing_key(sender_user, user_id, &allowed_signatures)?
{
self_signing_keys.insert(user_id.to_owned(), self_signing_key);
}
@@ -282,7 +326,13 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
let mut failures = BTreeMap::new();
let back_off = |id| async {
match services().globals.bad_query_ratelimiter.write().await.entry(id) {
match services()
.globals
.bad_query_ratelimiter
.write()
.await
.entry(id)
{
hash_map::Entry::Vacant(e) => {
e.insert((Instant::now(), 1));
},
@@ -293,7 +343,13 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
let mut futures: FuturesUnordered<_> = get_over_federation
.into_iter()
.map(|(server, vec)| async move {
if let Some((time, tries)) = services().globals.bad_query_ratelimiter.read().await.get(server) {
if let Some((time, tries)) = services()
.globals
.bad_query_ratelimiter
.read()
.await
.get(server)
{
// Exponential backoff
let mut min_elapsed_duration = Duration::from_secs(5 * 60) * (*tries) * (*tries);
if min_elapsed_duration > Duration::from_secs(60 * 60 * 24) {
@@ -313,7 +369,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
(
server,
tokio::time::timeout(
Duration::from_secs(50),
Duration::from_secs(90),
services().sending.send_federation_request(
server,
federation::keys::get_keys::v1::Request {
@@ -323,7 +379,7 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
)
.await
.map_err(|e| {
error!("get_keys_helper query took too long: {}", e);
error!("get_keys_helper query took too long: {e}");
Error::BadServerResponse("get_keys_helper query took too long")
}),
)
@@ -331,43 +387,42 @@ pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
.collect();
while let Some((server, response)) = futures.next().await {
match response {
Ok(Ok(response)) => {
for (user, masterkey) in response.master_keys {
let (master_key_id, mut master_key) = services().users.parse_master_key(&user, &masterkey)?;
if let Ok(Ok(response)) = response {
for (user, masterkey) in response.master_keys {
let (master_key_id, mut master_key) = services().users.parse_master_key(&user, &masterkey)?;
if let Some(our_master_key) =
services().users.get_key(&master_key_id, sender_user, &user, &allowed_signatures)?
{
let (_, our_master_key) = services().users.parse_master_key(&user, &our_master_key)?;
master_key.signatures.extend(our_master_key.signatures);
}
let json = serde_json::to_value(master_key).expect("to_value always works");
let raw = serde_json::from_value(json).expect("Raw::from_value always works");
services().users.add_cross_signing_keys(
&user, &raw, &None, &None,
false, /* Dont notify. A notification would trigger another key request resulting in an
* endless loop */
)?;
master_keys.insert(user, raw);
if let Some(our_master_key) =
services()
.users
.get_key(&master_key_id, sender_user, &user, &allowed_signatures)?
{
let (_, our_master_key) = services().users.parse_master_key(&user, &our_master_key)?;
master_key.signatures.extend(our_master_key.signatures);
}
let json = serde_json::to_value(master_key).expect("to_value always works");
let raw = serde_json::from_value(json).expect("Raw::from_value always works");
services().users.add_cross_signing_keys(
&user, &raw, &None, &None,
false, /* Dont notify. A notification would trigger another key request resulting in an
* endless loop */
)?;
master_keys.insert(user, raw);
}
self_signing_keys.extend(response.self_signing_keys);
device_keys.extend(response.device_keys);
},
_ => {
back_off(server.to_owned()).await;
failures.insert(server.to_string(), json!({}));
},
self_signing_keys.extend(response.self_signing_keys);
device_keys.extend(response.device_keys);
} else {
back_off(server.to_owned()).await;
failures.insert(server.to_string(), json!({}));
}
}
Ok(get_keys::v3::Response {
failures,
device_keys,
master_keys,
self_signing_keys,
user_signing_keys,
device_keys,
failures,
})
}
@@ -405,12 +460,18 @@ pub(crate) async fn claim_keys_helper(
for (user_id, map) in one_time_keys_input {
if user_id.server_name() != services().globals.server_name() {
get_over_federation.entry(user_id.server_name()).or_insert_with(Vec::new).push((user_id, map));
get_over_federation
.entry(user_id.server_name())
.or_insert_with(Vec::new)
.push((user_id, map));
}
let mut container = BTreeMap::new();
for (device_id, key_algorithm) in map {
if let Some(one_time_keys) = services().users.take_one_time_key(user_id, device_id, key_algorithm)? {
if let Some(one_time_keys) = services()
.users
.take_one_time_key(user_id, device_id, key_algorithm)?
{
let mut c = BTreeMap::new();
c.insert(one_time_keys.0, one_time_keys.1);
container.insert(device_id.clone(), c);
+151 -96
View File
@@ -1,9 +1,10 @@
use std::{io::Cursor, net::IpAddr, sync::Arc, time::Duration};
use std::{io::Cursor, sync::Arc, time::Duration};
use image::io::Reader as ImgReader;
use ipaddress::IPAddress;
use reqwest::Url;
use ruma::api::client::{
error::ErrorKind,
error::{ErrorKind, RetryAfter},
media::{
create_content, get_content, get_content_as_filename, get_content_thumbnail, get_media_config,
get_media_preview,
@@ -55,7 +56,7 @@ pub async fn get_media_preview_route(
) -> Result<get_media_preview::v3::Response> {
let url = &body.url;
if !url_preview_allowed(url) {
return Err(Error::BadRequest(ErrorKind::Forbidden, "URL is not allowed to be previewed"));
return Err(Error::BadRequest(ErrorKind::forbidden(), "URL is not allowed to be previewed"));
}
match get_url_preview(url).await {
@@ -64,7 +65,7 @@ pub async fn get_media_preview_route(
error!("Failed to convert UrlPreviewData into a serde json value: {}", e);
Error::BadRequest(
ErrorKind::LimitExceeded {
retry_after_ms: Some(Duration::from_secs(5)),
retry_after: Some(RetryAfter::Delay(Duration::from_secs(5))),
},
"Failed to generate a URL preview, try again later.",
)
@@ -79,7 +80,7 @@ pub async fn get_media_preview_route(
// the only response codes in the preview_url spec page are 200 and 429.
Err(Error::BadRequest(
ErrorKind::LimitExceeded {
retry_after_ms: Some(Duration::from_secs(5)),
retry_after: Some(RetryAfter::Delay(Duration::from_secs(5))),
},
"Failed to generate a URL preview, try again later.",
))
@@ -99,7 +100,7 @@ pub async fn get_media_preview_v1_route(
) -> Result<RumaResponse<get_media_preview::v3::Response>> {
let url = &body.url;
if !url_preview_allowed(url) {
return Err(Error::BadRequest(ErrorKind::Forbidden, "URL is not allowed to be previewed"));
return Err(Error::BadRequest(ErrorKind::forbidden(), "URL is not allowed to be previewed"));
}
match get_url_preview(url).await {
@@ -108,7 +109,7 @@ pub async fn get_media_preview_v1_route(
error!("Failed to convert UrlPreviewData into a serde json value: {}", e);
Error::BadRequest(
ErrorKind::LimitExceeded {
retry_after_ms: Some(Duration::from_secs(5)),
retry_after: Some(RetryAfter::Delay(Duration::from_secs(5))),
},
"Failed to generate a URL preview, try again later.",
)
@@ -123,7 +124,7 @@ pub async fn get_media_preview_v1_route(
// the only response codes in the preview_url spec page are 200 and 429.
Err(Error::BadRequest(
ErrorKind::LimitExceeded {
retry_after_ms: Some(Duration::from_secs(5)),
retry_after: Some(RetryAfter::Delay(Duration::from_secs(5))),
},
"Failed to generate a URL preview, try again later.",
))
@@ -151,7 +152,10 @@ pub async fn create_content_route(body: Ruma<create_content::v3::Request>) -> Re
.create(
Some(sender_user.clone()),
mxc.clone(),
body.filename.as_ref().map(|filename| "inline; filename=".to_owned() + filename).as_deref(),
body.filename
.as_ref()
.map(|filename| "inline; filename=".to_owned() + filename)
.as_deref(),
body.content_type.as_deref(),
&body.file,
)
@@ -191,7 +195,10 @@ pub async fn create_content_v1_route(
.create(
Some(sender_user.clone()),
mxc.clone(),
body.filename.as_ref().map(|filename| "inline; filename=".to_owned() + filename).as_deref(),
body.filename
.as_ref()
.map(|filename| "inline; filename=".to_owned() + filename)
.as_deref(),
body.content_type.as_deref(),
&body.file,
)
@@ -212,7 +219,11 @@ pub async fn get_remote_content(
) -> Result<get_content::v3::Response, Error> {
// we'll lie to the client and say the blocked server's media was not found and
// log. the client has no way of telling anyways so this is a security bonus.
if services().globals.prevent_media_downloads_from().contains(&server_name.to_owned()) {
if services()
.globals
.prevent_media_downloads_from()
.contains(&server_name.to_owned())
{
info!(
"Received request for remote media `{}` but server is in our media server blocklist. Returning 404.",
mxc
@@ -270,6 +281,7 @@ pub async fn get_content_route(body: Ruma<get_content::v3::Request>) -> Result<g
content_type,
content_disposition,
cross_origin_resource_policy: Some("cross-origin".to_owned()),
cache_control: Some("public, max-age=31536000, immutable".to_owned()),
})
} else if &*body.server_name != services().globals.server_name() && body.allow_remote {
let remote_content_response = get_remote_content(
@@ -314,6 +326,7 @@ pub async fn get_content_v1_route(
content_type,
content_disposition,
cross_origin_resource_policy: Some("cross-origin".to_owned()),
cache_control: Some("public, max-age=31536000, immutable".to_owned()),
}
.into())
} else if &*body.server_name != services().globals.server_name() && body.allow_remote {
@@ -355,6 +368,7 @@ pub async fn get_content_as_filename_route(
content_type,
content_disposition: Some(format!("inline; filename={}", body.filename)),
cross_origin_resource_policy: Some("cross-origin".to_owned()),
cache_control: Some("public, max-age=31536000, immutable".to_owned()),
})
} else if &*body.server_name != services().globals.server_name() && body.allow_remote {
let remote_content_response = get_remote_content(
@@ -371,6 +385,7 @@ pub async fn get_content_as_filename_route(
content_type: remote_content_response.content_type,
file: remote_content_response.file,
cross_origin_resource_policy: Some("cross-origin".to_owned()),
cache_control: Some("public, max-age=31536000, immutable".to_owned()),
})
} else {
Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
@@ -405,6 +420,7 @@ pub async fn get_content_as_filename_v1_route(
content_type,
content_disposition: Some(format!("inline; filename={}", body.filename)),
cross_origin_resource_policy: Some("cross-origin".to_owned()),
cache_control: Some("public, max-age=31536000, immutable".to_owned()),
}
.into())
} else if &*body.server_name != services().globals.server_name() && body.allow_remote {
@@ -422,6 +438,7 @@ pub async fn get_content_as_filename_v1_route(
content_type: remote_content_response.content_type,
file: remote_content_response.file,
cross_origin_resource_policy: Some("cross-origin".to_owned()),
cache_control: Some("public, max-age=31536000, immutable".to_owned()),
}
.into())
} else {
@@ -450,8 +467,12 @@ pub async fn get_content_thumbnail_route(
.media
.get_thumbnail(
mxc.clone(),
body.width.try_into().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?,
body.height.try_into().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Height is invalid."))?,
body.width
.try_into()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?,
body.height
.try_into()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Height is invalid."))?,
)
.await?
{
@@ -459,11 +480,16 @@ pub async fn get_content_thumbnail_route(
file,
content_type,
cross_origin_resource_policy: Some("cross-origin".to_owned()),
cache_control: Some("public, max-age=31536000, immutable".to_owned()),
})
} else if &*body.server_name != services().globals.server_name() && body.allow_remote {
// we'll lie to the client and say the blocked server's media was not found and
// log. the client has no way of telling anyways so this is a security bonus.
if services().globals.prevent_media_downloads_from().contains(&body.server_name.clone()) {
if services()
.globals
.prevent_media_downloads_from()
.contains(&body.server_name.clone())
{
info!(
"Received request for remote media `{}` but server is in our media server blocklist. Returning 404.",
mxc
@@ -532,8 +558,12 @@ pub async fn get_content_thumbnail_v1_route(
.media
.get_thumbnail(
mxc.clone(),
body.width.try_into().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?,
body.height.try_into().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Height is invalid."))?,
body.width
.try_into()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?,
body.height
.try_into()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Height is invalid."))?,
)
.await?
{
@@ -541,12 +571,17 @@ pub async fn get_content_thumbnail_v1_route(
file,
content_type,
cross_origin_resource_policy: Some("cross-origin".to_owned()),
cache_control: Some("public, max-age=31536000, immutable".to_owned()),
}
.into())
} else if &*body.server_name != services().globals.server_name() && body.allow_remote {
// we'll lie to the client and say the blocked server's media was not found and
// log. the client has no way of telling anyways so this is a security bonus.
if services().globals.prevent_media_downloads_from().contains(&body.server_name.clone()) {
if services()
.globals
.prevent_media_downloads_from()
.contains(&body.server_name.clone())
{
info!(
"Received request for remote media `{}` but server is in our media server blocklist. Returning 404.",
mxc
@@ -598,7 +633,10 @@ async fn download_image(client: &reqwest::Client, url: &str) -> Result<UrlPrevie
utils::random_string(MXC_LENGTH)
);
services().media.create(None, mxc.clone(), None, None, &image).await?;
services()
.media
.create(None, mxc.clone(), None, None, &image)
.await?;
let (width, height) = match ImgReader::new(Cursor::new(&image)).with_guessed_format() {
Err(_) => (None, None),
@@ -634,9 +672,8 @@ async fn download_html(client: &reqwest::Client, url: &str) -> Result<UrlPreview
}
}
let body = String::from_utf8_lossy(&bytes);
let html = match HTML::from_string(body.to_string(), Some(url.to_owned())) {
Ok(html) => html,
Err(_) => return Err(Error::BadRequest(ErrorKind::Unknown, "Failed to parse HTML")),
let Ok(html) = HTML::from_string(body.to_string(), Some(url.to_owned())) else {
return Err(Error::BadRequest(ErrorKind::Unknown, "Failed to parse HTML"));
};
let mut data = match html.opengraph.images.first() {
@@ -653,77 +690,58 @@ async fn download_html(client: &reqwest::Client, url: &str) -> Result<UrlPreview
Ok(data)
}
fn url_request_allowed(addr: &IpAddr) -> bool {
// TODO: make this check ip_range_denylist
// could be implemented with reqwest when it supports IP filtering:
// https://github.com/seanmonstar/reqwest/issues/1515
// These checks have been taken from the Rust core/net/ipaddr.rs crate,
// IpAddr::V4.is_global() and IpAddr::V6.is_global(), as .is_global is not
// yet stabilized. TODO: Once this is stable, this match can be simplified.
match addr {
IpAddr::V4(ip4) => {
!(ip4.octets()[0] == 0 // "This network"
|| ip4.is_private()
|| (ip4.octets()[0] == 100 && (ip4.octets()[1] & 0b1100_0000 == 0b0100_0000)) // is_shared()
|| ip4.is_loopback()
|| ip4.is_link_local()
// addresses reserved for future protocols (`192.0.0.0/24`)
|| (ip4.octets()[0] == 192 && ip4.octets()[1] == 0 && ip4.octets()[2] == 0)
|| ip4.is_documentation()
|| (ip4.octets()[0] == 198 && (ip4.octets()[1] & 0xfe) == 18) // is_benchmarking()
|| (ip4.octets()[0] & 240 == 240 && !ip4.is_broadcast()) // is_reserved()
|| ip4.is_broadcast())
},
IpAddr::V6(ip6) => {
!(ip6.is_unspecified()
|| ip6.is_loopback()
// IPv4-mapped Address (`::ffff:0:0/96`)
|| matches!(ip6.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
// IPv4-IPv6 Translat. (`64:ff9b:1::/48`)
|| matches!(ip6.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
// Discard-Only Address Block (`100::/64`)
|| matches!(ip6.segments(), [0x100, 0, 0, 0, _, _, _, _])
// IETF Protocol Assignments (`2001::/23`)
|| (matches!(ip6.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
&& !(
// Port Control Protocol Anycast (`2001:1::1`)
u128::from_be_bytes(ip6.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
// Traversal Using Relays around NAT Anycast (`2001:1::2`)
|| u128::from_be_bytes(ip6.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
// AMT (`2001:3::/32`)
|| matches!(ip6.segments(), [0x2001, 3, _, _, _, _, _, _])
// AS112-v6 (`2001:4:112::/48`)
|| matches!(ip6.segments(), [0x2001, 4, 0x112, _, _, _, _, _])
// ORCHIDv2 (`2001:20::/28`)
|| matches!(ip6.segments(), [0x2001, b, _, _, _, _, _, _] if (0x20..=0x2F).contains(&b))
))
|| ((ip6.segments()[0] == 0x2001) && (ip6.segments()[1] == 0xdb8)) // is_documentation()
|| ((ip6.segments()[0] & 0xfe00) == 0xfc00) // is_unique_local()
|| ((ip6.segments()[0] & 0xffc0) == 0xfe80)) // is_unicast_link_local
},
}
}
async fn request_url_preview(url: &str) -> Result<UrlPreviewData> {
let client = services().globals.url_preview_client();
if let Ok(ip) = IPAddress::parse(url) {
let cidr_ranges_s = services().globals.ip_range_denylist().to_vec();
let mut cidr_ranges: Vec<IPAddress> = Vec::new();
for cidr in cidr_ranges_s {
cidr_ranges.push(IPAddress::parse(cidr).expect("we checked this at startup"));
}
for cidr in cidr_ranges {
if cidr.includes(&ip) {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Requesting from this address is forbidden",
));
}
}
}
let client = &services().globals.client.url_preview;
let response = client.head(url).send().await?;
if !response.remote_addr().map_or(false, |a| url_request_allowed(&a.ip())) {
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Requesting from this address is forbidden",
));
if let Some(remote_addr) = response.remote_addr() {
if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) {
let cidr_ranges_s = services().globals.ip_range_denylist().to_vec();
let mut cidr_ranges: Vec<IPAddress> = Vec::new();
for cidr in cidr_ranges_s {
cidr_ranges.push(IPAddress::parse(cidr).expect("we checked this at startup"));
}
for cidr in cidr_ranges {
if cidr.includes(&ip) {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Requesting from this address is forbidden",
));
}
}
}
}
let content_type = match response.headers().get(reqwest::header::CONTENT_TYPE).and_then(|x| x.to_str().ok()) {
Some(ct) => ct,
None => return Err(Error::BadRequest(ErrorKind::Unknown, "Unknown Content-Type")),
let Some(content_type) = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|x| x.to_str().ok())
else {
return Err(Error::BadRequest(ErrorKind::Unknown, "Unknown Content-Type"));
};
let data = match content_type {
html if html.starts_with("text/html") => download_html(&client, url).await?,
img if img.starts_with("image/") => download_image(&client, url).await?,
html if html.starts_with("text/html") => download_html(client, url).await?,
img if img.starts_with("image/") => download_image(client, url).await?,
_ => return Err(Error::BadRequest(ErrorKind::Unknown, "Unsupported Content-Type")),
};
@@ -738,7 +756,15 @@ async fn get_url_preview(url: &str) -> Result<UrlPreviewData> {
}
// ensure that only one request is made per URL
let mutex_request = Arc::clone(services().media.url_preview_mutex.write().await.entry(url.to_owned()).or_default());
let mutex_request = Arc::clone(
services()
.media
.url_preview_mutex
.write()
.await
.entry(url.to_owned())
.or_default(),
);
let _request_lock = mutex_request.lock().await;
match services().media.get_url_preview(url).await {
@@ -756,7 +782,10 @@ fn url_preview_allowed(url_str: &str) -> bool {
},
};
if ["http", "https"].iter().all(|&scheme| scheme != url.scheme().to_lowercase()) {
if ["http", "https"]
.iter()
.all(|&scheme| scheme != url.scheme().to_lowercase())
{
debug!("Ignoring non-HTTP/HTTPS URL to preview: {}", url);
return false;
}
@@ -771,6 +800,7 @@ fn url_preview_allowed(url_str: &str) -> bool {
let allowlist_domain_contains = services().globals.url_preview_domain_contains_allowlist();
let allowlist_domain_explicit = services().globals.url_preview_domain_explicit_allowlist();
let denylist_domain_explicit = services().globals.url_preview_domain_explicit_denylist();
let allowlist_url_contains = services().globals.url_preview_url_contains_allowlist();
if allowlist_domain_contains.contains(&"*".to_owned())
@@ -782,18 +812,32 @@ fn url_preview_allowed(url_str: &str) -> bool {
}
if !host.is_empty() {
if denylist_domain_explicit.contains(&host) {
debug!(
"Host {} is not allowed by url_preview_domain_explicit_denylist (check 1/4)",
&host
);
return false;
}
if allowlist_domain_explicit.contains(&host) {
debug!("Host {} is allowed by url_preview_domain_explicit_allowlist (check 1/3)", &host);
debug!("Host {} is allowed by url_preview_domain_explicit_allowlist (check 2/4)", &host);
return true;
}
if allowlist_domain_contains.iter().any(|domain_s| domain_s.contains(&host.clone())) {
debug!("Host {} is allowed by url_preview_domain_contains_allowlist (check 2/3)", &host);
if allowlist_domain_contains
.iter()
.any(|domain_s| domain_s.contains(&host.clone()))
{
debug!("Host {} is allowed by url_preview_domain_contains_allowlist (check 3/4)", &host);
return true;
}
if allowlist_url_contains.iter().any(|url_s| url.to_string().contains(&url_s.to_string())) {
debug!("URL {} is allowed by url_preview_url_contains_allowlist (check 3/3)", &host);
if allowlist_url_contains
.iter()
.any(|url_s| url.to_string().contains(&url_s.to_string()))
{
debug!("URL {} is allowed by url_preview_url_contains_allowlist (check 4/4)", &host);
return true;
}
@@ -803,17 +847,28 @@ fn url_preview_allowed(url_str: &str) -> bool {
match host.split_once('.') {
None => return false,
Some((_, root_domain)) => {
if allowlist_domain_explicit.contains(&root_domain.to_owned()) {
if denylist_domain_explicit.contains(&root_domain.to_owned()) {
debug!(
"Root domain {} is allowed by url_preview_domain_explicit_allowlist (check 1/3)",
"Root domain {} is not allowed by url_preview_domain_explicit_denylist (check 1/3)",
&root_domain
);
return true;
}
if allowlist_domain_contains.iter().any(|domain_s| domain_s.contains(&root_domain.to_owned())) {
if allowlist_domain_explicit.contains(&root_domain.to_owned()) {
debug!(
"Root domain {} is allowed by url_preview_domain_contains_allowlist (check 2/3)",
"Root domain {} is allowed by url_preview_domain_explicit_allowlist (check 2/3)",
&root_domain
);
return true;
}
if allowlist_domain_contains
.iter()
.any(|domain_s| domain_s.contains(&root_domain.to_owned()))
{
debug!(
"Root domain {} is allowed by url_preview_domain_contains_allowlist (check 3/3)",
&root_domain
);
return true;
File diff suppressed because it is too large Load Diff
+112 -107
View File
@@ -6,15 +6,17 @@ use std::{
use ruma::{
api::client::{
error::ErrorKind,
filter::{RoomEventFilter, UrlFilter},
message::{get_message_events, send_message_event},
},
events::{StateEventType, TimelineEventType},
events::{MessageLikeEventType, StateEventType},
RoomId, UserId,
};
use serde_json::from_str;
use serde_json::{from_str, Value};
use crate::{
service::{pdu::PduBuilder, rooms::timeline::PduCount},
services, utils, Error, Result, Ruma,
services, utils, Error, PduEvent, Result, Ruma,
};
/// # `PUT /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId}`
@@ -32,65 +34,36 @@ pub async fn send_message_event_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let sender_device = body.sender_device.as_deref();
let mutex_state =
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(body.room_id.clone()).or_default());
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(body.room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
// Forbid m.room.encrypted if encryption is disabled
if TimelineEventType::RoomEncrypted == body.event_type.to_string().into() && !services().globals.allow_encryption()
{
return Err(Error::BadRequest(ErrorKind::Forbidden, "Encryption has been disabled"));
if MessageLikeEventType::RoomEncrypted == body.event_type && !services().globals.allow_encryption() {
return Err(Error::BadRequest(ErrorKind::forbidden(), "Encryption has been disabled"));
}
// certain event types require certain fields to be valid in request bodies.
// this helps prevent attempting to handle events that we can't deserialise
// later so don't waste resources on it.
//
// see https://spec.matrix.org/v1.9/client-server-api/#events-2 for what's required per event type.
match body.event_type.to_string().into() {
TimelineEventType::RoomMessage => {
let body_field = body.body.body.get_field::<String>("body");
let msgtype_field = body.body.body.get_field::<String>("msgtype");
if body_field.is_err() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"'body' field in JSON request is invalid",
));
}
if msgtype_field.is_err() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"'msgtype' field in JSON request is invalid",
));
}
},
TimelineEventType::RoomName => {
let name_field = body.body.body.get_field::<String>("name");
if name_field.is_err() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"'name' field in JSON request is invalid",
));
}
},
TimelineEventType::RoomTopic => {
let topic_field = body.body.body.get_field::<String>("topic");
if topic_field.is_err() {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"'topic' field in JSON request is invalid",
));
}
},
_ => {}, // event may be custom/experimental or can be empty don't do anything with it
};
if body.event_type == MessageLikeEventType::CallInvite
&& services().rooms.directory.is_public_room(&body.room_id)?
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Room call invites are not allowed in public rooms",
));
}
// Check if this is a new transaction id
if let Some(response) = services().transaction_ids.existing_txnid(sender_user, sender_device, &body.txn_id)? {
if let Some(response) = services()
.transaction_ids
.existing_txnid(sender_user, sender_device, &body.txn_id)?
{
// The client might have sent a txnid of the /sendToDevice endpoint
// This txnid has no response associated with it
if response.is_empty() {
@@ -130,7 +103,9 @@ pub async fn send_message_event_route(
)
.await?;
services().transaction_ids.add_txnid(sender_user, sender_device, &body.txn_id, event_id.as_bytes())?;
services()
.transaction_ids
.add_txnid(sender_user, sender_device, &body.txn_id, event_id.as_bytes())?;
drop(state_lock);
@@ -143,7 +118,7 @@ pub async fn send_message_event_route(
///
/// - Only works if the user is joined (TODO: always allow, but only show events
/// where the user was
/// joined, depending on history_visibility)
/// joined, depending on `history_visibility`)
pub async fn get_message_events_route(
body: Ruma<get_message_events::v3::Request>,
) -> Result<get_message_events::v3::Response> {
@@ -158,9 +133,16 @@ pub async fn get_message_events_route(
},
};
let to = body.to.as_ref().and_then(|t| PduCount::try_from_string(t).ok());
let to = body
.to
.as_ref()
.and_then(|t| PduCount::try_from_string(t).ok());
services().rooms.lazy_loading.lazy_load_confirm_delivery(sender_user, sender_device, &body.room_id, from).await?;
services()
.rooms
.lazy_loading
.lazy_load_confirm_delivery(sender_user, sender_device, &body.room_id, from)
.await?;
let limit = u64::from(body.limit).min(100) as usize;
@@ -176,79 +158,83 @@ pub async fn get_message_events_route(
.rooms
.timeline
.pdus_after(sender_user, &body.room_id, from)?
.take(limit)
.filter_map(std::result::Result::ok) // Filter out buggy events
.filter(|(_, pdu)| {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &body.room_id, &pdu.event_id)
.unwrap_or(false)
})
.filter_map(Result::ok) // Filter out buggy events
.filter(|(_, pdu)| contains_url_filter(pdu, &body.filter))
.filter(|(_, pdu)| visibility_filter(pdu, sender_user, &body.room_id))
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
.take(limit)
.collect();
for (_, event) in &events_after {
/* TODO: Remove this when these are resolved:
/* TODO: Remove the not "element_hacks" check when these are resolved:
* https://github.com/vector-im/element-android/issues/3417
* https://github.com/vector-im/element-web/issues/21034
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
sender_user,
sender_device,
&body.room_id,
&event.sender,
)? {
*/
if !cfg!(feature = "element_hacks")
&& !services().rooms.lazy_loading.lazy_load_was_sent_before(
sender_user,
sender_device,
&body.room_id,
&event.sender,
)? {
lazy_loaded.insert(event.sender.clone());
}
*/
lazy_loaded.insert(event.sender.clone());
}
next_token = events_after.last().map(|(count, _)| count).copied();
let events_after: Vec<_> = events_after.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect();
let events_after: Vec<_> = events_after
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
resp.start = from.stringify();
resp.end = next_token.map(|count| count.stringify());
resp.chunk = events_after;
},
ruma::api::Direction::Backward => {
services().rooms.timeline.backfill_if_required(&body.room_id, from).await?;
services()
.rooms
.timeline
.backfill_if_required(&body.room_id, from)
.await?;
let events_before: Vec<_> = services()
.rooms
.timeline
.pdus_until(sender_user, &body.room_id, from)?
.take(limit)
.filter_map(std::result::Result::ok) // Filter out buggy events
.filter(|(_, pdu)| {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &body.room_id, &pdu.event_id)
.unwrap_or(false)
})
.filter_map(Result::ok) // Filter out buggy events
.filter(|(_, pdu)| contains_url_filter(pdu, &body.filter))
.filter(|(_, pdu)| visibility_filter(pdu, sender_user, &body.room_id))
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
.take(limit)
.collect();
for (_, event) in &events_before {
/* TODO: Remove this when these are resolved:
/* TODO: Remove the not "element_hacks" check when these are resolved:
* https://github.com/vector-im/element-android/issues/3417
* https://github.com/vector-im/element-web/issues/21034
if !services().rooms.lazy_loading.lazy_load_was_sent_before(
sender_user,
sender_device,
&body.room_id,
&event.sender,
)? {
*/
if !cfg!(feature = "element_hacks")
&& !services().rooms.lazy_loading.lazy_load_was_sent_before(
sender_user,
sender_device,
&body.room_id,
&event.sender,
)? {
lazy_loaded.insert(event.sender.clone());
}
*/
lazy_loaded.insert(event.sender.clone());
}
next_token = events_before.last().map(|(count, _)| count).copied();
let events_before: Vec<_> = events_before.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect();
let events_before: Vec<_> = events_before
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect();
resp.start = from.stringify();
resp.end = next_token.map(|count| count.stringify());
@@ -267,18 +253,37 @@ pub async fn get_message_events_route(
}
}
// TODO: enable again when we are sure clients can handle it
/*
if let Some(next_token) = next_token {
services().rooms.lazy_loading.lazy_load_mark_sent(
sender_user,
sender_device,
&body.room_id,
lazy_loaded,
next_token,
).await;
// remove the feature check when we are sure clients like element can handle it
if !cfg!(feature = "element_hacks") {
if let Some(next_token) = next_token {
services()
.rooms
.lazy_loading
.lazy_load_mark_sent(sender_user, sender_device, &body.room_id, lazy_loaded, next_token)
.await;
}
}
*/
Ok(resp)
}
fn visibility_filter(pdu: &PduEvent, user_id: &UserId, room_id: &RoomId) -> bool {
services()
.rooms
.state_accessor
.user_can_see_event(user_id, room_id, &pdu.event_id)
.unwrap_or(false)
}
fn contains_url_filter(pdu: &PduEvent, filter: &RoomEventFilter) -> bool {
if filter.url_filter.is_none() {
return true;
}
let content: Value = from_str(pdu.content.get()).unwrap();
match filter.url_filter {
Some(UrlFilter::EventsWithoutUrl) => !content["url"].is_string(),
Some(UrlFilter::EventsWithUrl) => content["url"].is_string(),
None => true,
}
}
+2
View File
@@ -29,6 +29,7 @@ mod thirdparty;
mod threads;
mod to_device;
mod typing;
mod unstable;
mod unversioned;
mod user_directory;
mod voip;
@@ -64,6 +65,7 @@ pub use thirdparty::*;
pub use threads::*;
pub use to_device::*;
pub use typing::*;
pub use unstable::*;
pub use unversioned::*;
pub use user_directory::*;
pub use voip::*;
+15 -19
View File
@@ -12,22 +12,13 @@ use crate::{services, Error, Result, Ruma};
/// Sets the presence state of the sender user.
pub async fn set_presence_route(body: Ruma<set_presence::v3::Request>) -> Result<set_presence::v3::Response> {
if !services().globals.allow_local_presence() {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Presence is disabled on this server"));
return Err(Error::BadRequest(ErrorKind::forbidden(), "Presence is disabled on this server"));
}
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
for room_id in services().rooms.state_cache.rooms_joined(sender_user) {
let room_id = room_id?;
services().rooms.edus.presence.set_presence(
&room_id,
sender_user,
body.presence.clone(),
None,
None,
body.status_msg.clone(),
)?;
}
services()
.presence
.set_presence(sender_user, &body.presence, None, None, body.status_msg.clone())?;
Ok(set_presence::v3::Response {})
}
@@ -39,17 +30,19 @@ pub async fn set_presence_route(body: Ruma<set_presence::v3::Request>) -> Result
/// - Only works if you share a room with the user
pub async fn get_presence_route(body: Ruma<get_presence::v3::Request>) -> Result<get_presence::v3::Response> {
if !services().globals.allow_local_presence() {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Presence is disabled on this server"));
return Err(Error::BadRequest(ErrorKind::forbidden(), "Presence is disabled on this server"));
}
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let mut presence_event = None;
for room_id in services().rooms.user.get_shared_rooms(vec![sender_user.clone(), body.user_id.clone()])? {
let room_id = room_id?;
if let Some(presence) = services().rooms.edus.presence.get_presence(&room_id, sender_user)? {
for _room_id in services()
.rooms
.user
.get_shared_rooms(vec![sender_user.clone(), body.user_id.clone()])?
{
if let Some(presence) = services().presence.get_presence(sender_user)? {
presence_event = Some(presence);
break;
}
@@ -60,7 +53,10 @@ pub async fn get_presence_route(body: Ruma<get_presence::v3::Request>) -> Result
// TODO: Should ruma just use the presenceeventcontent type here?
status_msg: presence.content.status_msg,
currently_active: presence.content.currently_active,
last_active_ago: presence.content.last_active_ago.map(|millis| Duration::from_millis(millis.into())),
last_active_ago: presence
.content
.last_active_ago
.map(|millis| Duration::from_millis(millis.into())),
presence: presence.content.presence,
})
} else {
+92 -28
View File
@@ -25,20 +25,24 @@ pub async fn set_displayname_route(
) -> Result<set_display_name::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().users.set_displayname(sender_user, body.displayname.clone()).await?;
services()
.users
.set_displayname(sender_user, body.displayname.clone())
.await?;
// Send a new membership event and presence update into all joined rooms
let all_rooms_joined: Vec<_> = services()
.rooms
.state_cache
.rooms_joined(sender_user)
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.map(|room_id| {
Ok::<_, Error>((
PduBuilder {
event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent {
displayname: body.displayname.clone(),
join_authorized_via_users_server: None,
..serde_json::from_str(
services()
.rooms
@@ -60,20 +64,33 @@ pub async fn set_displayname_route(
room_id,
))
})
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.collect();
for (pdu_builder, room_id) in all_rooms_joined {
let mutex_state =
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default());
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
let _ = services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await;
_ = services()
.rooms
.timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await;
}
if services().globals.allow_local_presence() {
// Presence update
services().rooms.edus.presence.ping_presence(sender_user, PresenceState::Online)?;
services()
.presence
.ping_presence(sender_user, &PresenceState::Online)?;
}
Ok(set_display_name::v3::Response {})
@@ -105,9 +122,18 @@ pub async fn get_displayname_route(
services().users.create(&body.user_id, None)?;
}
services().users.set_displayname(&body.user_id, response.displayname.clone()).await?;
services().users.set_avatar_url(&body.user_id, response.avatar_url.clone()).await?;
services().users.set_blurhash(&body.user_id, response.blurhash.clone()).await?;
services()
.users
.set_displayname(&body.user_id, response.displayname.clone())
.await?;
services()
.users
.set_avatar_url(&body.user_id, response.avatar_url.clone())
.await?;
services()
.users
.set_blurhash(&body.user_id, response.blurhash.clone())
.await?;
return Ok(get_display_name::v3::Response {
displayname: response.displayname,
@@ -126,30 +152,37 @@ pub async fn get_displayname_route(
})
}
/// # `PUT /_matrix/client/r0/profile/{userId}/avatar_url`
/// # `PUT /_matrix/client/v3/profile/{userId}/avatar_url`
///
/// Updates the avatar_url and blurhash.
/// Updates the `avatar_url` and `blurhash`.
///
/// - Also makes sure other users receive the update using presence EDUs
pub async fn set_avatar_url_route(body: Ruma<set_avatar_url::v3::Request>) -> Result<set_avatar_url::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().users.set_avatar_url(sender_user, body.avatar_url.clone()).await?;
services()
.users
.set_avatar_url(sender_user, body.avatar_url.clone())
.await?;
services().users.set_blurhash(sender_user, body.blurhash.clone()).await?;
services()
.users
.set_blurhash(sender_user, body.blurhash.clone())
.await?;
// Send a new membership event and presence update into all joined rooms
let all_joined_rooms: Vec<_> = services()
.rooms
.state_cache
.rooms_joined(sender_user)
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.map(|room_id| {
Ok::<_, Error>((
PduBuilder {
event_type: TimelineEventType::RoomMember,
content: to_raw_value(&RoomMemberEventContent {
avatar_url: body.avatar_url.clone(),
join_authorized_via_users_server: None,
..serde_json::from_str(
services()
.rooms
@@ -171,20 +204,33 @@ pub async fn set_avatar_url_route(body: Ruma<set_avatar_url::v3::Request>) -> Re
room_id,
))
})
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.collect();
for (pdu_builder, room_id) in all_joined_rooms {
let mutex_state =
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default());
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
let _ = services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await;
_ = services()
.rooms
.timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await;
}
if services().globals.allow_local_presence() {
// Presence update
services().rooms.edus.presence.ping_presence(sender_user, PresenceState::Online)?;
services()
.presence
.ping_presence(sender_user, &PresenceState::Online)?;
}
Ok(set_avatar_url::v3::Response {})
@@ -192,10 +238,10 @@ pub async fn set_avatar_url_route(body: Ruma<set_avatar_url::v3::Request>) -> Re
/// # `GET /_matrix/client/v3/profile/{userId}/avatar_url`
///
/// Returns the avatar_url and blurhash of the user.
/// Returns the `avatar_url` and `blurhash` of the user.
///
/// - If user is on another server and we do not have a local copy already
/// fetch avatar_url and blurhash over federation
/// fetch `avatar_url` and blurhash over federation
pub async fn get_avatar_url_route(body: Ruma<get_avatar_url::v3::Request>) -> Result<get_avatar_url::v3::Response> {
if body.user_id.server_name() != services().globals.server_name() {
// Create and update our local copy of the user
@@ -214,9 +260,18 @@ pub async fn get_avatar_url_route(body: Ruma<get_avatar_url::v3::Request>) -> Re
services().users.create(&body.user_id, None)?;
}
services().users.set_displayname(&body.user_id, response.displayname.clone()).await?;
services().users.set_avatar_url(&body.user_id, response.avatar_url.clone()).await?;
services().users.set_blurhash(&body.user_id, response.blurhash.clone()).await?;
services()
.users
.set_displayname(&body.user_id, response.displayname.clone())
.await?;
services()
.users
.set_avatar_url(&body.user_id, response.avatar_url.clone())
.await?;
services()
.users
.set_blurhash(&body.user_id, response.blurhash.clone())
.await?;
return Ok(get_avatar_url::v3::Response {
avatar_url: response.avatar_url,
@@ -261,9 +316,18 @@ pub async fn get_profile_route(body: Ruma<get_profile::v3::Request>) -> Result<g
services().users.create(&body.user_id, None)?;
}
services().users.set_displayname(&body.user_id, response.displayname.clone()).await?;
services().users.set_avatar_url(&body.user_id, response.avatar_url.clone()).await?;
services().users.set_blurhash(&body.user_id, response.blurhash.clone()).await?;
services()
.users
.set_displayname(&body.user_id, response.displayname.clone())
.await?;
services()
.users
.set_avatar_url(&body.user_id, response.avatar_url.clone())
.await?;
services()
.users
.set_blurhash(&body.user_id, response.blurhash.clone())
.await?;
return Ok(get_profile::v3::Response {
displayname: response.displayname,
+58 -18
View File
@@ -7,12 +7,12 @@ use ruma::{
},
},
events::{push_rules::PushRulesEvent, GlobalAccountDataEventType},
push::{InsertPushRuleError, RemovePushRuleError},
push::{InsertPushRuleError, RemovePushRuleError, Ruleset},
};
use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/r0/pushrules`
/// # `GET /_matrix/client/r0/pushrules/`
///
/// Retrieves the push rules event for this user.
pub async fn get_pushrules_all_route(
@@ -20,18 +20,36 @@ pub async fn get_pushrules_all_route(
) -> Result<get_pushrules_all::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services()
.account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?
.ok_or(Error::BadRequest(ErrorKind::NotFound, "PushRules event not found."))?;
let event =
services()
.account_data
.get(None, sender_user, GlobalAccountDataEventType::PushRules.to_string().into())?;
let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content;
if let Some(event) = event {
let account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content;
Ok(get_pushrules_all::v3::Response {
global: account_data.global,
})
Ok(get_pushrules_all::v3::Response {
global: account_data.global,
})
} else {
services().account_data.update(
None,
sender_user,
GlobalAccountDataEventType::PushRules.to_string().into(),
&serde_json::to_value(PushRulesEvent {
content: ruma::events::push_rules::PushRulesEventContent {
global: Ruleset::server_default(sender_user),
},
})
.expect("to json always works"),
)?;
Ok(get_pushrules_all::v3::Response {
global: Ruleset::server_default(sender_user),
})
}
}
/// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}`
@@ -49,7 +67,10 @@ pub async fn get_pushrule_route(body: Ruma<get_pushrule::v3::Request>) -> Result
.map_err(|_| Error::bad_database("Invalid account data event in db."))?
.content;
let rule = account_data.global.get(body.kind.clone(), &body.rule_id).map(Into::into);
let rule = account_data
.global
.get(body.kind.clone(), &body.rule_id)
.map(Into::into);
if let Some(rule) = rule {
Ok(get_pushrule::v3::Response {
@@ -83,7 +104,10 @@ pub async fn set_pushrule_route(body: Ruma<set_pushrule::v3::Request>) -> Result
.map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if let Err(error) =
account_data.content.global.insert(body.rule.clone(), body.after.as_deref(), body.before.as_deref())
account_data
.content
.global
.insert(body.rule.clone(), body.after.as_deref(), body.before.as_deref())
{
let err = match error {
InsertPushRuleError::ServerDefaultRuleId => Error::BadRequest(
@@ -178,7 +202,12 @@ pub async fn set_pushrule_actions_route(
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if account_data.content.global.set_actions(body.kind.clone(), &body.rule_id, body.actions.clone()).is_err() {
if account_data
.content
.global
.set_actions(body.kind.clone(), &body.rule_id, body.actions.clone())
.is_err()
{
return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found."));
}
@@ -249,7 +278,12 @@ pub async fn set_pushrule_enabled_route(
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if account_data.content.global.set_enabled(body.kind.clone(), &body.rule_id, body.enabled).is_err() {
if account_data
.content
.global
.set_enabled(body.kind.clone(), &body.rule_id, body.enabled)
.is_err()
{
return Err(Error::BadRequest(ErrorKind::NotFound, "Push rule not found."));
}
@@ -284,7 +318,11 @@ pub async fn delete_pushrule_route(body: Ruma<delete_pushrule::v3::Request>) ->
let mut account_data = serde_json::from_str::<PushRulesEvent>(event.get())
.map_err(|_| Error::bad_database("Invalid account data event in db."))?;
if let Err(error) = account_data.content.global.remove(body.kind.clone(), &body.rule_id) {
if let Err(error) = account_data
.content
.global
.remove(body.kind.clone(), &body.rule_id)
{
let err = match error {
RemovePushRuleError::ServerDefault => {
Error::BadRequest(ErrorKind::InvalidParam, "Cannot delete a server-default pushrule.")
@@ -325,7 +363,9 @@ pub async fn get_pushers_route(body: Ruma<get_pushers::v3::Request>) -> Result<g
pub async fn set_pushers_route(body: Ruma<set_pusher::v3::Request>) -> Result<set_pusher::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
services().pusher.set_pusher(sender_user, body.action.clone())?;
services()
.pusher
.set_pusher(sender_user, body.action.clone())?;
Ok(set_pusher::v3::Response::default())
}
+18 -10
View File
@@ -36,7 +36,10 @@ pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) ->
}
if body.private_read_receipt.is_some() || body.read_receipt.is_some() {
services().rooms.user.reset_notification_counts(sender_user, &body.room_id)?;
services()
.rooms
.user
.reset_notification_counts(sender_user, &body.room_id)?;
}
if let Some(event) = &body.private_read_receipt {
@@ -54,7 +57,10 @@ pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) ->
},
PduCount::Normal(c) => c,
};
services().rooms.edus.read_receipt.private_read_set(&body.room_id, sender_user, count)?;
services()
.rooms
.read_receipt
.private_read_set(&body.room_id, sender_user, count)?;
}
if let Some(event) = &body.read_receipt {
@@ -73,7 +79,7 @@ pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) ->
let mut receipt_content = BTreeMap::new();
receipt_content.insert(event.to_owned(), receipts);
services().rooms.edus.read_receipt.readreceipt_update(
services().rooms.read_receipt.readreceipt_update(
sender_user,
&body.room_id,
ruma::events::receipt::ReceiptEvent {
@@ -81,8 +87,6 @@ pub async fn set_read_marker_route(body: Ruma<set_read_marker::v3::Request>) ->
room_id: body.room_id.clone(),
},
)?;
services().sending.flush_room(&body.room_id)?;
}
Ok(set_read_marker::v3::Response {})
@@ -98,7 +102,10 @@ pub async fn create_receipt_route(body: Ruma<create_receipt::v3::Request>) -> Re
&body.receipt_type,
create_receipt::v3::ReceiptType::Read | create_receipt::v3::ReceiptType::ReadPrivate
) {
services().rooms.user.reset_notification_counts(sender_user, &body.room_id)?;
services()
.rooms
.user
.reset_notification_counts(sender_user, &body.room_id)?;
}
match body.receipt_type {
@@ -130,7 +137,7 @@ pub async fn create_receipt_route(body: Ruma<create_receipt::v3::Request>) -> Re
let mut receipt_content = BTreeMap::new();
receipt_content.insert(body.event_id.clone(), receipts);
services().rooms.edus.read_receipt.readreceipt_update(
services().rooms.read_receipt.readreceipt_update(
sender_user,
&body.room_id,
ruma::events::receipt::ReceiptEvent {
@@ -138,8 +145,6 @@ pub async fn create_receipt_route(body: Ruma<create_receipt::v3::Request>) -> Re
room_id: body.room_id.clone(),
},
)?;
services().sending.flush_room(&body.room_id)?;
},
create_receipt::v3::ReceiptType::ReadPrivate => {
let count = services()
@@ -156,7 +161,10 @@ pub async fn create_receipt_route(body: Ruma<create_receipt::v3::Request>) -> Re
},
PduCount::Normal(c) => c,
};
services().rooms.edus.read_receipt.private_read_set(&body.room_id, sender_user, count)?;
services()
.rooms
.read_receipt
.private_read_set(&body.room_id, sender_user, count)?;
},
_ => return Err(Error::bad_database("Unsupported receipt type")),
}
+9 -2
View File
@@ -17,8 +17,15 @@ pub async fn redact_event_route(body: Ruma<redact_event::v3::Request>) -> Result
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let body = body.body;
let mutex_state =
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(body.room_id.clone()).or_default());
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(body.room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
let event_id = services()
+48 -73
View File
@@ -2,7 +2,7 @@ use ruma::api::client::relations::{
get_relating_events, get_relating_events_with_rel_type, get_relating_events_with_rel_type_and_event_type,
};
use crate::{service::rooms::timeline::PduCount, services, Result, Ruma};
use crate::{services, Result, Ruma};
/// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}/{eventType}`
pub async fn get_relating_events_with_rel_type_and_event_type_route(
@@ -10,35 +10,27 @@ pub async fn get_relating_events_with_rel_type_and_event_type_route(
) -> Result<get_relating_events_with_rel_type_and_event_type::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let from = match body.from.clone() {
Some(from) => PduCount::try_from_string(&from)?,
None => match ruma::api::Direction::Backward {
// TODO: fix ruma so `body.dir` exists
ruma::api::Direction::Forward => PduCount::min(),
ruma::api::Direction::Backward => PduCount::max(),
},
};
let to = body.to.as_ref().and_then(|t| PduCount::try_from_string(t).ok());
// Use limit or else 10, with maximum 100
let limit = body.limit.and_then(|u| u32::try_from(u).ok()).map_or(10_usize, |u| u as usize).min(100);
let res = services().rooms.pdu_metadata.paginate_relations_with_filter(
sender_user,
&body.room_id,
&body.event_id,
&Some(body.event_type.clone()),
&Some(body.rel_type.clone()),
from,
to,
limit,
)?;
let res = services()
.rooms
.pdu_metadata
.paginate_relations_with_filter(
sender_user,
&body.room_id,
&body.event_id,
&Some(body.event_type.clone()),
&Some(body.rel_type.clone()),
&body.from,
&body.to,
&body.limit,
body.recurse,
body.dir,
)?;
Ok(get_relating_events_with_rel_type_and_event_type::v1::Response {
chunk: res.chunk,
next_batch: res.next_batch,
prev_batch: res.prev_batch,
recursion_depth: res.recursion_depth,
})
}
@@ -48,35 +40,27 @@ pub async fn get_relating_events_with_rel_type_route(
) -> Result<get_relating_events_with_rel_type::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let from = match body.from.clone() {
Some(from) => PduCount::try_from_string(&from)?,
None => match ruma::api::Direction::Backward {
// TODO: fix ruma so `body.dir` exists
ruma::api::Direction::Forward => PduCount::min(),
ruma::api::Direction::Backward => PduCount::max(),
},
};
let to = body.to.as_ref().and_then(|t| PduCount::try_from_string(t).ok());
// Use limit or else 10, with maximum 100
let limit = body.limit.and_then(|u| u32::try_from(u).ok()).map_or(10_usize, |u| u as usize).min(100);
let res = services().rooms.pdu_metadata.paginate_relations_with_filter(
sender_user,
&body.room_id,
&body.event_id,
&None,
&Some(body.rel_type.clone()),
from,
to,
limit,
)?;
let res = services()
.rooms
.pdu_metadata
.paginate_relations_with_filter(
sender_user,
&body.room_id,
&body.event_id,
&None,
&Some(body.rel_type.clone()),
&body.from,
&body.to,
&body.limit,
body.recurse,
body.dir,
)?;
Ok(get_relating_events_with_rel_type::v1::Response {
chunk: res.chunk,
next_batch: res.next_batch,
prev_batch: res.prev_batch,
recursion_depth: res.recursion_depth,
})
}
@@ -86,28 +70,19 @@ pub async fn get_relating_events_route(
) -> Result<get_relating_events::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let from = match body.from.clone() {
Some(from) => PduCount::try_from_string(&from)?,
None => match ruma::api::Direction::Backward {
// TODO: fix ruma so `body.dir` exists
ruma::api::Direction::Forward => PduCount::min(),
ruma::api::Direction::Backward => PduCount::max(),
},
};
let to = body.to.as_ref().and_then(|t| PduCount::try_from_string(t).ok());
// Use limit or else 10, with maximum 100
let limit = body.limit.and_then(|u| u32::try_from(u).ok()).map_or(10_usize, |u| u as usize).min(100);
services().rooms.pdu_metadata.paginate_relations_with_filter(
sender_user,
&body.room_id,
&body.event_id,
&None,
&None,
from,
to,
limit,
)
services()
.rooms
.pdu_metadata
.paginate_relations_with_filter(
sender_user,
&body.room_id,
&body.event_id,
&None,
&None,
&body.from,
&body.to,
&body.limit,
body.recurse,
body.dir,
)
}
+21 -22
View File
@@ -21,14 +21,11 @@ pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Resu
info!("Received /report request by user {}", sender_user);
// check if we know about the reported event ID or if it's invalid
let pdu = match services().rooms.timeline.get_pdu(&body.event_id)? {
Some(pdu) => pdu,
_ => {
return Err(Error::BadRequest(
ErrorKind::NotFound,
"Event ID is not known to us or Event ID is invalid",
))
},
let Some(pdu) = services().rooms.timeline.get_pdu(&body.event_id)? else {
return Err(Error::BadRequest(
ErrorKind::NotFound,
"Event ID is not known to us or Event ID is invalid",
));
};
// check if the room ID from the URI matches the PDU's room ID
@@ -44,7 +41,7 @@ pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Resu
.rooms
.state_cache
.room_members(&pdu.room_id)
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.any(|user_id| user_id == *sender_user)
{
return Err(Error::BadRequest(
@@ -71,18 +68,20 @@ pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Resu
// send admin room message that we received the report with an @room ping for
// urgency
services().admin.send_message(message::RoomMessageEventContent::text_html(
format!(
"@room Report received from: {}\n\nEvent ID: {}\nRoom ID: {}\nSent By: {}\n\nReport Score: {}\nReport \
Reason: {}",
sender_user.to_owned(),
pdu.event_id,
pdu.room_id,
pdu.sender.clone(),
body.score.unwrap_or_else(|| ruma::Int::from(0)),
body.reason.as_deref().unwrap_or("")
),
format!(
services()
.admin
.send_message(message::RoomMessageEventContent::text_html(
format!(
"@room Report received from: {}\n\nEvent ID: {}\nRoom ID: {}\nSent By: {}\n\nReport Score: {}\nReport \
Reason: {}",
sender_user.to_owned(),
pdu.event_id,
pdu.room_id,
pdu.sender.clone(),
body.score.unwrap_or_else(|| ruma::Int::from(0)),
body.reason.as_deref().unwrap_or("")
),
format!(
"<details><summary>@room Report received from: <a href=\"https://matrix.to/#/{0}\">{0}\
</a></summary><ul><li>Event Info<ul><li>Event ID: <code>{1}</code>\
<a href=\"https://matrix.to/#/{2}/{1}\">🔗</a></li><li>Room ID: <code>{2}</code>\
@@ -96,7 +95,7 @@ pub async fn report_event_route(body: Ruma<report_content::v3::Request>) -> Resu
body.score.unwrap_or_else(|| ruma::Int::from(0)),
HtmlEscape(body.reason.as_deref().unwrap_or(""))
),
));
));
// even though this is kinda security by obscurity, let's still make a small
// random delay sending a successful response per spec suggestion regarding
+209 -95
View File
@@ -34,7 +34,7 @@ use crate::{api::client_server::invite_helper, service::pdu::PduBuilder, service
/// Creates a new room.
///
/// - Room ID is randomly generated
/// - Create alias if room_alias_name is set
/// - Create alias if `room_alias_name` is set
/// - Send create event
/// - Join sender user
/// - Send power levels event
@@ -50,8 +50,11 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().globals.allow_room_creation() && !&body.from_appservice && !services().users.is_admin(sender_user)? {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Room creation has been disabled."));
if !services().globals.allow_room_creation()
&& body.appservice_info.is_none()
&& !services().users.is_admin(sender_user)?
{
return Err(Error::BadRequest(ErrorKind::forbidden(), "Room creation has been disabled."));
}
let room_id: OwnedRoomId;
@@ -80,7 +83,11 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
}
// apply forbidden room alias checks to custom room IDs too
if services().globals.forbidden_room_names().is_match(&custom_room_id_s) {
if services()
.globals
.forbidden_alias_names()
.is_match(&custom_room_id_s)
{
return Err(Error::BadRequest(ErrorKind::Unknown, "Custom room ID is forbidden."));
}
@@ -110,60 +117,93 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
services().rooms.short.get_or_create_shortroomid(&room_id)?;
let mutex_state =
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default());
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
let alias: Option<OwnedRoomAliasId> = body.room_alias_name.as_ref().map_or(Ok(None), |localpart| {
// Basic checks on the room alias validity
if localpart.contains(':') {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias contained `:` which is not allowed. Please note that this expects a localpart, not the \
full room alias.",
));
} else if localpart.contains(char::is_whitespace) {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias contained spaces which is not a valid room alias.",
));
} else if localpart.len() > 255 {
// there is nothing spec-wise saying to check the limit of this,
// however absurdly long room aliases are guaranteed to be unreadable or done
// maliciously. there is no reason a room alias should even exceed 100
// characters as is. generally in spec, 255 is matrix's fav number
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias is excessively long, clients may not be able to handle this. Please shorten it.",
));
} else if localpart.contains('"') {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias contained `\"` which is not allowed.",
));
}
let alias: Option<OwnedRoomAliasId> = body
.room_alias_name
.as_ref()
.map_or(Ok(None), |localpart| {
// Basic checks on the room alias validity
if localpart.contains(':') {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias contained `:` which is not allowed. Please note that this expects a localpart, not \
the full room alias.",
));
} else if localpart.contains(char::is_whitespace) {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias contained spaces which is not a valid room alias.",
));
} else if localpart.len() > 255 {
// there is nothing spec-wise saying to check the limit of this,
// however absurdly long room aliases are guaranteed to be unreadable or done
// maliciously. there is no reason a room alias should even exceed 100
// characters as is. generally in spec, 255 is matrix's fav number
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias is excessively long, clients may not be able to handle this. Please shorten it.",
));
} else if localpart.contains('"') {
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Room alias contained `\"` which is not allowed.",
));
}
// check if room alias is forbidden
if services().globals.forbidden_room_names().is_match(localpart) {
return Err(Error::BadRequest(ErrorKind::Unknown, "Room alias name is forbidden."));
}
// check if room alias is forbidden
if services()
.globals
.forbidden_alias_names()
.is_match(localpart)
{
return Err(Error::BadRequest(ErrorKind::Unknown, "Room alias name is forbidden."));
}
let alias =
RoomAliasId::parse(format!("#{}:{}", localpart, services().globals.server_name())).map_err(|e| {
warn!("Failed to parse room alias for room ID {}: {e}", room_id);
Error::BadRequest(ErrorKind::InvalidParam, "Invalid room alias specified.")
})?;
let alias =
RoomAliasId::parse(format!("#{}:{}", localpart, services().globals.server_name())).map_err(|e| {
warn!("Failed to parse room alias for room ID {}: {e}", room_id);
Error::BadRequest(ErrorKind::InvalidParam, "Invalid room alias specified.")
})?;
if services().rooms.alias.resolve_local_alias(&alias)?.is_some() {
Err(Error::BadRequest(ErrorKind::RoomInUse, "Room alias already exists."))
} else {
Ok(Some(alias))
if services()
.rooms
.alias
.resolve_local_alias(&alias)?
.is_some()
{
Err(Error::BadRequest(ErrorKind::RoomInUse, "Room alias already exists."))
} else {
Ok(Some(alias))
}
})?;
if let Some(ref alias) = alias {
if let Some(ref info) = body.appservice_info {
if !info.aliases.is_match(alias.as_str()) {
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias is not in namespace."));
}
} else if services().appservice.is_exclusive_alias(alias).await {
return Err(Error::BadRequest(ErrorKind::Exclusive, "Room alias reserved by appservice."));
}
})?;
}
let room_version = match body.room_version.clone() {
Some(room_version) => {
if services().globals.supported_room_versions().contains(&room_version) {
if services()
.globals
.supported_room_versions()
.contains(&room_version)
{
room_version
} else {
return Err(Error::BadRequest(
@@ -177,10 +217,12 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
let content = match &body.creation_content {
Some(content) => {
let mut content = content.deserialize_as::<CanonicalJsonObject>().map_err(|e| {
error!("Failed to deserialise content as canonical JSON: {}", e);
Error::bad_database("Failed to deserialise content as canonical JSON.")
})?;
let mut content = content
.deserialize_as::<CanonicalJsonObject>()
.map_err(|e| {
error!("Failed to deserialise content as canonical JSON: {}", e);
Error::bad_database("Failed to deserialise content as canonical JSON.")
})?;
match room_version {
RoomVersionId::V1
| RoomVersionId::V2
@@ -202,7 +244,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
},
RoomVersionId::V11 => {}, // V11 removed the "creator" key
_ => {
warn!("Unexpected or unsupported room version {}", room_version);
warn!("Unexpected or unsupported room version {room_version}");
return Err(Error::BadRequest(
ErrorKind::BadJson,
"Unexpected or unsupported room version found",
@@ -219,7 +261,6 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
content
},
None => {
// TODO: Add correct value for v11
let content = match room_version {
RoomVersionId::V1
| RoomVersionId::V2
@@ -233,7 +274,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
| RoomVersionId::V10 => RoomCreateEventContent::new_v1(sender_user.clone()),
RoomVersionId::V11 => RoomCreateEventContent::new_v11(),
_ => {
warn!("Unexpected or unsupported room version {}", room_version);
warn!("Unexpected or unsupported room version {room_version}");
return Err(Error::BadRequest(
ErrorKind::BadJson,
"Unexpected or unsupported room version found",
@@ -257,8 +298,11 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
};
// Validate creation content
let de_result =
serde_json::from_str::<CanonicalJsonObject>(to_raw_value(&content).expect("Invalid creation content").get());
let de_result = serde_json::from_str::<CanonicalJsonObject>(
to_raw_value(&content)
.expect("Invalid creation content")
.get(),
);
if de_result.is_err() {
return Err(Error::BadRequest(ErrorKind::BadJson, "Invalid creation content"));
@@ -273,7 +317,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
event_type: TimelineEventType::RoomCreate,
content: to_raw_value(&content).expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -333,6 +377,25 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
})
.expect("event is valid, we just created it");
// secure proper defaults of sensitive/dangerous permissions that moderators
// (power level 50) should not have easy access to
power_levels_content["events"]["m.room.power_levels"] = serde_json::to_value(100).expect("100 is valid Value");
power_levels_content["events"]["m.room.server_acl"] = serde_json::to_value(100).expect("100 is valid Value");
power_levels_content["events"]["m.room.tombstone"] = serde_json::to_value(100).expect("100 is valid Value");
power_levels_content["events"]["m.room.encryption"] = serde_json::to_value(100).expect("100 is valid Value");
power_levels_content["events"]["m.room.history_visibility"] =
serde_json::to_value(100).expect("100 is valid Value");
// synapse does this too. clients do not expose these permissions. it prevents
// default users from calling public rooms, for obvious reasons.
if body.visibility == room::Visibility::Public {
power_levels_content["events"]["m.call.invite"] = serde_json::to_value(50).expect("50 is valid Value");
power_levels_content["events"]["org.matrix.msc3401.call"] =
serde_json::to_value(50).expect("50 is valid Value");
power_levels_content["events"]["org.matrix.msc3401.call.member"] =
serde_json::to_value(50).expect("50 is valid Value");
}
if let Some(power_level_content_override) = &body.power_level_content_override {
let json: JsonObject = serde_json::from_str(power_level_content_override.json().get())
.map_err(|_| Error::BadRequest(ErrorKind::BadJson, "Invalid power_level_content_override."))?;
@@ -350,7 +413,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
event_type: TimelineEventType::RoomPowerLevels,
content: to_raw_value(&power_levels_content).expect("to_raw_value always works on serde_json::Value"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -373,7 +436,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
})
.expect("We checked that alias earlier, it must be fine"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -399,7 +462,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
}))
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -418,7 +481,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
content: to_raw_value(&RoomHistoryVisibilityEventContent::new(HistoryVisibility::Shared))
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -440,7 +503,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
}))
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -457,14 +520,18 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
})?;
// Implicit state key defaults to ""
pdu_builder.state_key.get_or_insert_with(|| "".to_owned());
pdu_builder.state_key.get_or_insert_with(String::new);
// Silently skip encryption events if they are not allowed
if pdu_builder.event_type == TimelineEventType::RoomEncryption && !services().globals.allow_encryption() {
continue;
}
services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await?;
services()
.rooms
.timeline
.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock)
.await?;
}
// 7. Events implied by name and topic
@@ -478,7 +545,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
content: to_raw_value(&RoomNameEventContent::new(name.clone()))
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -500,7 +567,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
})
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -513,7 +580,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
// 8. Events implied by invite (and TODO: invite_3pid)
drop(state_lock);
for user_id in &body.invite {
let _ = invite_helper(sender_user, user_id, &room_id, None, body.is_direct).await;
_ = invite_helper(sender_user, user_id, &room_id, None, body.is_direct).await;
}
// Homeserver specific stuff
@@ -539,14 +606,22 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
pub async fn get_room_event_route(body: Ruma<get_room_event::v3::Request>) -> Result<get_room_event::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services().rooms.timeline.get_pdu(&body.event_id)?.ok_or_else(|| {
warn!("Event not found, event ID: {:?}", &body.event_id);
Error::BadRequest(ErrorKind::NotFound, "Event not found.")
})?;
let event = services()
.rooms
.timeline
.get_pdu(&body.event_id)?
.ok_or_else(|| {
warn!("Event not found, event ID: {:?}", &body.event_id);
Error::BadRequest(ErrorKind::NotFound, "Event not found.")
})?;
if !services().rooms.state_accessor.user_can_see_event(sender_user, &event.room_id, &body.event_id)? {
if !services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &event.room_id, &body.event_id)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
ErrorKind::forbidden(),
"You don't have permission to view this event.",
));
}
@@ -563,14 +638,18 @@ pub async fn get_room_event_route(body: Ruma<get_room_event::v3::Request>) -> Re
///
/// Lists all aliases of the room.
///
/// - Only users joined to the room are allowed to call this TODO: Allow any
/// user to call it if history_visibility is world readable
/// - Only users joined to the room are allowed to call this, or if
/// `history_visibility` is world readable in the room
pub async fn get_room_aliases_route(body: Ruma<aliases::v3::Request>) -> Result<aliases::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_cache.is_joined(sender_user, &body.room_id)? {
if !services()
.rooms
.state_accessor
.user_can_see_state_events(sender_user, &body.room_id)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
ErrorKind::forbidden(),
"You don't have permission to view this room.",
));
}
@@ -580,7 +659,7 @@ pub async fn get_room_aliases_route(body: Ruma<aliases::v3::Request>) -> Result<
.rooms
.alias
.local_aliases_for_room(&body.room_id)
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.collect(),
})
}
@@ -598,7 +677,11 @@ pub async fn get_room_aliases_route(body: Ruma<aliases::v3::Request>) -> Result<
pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result<upgrade_room::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().globals.supported_room_versions().contains(&body.new_version) {
if !services()
.globals
.supported_room_versions()
.contains(&body.new_version)
{
return Err(Error::BadRequest(
ErrorKind::UnsupportedRoomVersion,
"This server does not support that room version.",
@@ -607,10 +690,20 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Create a replacement room
let replacement_room = RoomId::new(services().globals.server_name());
services().rooms.short.get_or_create_shortroomid(&replacement_room)?;
services()
.rooms
.short
.get_or_create_shortroomid(&replacement_room)?;
let mutex_state =
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(body.room_id.clone()).or_default());
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(body.room_id.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
// Send a m.room.tombstone event to the old room to indicate that it is not
@@ -628,7 +721,7 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
})
.expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -639,8 +732,15 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Change lock to replacement room
drop(state_lock);
let mutex_state =
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(replacement_room.clone()).or_default());
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(replacement_room.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
// Get the old room creation event
@@ -710,7 +810,9 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Validate creation event content
let de_result = serde_json::from_str::<CanonicalJsonObject>(
to_raw_value(&create_event_content).expect("Error forming creation event").get(),
to_raw_value(&create_event_content)
.expect("Error forming creation event")
.get(),
);
if de_result.is_err() {
@@ -725,7 +827,7 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
event_type: TimelineEventType::RoomCreate,
content: to_raw_value(&create_event_content).expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -777,7 +879,11 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Replicate transferable state events to the new room
for event_type in transferable_state_events {
let event_content = match services().rooms.state_accessor.room_state_get(&body.room_id, &event_type, "")? {
let event_content = match services()
.rooms
.state_accessor
.room_state_get(&body.room_id, &event_type, "")?
{
Some(v) => v.content.clone(),
None => continue, // Skipping missing events.
};
@@ -790,7 +896,7 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
event_type: event_type.to_string().into(),
content: event_content,
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
@@ -801,8 +907,16 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
}
// Moves any local aliases to the new room
for alias in services().rooms.alias.local_aliases_for_room(&body.room_id).filter_map(std::result::Result::ok) {
services().rooms.alias.set_alias(&alias, &replacement_room)?;
for alias in services()
.rooms
.alias
.local_aliases_for_room(&body.room_id)
.filter_map(Result::ok)
{
services()
.rooms
.alias
.set_alias(&alias, &replacement_room)?;
}
// Get the old room power levels
@@ -824,7 +938,7 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Modify the power levels in the old room to prevent sending of events and
// inviting new users
let _ = services()
_ = services()
.rooms
.timeline
.build_and_append_pdu(
@@ -832,7 +946,7 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
event_type: TimelineEventType::RoomPowerLevels,
content: to_raw_value(&power_levels_event_content).expect("event is valid, we just created it"),
unsigned: None,
state_key: Some("".to_owned()),
state_key: Some(String::new()),
redacts: None,
},
sender_user,
+76 -14
View File
@@ -1,12 +1,18 @@
use std::collections::BTreeMap;
use ruma::api::client::{
error::ErrorKind,
search::search_events::{
self,
v3::{EventContextResult, ResultCategories, ResultRoomEvents, SearchResult},
use ruma::{
api::client::{
error::ErrorKind,
search::search_events::{
self,
v3::{EventContextResult, ResultCategories, ResultRoomEvents, SearchResult},
},
},
events::AnyStateEvent,
serde::Raw,
OwnedRoomId,
};
use tracing::debug;
use crate::{services, Error, Result, Ruma};
@@ -21,25 +27,81 @@ pub async fn search_events_route(body: Ruma<search_events::v3::Request>) -> Resu
let search_criteria = body.search_categories.room_events.as_ref().unwrap();
let filter = &search_criteria.filter;
let include_state = &search_criteria.include_state;
let room_ids = filter.rooms.clone().unwrap_or_else(|| {
services().rooms.state_cache.rooms_joined(sender_user).filter_map(std::result::Result::ok).collect()
services()
.rooms
.state_cache
.rooms_joined(sender_user)
.filter_map(Result::ok)
.collect()
});
// Use limit or else 10, with maximum 100
let limit = filter.limit.map_or(10, u64::from).min(100) as usize;
let mut room_states: BTreeMap<OwnedRoomId, Vec<Raw<AnyStateEvent>>> = BTreeMap::new();
if include_state.is_some_and(|include_state| include_state) {
for room_id in &room_ids {
if !services()
.rooms
.state_cache
.is_joined(sender_user, room_id)?
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"You don't have permission to view this room.",
));
}
// check if sender_user can see state events
if services()
.rooms
.state_accessor
.user_can_see_state_events(sender_user, room_id)?
{
let room_state = services()
.rooms
.state_accessor
.room_state_full(room_id)
.await?
.values()
.map(|pdu| pdu.to_state_event())
.collect::<Vec<_>>();
debug!("Room state: {:?}", room_state);
room_states.insert(room_id.clone(), room_state);
} else {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"You don't have permission to view this room.",
));
}
}
}
let mut searches = Vec::new();
for room_id in room_ids {
if !services().rooms.state_cache.is_joined(sender_user, &room_id)? {
for room_id in &room_ids {
if !services()
.rooms
.state_cache
.is_joined(sender_user, room_id)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
ErrorKind::forbidden(),
"You don't have permission to view this room.",
));
}
if let Some(search) = services().rooms.search.search_pdus(&room_id, &search_criteria.search_term)? {
if let Some(search) = services()
.rooms
.search
.search_pdus(room_id, &search_criteria.search_term)?
{
searches.push(search.0.peekable());
}
}
@@ -92,7 +154,7 @@ pub async fn search_events_route(body: Ruma<search_events::v3::Request>) -> Resu
result: Some(result),
})
})
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.skip(skip)
.take(limit)
.collect();
@@ -105,11 +167,11 @@ pub async fn search_events_route(body: Ruma<search_events::v3::Request>) -> Resu
Ok(search_events::v3::Response::new(ResultCategories {
room_events: ResultRoomEvents {
count: Some((results.len() as u32).into()), // TODO: set this to none. Element shouldn't depend on it
groups: BTreeMap::new(), // TODO
count: Some((results.len() as u32).into()),
groups: BTreeMap::new(), // TODO
next_batch,
results,
state: BTreeMap::new(), // TODO
state: room_states,
highlights: search_criteria
.search_term
.split_terminator(|c: char| !c.is_alphanumeric())
+69 -61
View File
@@ -66,31 +66,27 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
..
}) => {
debug!("Got password login type");
let username = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
debug!("Using username from identifier field");
user_id.to_lowercase()
} else if let Some(user_id) = user {
warn!(
"User \"{}\" is attempting to login with the deprecated \"user\" field at \
\"/_matrix/client/v3/login\". conduwuit implements this deprecated behaviour, but this is \
destined to be removed in a future Matrix release.",
user_id
);
user_id.to_lowercase()
let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
UserId::parse_with_server_name(user_id.to_lowercase(), services().globals.server_name())
} else if let Some(user) = user {
UserId::parse(user)
} else {
warn!("Bad login type: {:?}", &body.login_info);
return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type."));
};
let user_id = UserId::parse_with_server_name(username, services().globals.server_name()).map_err(|e| {
warn!("Failed to parse username from user logging in: {}", e);
return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type."));
}
.map_err(|e| {
warn!("Failed to parse username from user logging in: {e}");
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?;
if services().appservice.is_exclusive_user_id(&user_id).await {
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice."));
}
let hash = services()
.users
.password_hash(&user_id)?
.ok_or(Error::BadRequest(ErrorKind::Forbidden, "Wrong username or password."))?;
.ok_or(Error::BadRequest(ErrorKind::forbidden(), "Wrong username or password."))?;
if hash.is_empty() {
return Err(Error::BadRequest(ErrorKind::UserDeactivated, "The user has been deactivated"));
@@ -101,10 +97,14 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
return Err(Error::BadServerResponse("could not hash"));
};
let hash_matches = services().globals.argon.verify_password(password.as_bytes(), &parsed_hash).is_ok();
let hash_matches = services()
.globals
.argon
.verify_password(password.as_bytes(), &parsed_hash)
.is_ok();
if !hash_matches {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Wrong username or password."));
return Err(Error::BadRequest(ErrorKind::forbidden(), "Wrong username or password."));
}
user_id
@@ -117,16 +117,23 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
let token =
jsonwebtoken::decode::<Claims>(token, jwt_decoding_key, &jsonwebtoken::Validation::default())
.map_err(|e| {
warn!("Failed to parse JWT token from user logging in: {}", e);
warn!("Failed to parse JWT token from user logging in: {e}");
Error::BadRequest(ErrorKind::InvalidUsername, "Token is invalid.")
})?;
let username = token.claims.sub.to_lowercase();
UserId::parse_with_server_name(username, services().globals.server_name()).map_err(|e| {
warn!("Failed to parse username from user logging in: {}", e);
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?
let user_id =
UserId::parse_with_server_name(username, services().globals.server_name()).map_err(|e| {
warn!("Failed to parse username from user logging in: {e}");
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?;
if services().appservice.is_exclusive_user_id(&user_id).await {
return Err(Error::BadRequest(ErrorKind::Exclusive, "User ID reserved by appservice."));
}
user_id
} else {
return Err(Error::BadRequest(
ErrorKind::Unknown,
@@ -140,31 +147,28 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
user,
}) => {
debug!("Got appservice login type");
if !body.from_appservice {
info!(
"User tried logging in as an appservice, but request body is not from a known/registered \
appservice"
);
return Err(Error::BadRequest(ErrorKind::Forbidden, "Forbidden login type."));
};
let username = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
user_id.to_lowercase()
} else if let Some(user_id) = user {
warn!(
"Appservice \"{}\" is attempting to login with the deprecated \"user\" field at \
\"/_matrix/client/v3/login\". conduwuit implements this deprecated behaviour, but this is \
destined to be removed in a future Matrix release.",
user_id
);
user_id.to_lowercase()
let user_id = if let Some(UserIdentifier::UserIdOrLocalpart(user_id)) = identifier {
UserId::parse_with_server_name(user_id.to_lowercase(), services().globals.server_name())
} else if let Some(user) = user {
UserId::parse(user)
} else {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type."));
};
UserId::parse_with_server_name(username, services().globals.server_name()).map_err(|e| {
warn!("Failed to parse username from appservice logging in: {}", e);
warn!("Bad login type: {:?}", &body.login_info);
return Err(Error::BadRequest(ErrorKind::forbidden(), "Bad login type."));
}
.map_err(|e| {
warn!("Failed to parse username from appservice logging in: {e}");
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?
})?;
if let Some(ref info) = body.appservice_info {
if !info.is_user_match(&user_id) {
return Err(Error::BadRequest(ErrorKind::Exclusive, "User is not in namespace."));
}
} else {
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing appservice token."));
}
user_id
},
_ => {
warn!("Unsupported or unknown login type: {:?}", &body.login_info);
@@ -174,28 +178,38 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
};
// Generate new device id if the user didn't specify one
let device_id = body.device_id.clone().unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
let device_id = body
.device_id
.clone()
.unwrap_or_else(|| utils::random_string(DEVICE_ID_LENGTH).into());
// Generate a new token for the device
let token = utils::random_string(TOKEN_LENGTH);
// Determine if device_id was provided and exists in the db for this user
let device_exists = body.device_id.as_ref().map_or(false, |device_id| {
services().users.all_device_ids(&user_id).any(|x| x.as_ref().map_or(false, |v| v == device_id))
services()
.users
.all_device_ids(&user_id)
.any(|x| x.as_ref().map_or(false, |v| v == device_id))
});
if device_exists {
services().users.set_token(&user_id, &device_id, &token)?;
} else {
services().users.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?;
services()
.users
.create_device(&user_id, &device_id, &token, body.initial_device_display_name.clone())?;
}
// send client well-known if specified so the client knows to reconfigure itself
let client_discovery_info = DiscoveryInfo::new(HomeserverInfo::new(
services().globals.well_known_client().to_owned().unwrap_or_else(|| "".to_owned()),
));
let client_discovery_info: Option<DiscoveryInfo> = services()
.globals
.well_known_client()
.as_ref()
.map(|server| DiscoveryInfo::new(HomeserverInfo::new(server.to_string())));
info!("{} logged in", user_id);
info!("{user_id} logged in");
// home_server is deprecated but apparently must still be sent despite it being
// deprecated over 6 years ago. initially i thought this macro was unnecessary,
@@ -205,13 +219,7 @@ pub async fn login_route(body: Ruma<login::v3::Request>) -> Result<login::v3::Re
user_id,
access_token: token,
device_id,
well_known: {
if client_discovery_info.homeserver.base_url.as_str() == "" {
None
} else {
Some(client_discovery_info)
}
},
well_known: client_discovery_info,
expires_in: None,
home_server: Some(services().globals.server_name().to_owned()),
refresh_token: None,
+13 -4
View File
@@ -7,18 +7,27 @@ use ruma::{
use crate::{service::rooms::spaces::PagnationToken, services, Error, Result, Ruma};
/// # `GET /_matrix/client/v1/rooms/{room_id}/hierarchy``
/// # `GET /_matrix/client/v1/rooms/{room_id}/hierarchy`
///
/// Paginates over the space tree in a depth-first manner to locate child rooms
/// of a given space.
pub async fn get_hierarchy_route(body: Ruma<get_hierarchy::v1::Request>) -> Result<get_hierarchy::v1::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let limit = body.limit.unwrap_or_else(|| UInt::from(10_u32)).min(UInt::from(100_u32));
let limit = body
.limit
.unwrap_or_else(|| UInt::from(10_u32))
.min(UInt::from(100_u32));
let max_depth = body.max_depth.unwrap_or_else(|| UInt::from(3_u32)).min(UInt::from(10_u32));
let max_depth = body
.max_depth
.unwrap_or_else(|| UInt::from(3_u32))
.min(UInt::from(10_u32));
let key = body.from.as_ref().and_then(|s| PagnationToken::from_str(s).ok());
let key = body
.from
.as_ref()
.and_then(|s| PagnationToken::from_str(s).ok());
// Should prevent unexpeded behaviour in (bad) clients
if let Some(ref token) = key {
+114 -56
View File
@@ -5,22 +5,31 @@ use ruma::{
error::ErrorKind,
state::{get_state_events, get_state_events_for_key, send_state_event},
},
events::{room::canonical_alias::RoomCanonicalAliasEventContent, AnyStateEventContent, StateEventType},
events::{
room::{
canonical_alias::RoomCanonicalAliasEventContent,
join_rules::{JoinRule, RoomJoinRulesEventContent},
},
AnyStateEventContent, StateEventType,
},
serde::Raw,
EventId, RoomId, UserId,
};
use tracing::{error, log::warn};
use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma, RumaResponse};
use crate::{
service::{self, pdu::PduBuilder},
services, Error, Result, Ruma, RumaResponse,
};
/// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}`
/// # `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}`
///
/// Sends a state event into the room.
///
/// - The only requirement for the content is that it has to be valid json
/// - Tries to send the event into the room, auth rules will determine if it is
/// allowed
/// - If event is new canonical_alias: Rejects if alias is incorrect
/// - If event is new `canonical_alias`: Rejects if alias is incorrect
pub async fn send_state_event_for_key_route(
body: Ruma<send_state_event::v3::Request>,
) -> Result<send_state_event::v3::Response> {
@@ -41,24 +50,19 @@ pub async fn send_state_event_for_key_route(
})
}
/// # `PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}`
/// # `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}`
///
/// Sends a state event into the room.
///
/// - The only requirement for the content is that it has to be valid json
/// - Tries to send the event into the room, auth rules will determine if it is
/// allowed
/// - If event is new canonical_alias: Rejects if alias is incorrect
/// - If event is new `canonical_alias`: Rejects if alias is incorrect
pub async fn send_state_event_for_empty_key_route(
body: Ruma<send_state_event::v3::Request>,
) -> Result<RumaResponse<send_state_event::v3::Response>> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
// Forbid m.room.encryption if encryption is disabled
if body.event_type == StateEventType::RoomEncryption && !services().globals.allow_encryption() {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Encryption has been disabled"));
}
let event_id = send_state_event_for_key_helper(
sender_user,
&body.room_id,
@@ -86,9 +90,13 @@ pub async fn get_state_events_route(
) -> Result<get_state_events::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_accessor.user_can_see_state_events(sender_user, &body.room_id)? {
if !services()
.rooms
.state_accessor
.user_can_see_state_events(sender_user, &body.room_id)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
ErrorKind::forbidden(),
"You don't have permission to view the room state.",
));
}
@@ -118,21 +126,30 @@ pub async fn get_state_events_for_key_route(
) -> Result<get_state_events_for_key::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_accessor.user_can_see_state_events(sender_user, &body.room_id)? {
if !services()
.rooms
.state_accessor
.user_can_see_state_events(sender_user, &body.room_id)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
ErrorKind::forbidden(),
"You don't have permission to view the room state.",
));
}
let event =
services().rooms.state_accessor.room_state_get(&body.room_id, &body.event_type, &body.state_key)?.ok_or_else(
|| {
warn!("State event {:?} not found in room {:?}", &body.event_type, &body.room_id);
Error::BadRequest(ErrorKind::NotFound, "State event not found.")
},
)?;
if body.format.as_ref().is_some_and(|f| f.to_lowercase().eq("event")) {
let event = services()
.rooms
.state_accessor
.room_state_get(&body.room_id, &body.event_type, &body.state_key)?
.ok_or_else(|| {
warn!("State event {:?} not found in room {:?}", &body.event_type, &body.room_id);
Error::BadRequest(ErrorKind::NotFound, "State event not found.")
})?;
if body
.format
.as_ref()
.is_some_and(|f| f.to_lowercase().eq("event"))
{
Ok(get_state_events_for_key::v3::Response {
content: None,
event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| {
@@ -164,20 +181,31 @@ pub async fn get_state_events_for_empty_key_route(
) -> Result<RumaResponse<get_state_events_for_key::v3::Response>> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_accessor.user_can_see_state_events(sender_user, &body.room_id)? {
if !services()
.rooms
.state_accessor
.user_can_see_state_events(sender_user, &body.room_id)?
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
ErrorKind::forbidden(),
"You don't have permission to view the room state.",
));
}
let event =
services().rooms.state_accessor.room_state_get(&body.room_id, &body.event_type, "")?.ok_or_else(|| {
let event = services()
.rooms
.state_accessor
.room_state_get(&body.room_id, &body.event_type, "")?
.ok_or_else(|| {
warn!("State event {:?} not found in room {:?}", &body.event_type, &body.room_id);
Error::BadRequest(ErrorKind::NotFound, "State event not found.")
})?;
if body.format.as_ref().is_some_and(|f| f.to_lowercase().eq("event")) {
if body
.format
.as_ref()
.is_some_and(|f| f.to_lowercase().eq("event"))
{
Ok(get_state_events_for_key::v3::Response {
content: None,
event: serde_json::from_str(event.to_state_event().json().get()).map_err(|e| {
@@ -201,36 +229,66 @@ pub async fn get_state_events_for_empty_key_route(
async fn send_state_event_for_key_helper(
sender: &UserId, room_id: &RoomId, event_type: &StateEventType, json: &Raw<AnyStateEventContent>, state_key: String,
) -> Result<Arc<EventId>> {
let sender_user = sender;
// TODO: Review this check, error if event is unparsable, use event type, allow
// alias if it previously existed
if let Ok(canonical_alias) = serde_json::from_str::<RoomCanonicalAliasEventContent>(json.json().get()) {
let mut aliases = canonical_alias.alt_aliases.clone();
if let Some(alias) = canonical_alias.alias {
aliases.push(alias);
}
for alias in aliases {
if alias.server_name() != services().globals.server_name()
|| services()
.rooms
.alias
.resolve_local_alias(&alias)?
.filter(|room| room == room_id) // Make sure it's the right room
.is_none()
{
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"You are only allowed to send canonical_alias events when it's aliases already exists",
));
match *event_type {
// Forbid m.room.encryption if encryption is disabled
StateEventType::RoomEncryption => {
if !services().globals.allow_encryption() {
return Err(Error::BadRequest(ErrorKind::forbidden(), "Encryption has been disabled"));
}
}
},
// admin room is a sensitive room, it should not ever be made public
StateEventType::RoomJoinRules => {
if let Some(admin_room_id) = service::admin::Service::get_admin_room()? {
if admin_room_id == room_id {
if let Ok(join_rule) = serde_json::from_str::<RoomJoinRulesEventContent>(json.json().get()) {
if join_rule.join_rule == JoinRule::Public {
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Admin room is not allowed to be public.",
));
}
}
}
}
},
// TODO: allow alias if it previously existed
StateEventType::RoomCanonicalAlias => {
if let Ok(canonical_alias) = serde_json::from_str::<RoomCanonicalAliasEventContent>(json.json().get()) {
let mut aliases = canonical_alias.alt_aliases.clone();
if let Some(alias) = canonical_alias.alias {
aliases.push(alias);
}
for alias in aliases {
if alias.server_name() != services().globals.server_name()
|| services()
.rooms
.alias
.resolve_local_alias(&alias)?
.filter(|room| room == room_id) // Make sure it's the right room
.is_none()
{
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"You are only allowed to send canonical_alias events when its aliases already exist",
));
}
}
}
},
_ => {},
}
let mutex_state =
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.to_owned()).or_default());
let mutex_state = Arc::clone(
services()
.globals
.roomid_mutex_state
.write()
.await
.entry(room_id.to_owned())
.or_default(),
);
let state_lock = mutex_state.lock().await;
let event_id = services()
@@ -244,7 +302,7 @@ async fn send_state_event_for_key_helper(
state_key: Some(state_key),
redacts: None,
},
sender_user,
sender,
room_id,
&state_lock,
)
File diff suppressed because it is too large Load Diff
+28 -16
View File
@@ -18,19 +18,25 @@ use crate::{services, Error, Result, Ruma};
pub async fn update_tag_route(body: Ruma<create_tag::v3::Request>) -> Result<create_tag::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services().account_data.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?;
let event = services()
.account_data
.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?;
let mut tags_event = event
.map(|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db.")))
.unwrap_or_else(|| {
let mut tags_event = event.map_or_else(
|| {
Ok(TagEvent {
content: TagEventContent {
tags: BTreeMap::new(),
},
})
})?;
},
|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db.")),
)?;
tags_event.content.tags.insert(body.tag.clone().into(), body.tag_info.clone());
tags_event
.content
.tags
.insert(body.tag.clone().into(), body.tag_info.clone());
services().account_data.update(
Some(&body.room_id),
@@ -50,17 +56,20 @@ pub async fn update_tag_route(body: Ruma<create_tag::v3::Request>) -> Result<cre
pub async fn delete_tag_route(body: Ruma<delete_tag::v3::Request>) -> Result<delete_tag::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services().account_data.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?;
let event = services()
.account_data
.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?;
let mut tags_event = event
.map(|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db.")))
.unwrap_or_else(|| {
let mut tags_event = event.map_or_else(
|| {
Ok(TagEvent {
content: TagEventContent {
tags: BTreeMap::new(),
},
})
})?;
},
|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db.")),
)?;
tags_event.content.tags.remove(&body.tag.clone().into());
@@ -82,17 +91,20 @@ pub async fn delete_tag_route(body: Ruma<delete_tag::v3::Request>) -> Result<del
pub async fn get_tags_route(body: Ruma<get_tags::v3::Request>) -> Result<get_tags::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let event = services().account_data.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?;
let event = services()
.account_data
.get(Some(&body.room_id), sender_user, RoomAccountDataEventType::Tag)?;
let tags_event = event
.map(|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db.")))
.unwrap_or_else(|| {
let tags_event = event.map_or_else(
|| {
Ok(TagEvent {
content: TagEventContent {
tags: BTreeMap::new(),
},
})
})?;
},
|e| serde_json::from_str(e.get()).map_err(|_| Error::bad_database("Invalid account data event in db.")),
)?;
Ok(get_tags::v3::Response {
tags: tags_event.content.tags,
+12 -4
View File
@@ -7,10 +7,15 @@ pub async fn get_threads_route(body: Ruma<get_threads::v1::Request>) -> Result<g
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
// Use limit or else 10, with maximum 100
let limit = body.limit.and_then(|l| l.try_into().ok()).unwrap_or(10).min(100);
let limit = body
.limit
.and_then(|l| l.try_into().ok())
.unwrap_or(10)
.min(100);
let from = if let Some(from) = &body.from {
from.parse().map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, ""))?
from.parse()
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, ""))?
} else {
u64::MAX
};
@@ -20,7 +25,7 @@ pub async fn get_threads_route(body: Ruma<get_threads::v1::Request>) -> Result<g
.threads
.threads_until(sender_user, &body.room_id, from, &body.include)?
.take(limit)
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.filter(|(_, pdu)| {
services()
.rooms
@@ -33,7 +38,10 @@ pub async fn get_threads_route(body: Ruma<get_threads::v1::Request>) -> Result<g
let next_batch = threads.last().map(|(count, _)| count.to_string());
Ok(get_threads::v1::Response {
chunk: threads.into_iter().map(|(_, pdu)| pdu.to_room_event()).collect(),
chunk: threads
.into_iter()
.map(|(_, pdu)| pdu.to_room_event())
.collect(),
next_batch,
})
}
+9 -4
View File
@@ -20,7 +20,11 @@ pub async fn send_event_to_device_route(
let sender_device = body.sender_device.as_deref();
// Check if this is a new transaction id
if services().transaction_ids.existing_txnid(sender_user, sender_device, &body.txn_id)?.is_some() {
if services()
.transaction_ids
.existing_txnid(sender_user, sender_device, &body.txn_id)?
.is_some()
{
return Ok(send_event_to_device::v3::Response {});
}
@@ -33,7 +37,7 @@ pub async fn send_event_to_device_route(
messages.insert(target_user_id.clone(), map);
let count = services().globals.next_count()?;
services().sending.send_reliable_edu(
services().sending.send_edu_server(
target_user_id.server_name(),
serde_json::to_vec(&federation::transactions::edu::Edu::DirectToDevice(DirectDeviceContent {
sender: sender_user.clone(),
@@ -42,7 +46,6 @@ pub async fn send_event_to_device_route(
messages,
}))
.expect("DirectToDevice EDU can be serialized"),
count,
)?;
continue;
@@ -79,7 +82,9 @@ pub async fn send_event_to_device_route(
}
// Save transaction id with empty data
services().transaction_ids.add_txnid(sender_user, sender_device, &body.txn_id, &[])?;
services()
.transaction_ids
.add_txnid(sender_user, sender_device, &body.txn_id, &[])?;
Ok(send_event_to_device::v3::Response {})
}
+17 -9
View File
@@ -12,23 +12,31 @@ pub async fn create_typing_event_route(
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if !services().rooms.state_cache.is_joined(sender_user, &body.room_id)? {
return Err(Error::BadRequest(ErrorKind::Forbidden, "You are not in this room."));
if !services()
.rooms
.state_cache
.is_joined(sender_user, &body.room_id)?
{
return Err(Error::BadRequest(ErrorKind::forbidden(), "You are not in this room."));
}
if let Typing::Yes(duration) = body.state {
let duration = utils::clamp(
duration.as_millis() as u64,
services().globals.config.typing_client_timeout_min_s * 1000,
services().globals.config.typing_client_timeout_max_s * 1000,
);
services()
.rooms
.edus
.typing
.typing_add(
sender_user,
&body.room_id,
duration.as_millis() as u64 + utils::millis_since_unix_epoch(),
)
.typing_add(sender_user, &body.room_id, utils::millis_since_unix_epoch() + duration)
.await?;
} else {
services().rooms.edus.typing.typing_remove(sender_user, &body.room_id).await?;
services()
.rooms
.typing
.typing_remove(sender_user, &body.room_id)
.await?;
}
Ok(create_typing_event::v3::Response {})
+45
View File
@@ -0,0 +1,45 @@
use ruma::{
api::client::{error::ErrorKind, membership::mutual_rooms},
OwnedRoomId,
};
use crate::{services, Error, Result, Ruma};
/// # `GET /_matrix/client/unstable/uk.half-shot.msc2666/user/mutual_rooms`
///
/// Gets all the rooms the sender shares with the specified user.
///
/// TODO: Implement pagination, currently this just returns everything
///
/// An implementation of [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666)
pub async fn get_mutual_rooms_route(
body: Ruma<mutual_rooms::unstable::Request>,
) -> Result<mutual_rooms::unstable::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated");
if sender_user == &body.user_id {
return Err(Error::BadRequest(
ErrorKind::Unknown,
"You cannot request rooms in common with yourself.",
));
}
if !services().users.exists(&body.user_id)? {
return Ok(mutual_rooms::unstable::Response {
joined: vec![],
next_batch_token: None,
});
}
let mutual_rooms: Vec<OwnedRoomId> = services()
.rooms
.user
.get_shared_rooms(vec![sender_user.clone(), body.user_id.clone()])?
.filter_map(Result::ok)
.collect();
Ok(mutual_rooms::unstable::Response {
joined: mutual_rooms,
next_batch_token: None,
})
}
+99 -11
View File
@@ -1,7 +1,14 @@
use std::collections::BTreeMap;
use axum::{response::IntoResponse, Json};
use ruma::api::client::{discovery::get_supported_versions, error::ErrorKind};
use ruma::api::client::{
discovery::{
discover_homeserver::{self, HomeserverInfo, SlidingSyncProxyInfo},
discover_support::{self, Contact},
get_supported_versions,
},
error::ErrorKind,
};
use crate::{services, Error, Result, Ruma};
@@ -38,9 +45,12 @@ pub async fn get_supported_versions_route(
],
unstable_features: BTreeMap::from_iter([
("org.matrix.e2e_cross_signing".to_owned(), true),
("org.matrix.msc2285.stable".to_owned(), true),
("uk.half-shot.msc2666.query_mutual_rooms".to_owned(), true),
("org.matrix.msc2836".to_owned(), true),
("org.matrix.msc3827".to_owned(), true),
("org.matrix.msc2946".to_owned(), true),
("org.matrix.msc3026.busy_presence".to_owned(), true),
("org.matrix.msc3827".to_owned(), true),
]),
};
@@ -48,16 +58,73 @@ pub async fn get_supported_versions_route(
}
/// # `GET /.well-known/matrix/client`
pub async fn well_known_client_route() -> Result<impl IntoResponse> {
///
/// Returns the .well-known URL if it is configured, otherwise returns 404.
pub async fn well_known_client(_body: Ruma<discover_homeserver::Request>) -> Result<discover_homeserver::Response> {
let client_url = match services().globals.well_known_client() {
Some(url) => url.clone(),
Some(url) => url.to_string(),
None => return Err(Error::BadRequest(ErrorKind::NotFound, "Not found.")),
};
Ok(Json(serde_json::json!({
"m.homeserver": {"base_url": client_url},
"org.matrix.msc3575.proxy": {"url": client_url}
})))
Ok(discover_homeserver::Response {
homeserver: HomeserverInfo {
base_url: client_url.clone(),
},
identity_server: None,
sliding_sync_proxy: Some(SlidingSyncProxyInfo {
url: client_url,
}),
tile_server: None,
})
}
/// # `GET /.well-known/matrix/support`
///
/// Server support contact and support page of a homeserver's domain.
pub async fn well_known_support(_body: Ruma<discover_support::Request>) -> Result<discover_support::Response> {
let support_page = services()
.globals
.well_known_support_page()
.as_ref()
.map(ToString::to_string);
let role = services().globals.well_known_support_role().clone();
// support page or role must be either defined for this to be valid
if support_page.is_none() && role.is_none() {
return Err(Error::BadRequest(ErrorKind::NotFound, "Not found."));
}
let email_address = services().globals.well_known_support_email().clone();
let matrix_id = services().globals.well_known_support_mxid().clone();
// if a role is specified, an email address or matrix id is required
if role.is_some() && (email_address.is_none() && matrix_id.is_none()) {
return Err(Error::BadRequest(ErrorKind::NotFound, "Not found."));
}
// TOOD: support defining multiple contacts in the config
let mut contacts: Vec<Contact> = vec![];
if let Some(role) = role {
let contact = Contact {
role,
email_address,
matrix_id,
};
contacts.push(contact);
}
// support page or role+contacts must be either defined for this to be valid
if contacts.is_empty() && support_page.is_none() {
return Err(Error::BadRequest(ErrorKind::NotFound, "Not found."));
}
Ok(discover_support::Response {
contacts,
support_page,
})
}
/// # `GET /client/server.json`
@@ -66,15 +133,36 @@ pub async fn well_known_client_route() -> Result<impl IntoResponse> {
/// Web as a non-standard health check.
pub async fn syncv3_client_server_json() -> Result<impl IntoResponse> {
let server_url = match services().globals.well_known_client() {
Some(url) => url.clone(),
Some(url) => url.to_string(),
None => match services().globals.well_known_server() {
Some(url) => url.clone(),
Some(url) => url.to_string(),
None => return Err(Error::BadRequest(ErrorKind::NotFound, "Not found.")),
},
};
let version = match option_env!("CONDUIT_VERSION_EXTRA") {
Some(extra) => format!("{} ({})", env!("CARGO_PKG_VERSION"), extra),
None => env!("CARGO_PKG_VERSION").to_owned(),
};
Ok(Json(serde_json::json!({
"server": server_url,
"version": format!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
"version": version,
})))
}
/// # `GET /_conduwuit/server_version`
///
/// Conduwuit-specific API to get the server version, results akin to
/// `/_matrix/federation/v1/version`
pub async fn conduwuit_server_version() -> Result<impl IntoResponse> {
let version = match option_env!("CONDUIT_VERSION_EXTRA") {
Some(extra) => format!("{} ({})", env!("CARGO_PKG_VERSION"), extra),
None => env!("CARGO_PKG_VERSION").to_owned(),
};
Ok(Json(serde_json::json!({
"name": "Conduwuit",
"version": version,
})))
}
+28 -11
View File
@@ -29,12 +29,19 @@ pub async fn search_users_route(body: Ruma<search_users::v3::Request>) -> Result
avatar_url: services().users.avatar_url(&user_id).ok()?,
};
let user_id_matches = user.user_id.to_string().to_lowercase().contains(&body.search_term.to_lowercase());
let user_id_matches = user
.user_id
.to_string()
.to_lowercase()
.contains(&body.search_term.to_lowercase());
let user_displayname_matches = user
.display_name
.as_ref()
.filter(|name| name.to_lowercase().contains(&body.search_term.to_lowercase()))
.filter(|name| {
name.to_lowercase()
.contains(&body.search_term.to_lowercase())
})
.is_some();
if !user_id_matches && !user_displayname_matches {
@@ -44,24 +51,34 @@ pub async fn search_users_route(body: Ruma<search_users::v3::Request>) -> Result
// It's a matching user, but is the sender allowed to see them?
let mut user_visible = false;
let user_is_in_public_rooms =
services().rooms.state_cache.rooms_joined(&user_id).filter_map(std::result::Result::ok).any(|room| {
services().rooms.state_accessor.room_state_get(&room, &StateEventType::RoomJoinRules, "").map_or(
false,
|event| {
let user_is_in_public_rooms = services()
.rooms
.state_cache
.rooms_joined(&user_id)
.filter_map(Result::ok)
.any(|room| {
services()
.rooms
.state_accessor
.room_state_get(&room, &StateEventType::RoomJoinRules, "")
.map_or(false, |event| {
event.map_or(false, |event| {
serde_json::from_str(event.content.get())
.map_or(false, |r: RoomJoinRulesEventContent| r.join_rule == JoinRule::Public)
})
},
)
})
});
if user_is_in_public_rooms {
user_visible = true;
} else {
let user_is_in_shared_rooms =
services().rooms.user.get_shared_rooms(vec![sender_user.clone(), user_id]).ok()?.next().is_some();
let user_is_in_shared_rooms = services()
.rooms
.user
.get_shared_rooms(vec![sender_user.clone(), user_id])
.ok()?
.next()
.is_some();
if user_is_in_shared_rooms {
user_visible = true;
-1
View File
@@ -1,4 +1,3 @@
pub mod appservice_server;
pub mod client_server;
pub mod ruma_wrapper;
pub mod server_server;
+214 -199
View File
@@ -12,16 +12,23 @@ use axum::{
BoxError, RequestExt, RequestPartsExt,
};
use bytes::{Buf, BufMut, Bytes, BytesMut};
use http::{Request, StatusCode};
use http::{uri::PathAndQuery, Request, StatusCode};
use ruma::{
api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse},
CanonicalJsonValue, OwnedDeviceId, OwnedServerName, UserId,
CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId, UserId,
};
use serde::Deserialize;
use tracing::{debug, error, warn};
use tracing::{debug, error, trace, warn};
use super::{Ruma, RumaResponse};
use crate::{services, Error, Result};
use crate::{service::appservice::RegistrationInfo, services, Error, Result};
enum Token {
Appservice(Box<RegistrationInfo>),
User((OwnedUserId, OwnedDeviceId)),
Invalid,
None,
}
#[derive(Deserialize)]
struct QueryParams {
@@ -44,14 +51,16 @@ where
let (mut parts, mut body) = match req.with_limited_body() {
Ok(limited_req) => {
let (parts, body) = limited_req.into_parts();
let body =
to_bytes(body).await.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?;
let body = to_bytes(body)
.await
.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?;
(parts, body)
},
Err(original_req) => {
let (parts, body) = original_req.into_parts();
let body =
to_bytes(body).await.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?;
let body = to_bytes(body)
.await
.map_err(|_| Error::BadRequest(ErrorKind::MissingToken, "Missing token."))?;
(parts, body)
},
};
@@ -64,7 +73,7 @@ where
let query_params: QueryParams = match serde_html_form::from_str(query) {
Ok(params) => params,
Err(e) => {
error!(%query, "Failed to deserialize query parameters: {}", e);
error!(%query, "Failed to deserialize query parameters: {e}");
return Err(Error::BadRequest(ErrorKind::Unknown, "Failed to read query parameters"));
},
};
@@ -74,200 +83,196 @@ where
None => query_params.access_token.as_deref(),
};
let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&body).ok();
let appservices = services().appservice.all().unwrap();
let appservice_registration =
appservices.iter().find(|(_id, registration)| Some(registration.as_token.as_str()) == token);
let (sender_user, sender_device, sender_servername, from_appservice) = if let Some((_id, registration)) =
appservice_registration
{
match metadata.authentication {
// TODO: verify if just or'ing `AuthScheme::AppserviceToken` is correct here
AuthScheme::AccessToken | AuthScheme::AccessTokenOptional | AuthScheme::AppserviceToken => {
let user_id = query_params.user_id.map_or_else(
|| {
UserId::parse_with_server_name(
registration.sender_localpart.as_str(),
services().globals.server_name(),
)
.unwrap()
},
|s| UserId::parse(s).unwrap(),
);
if !services().users.exists(&user_id)? {
return Err(Error::BadRequest(ErrorKind::Forbidden, "User does not exist."));
}
// TODO: Check if appservice is allowed to be that user
(Some(user_id), None, None, true)
},
AuthScheme::ServerSignatures => (None, None, None, true),
AuthScheme::None => (None, None, None, true),
let token = if let Some(token) = token {
if let Some(reg_info) = services().appservice.find_from_token(token).await {
Token::Appservice(Box::new(reg_info))
} else if let Some((user_id, device_id)) = services().users.find_from_token(token)? {
Token::User((user_id, OwnedDeviceId::from(device_id)))
} else {
Token::Invalid
}
} else {
match metadata.authentication {
AuthScheme::AccessToken => {
let token = match token {
Some(token) => token,
_ => return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token.")),
};
Token::None
};
match services().users.find_from_token(token)? {
None => {
return Err(Error::BadRequest(
ErrorKind::UnknownToken {
soft_logout: false,
},
"Unknown access token.",
))
},
Some((user_id, device_id)) => {
(Some(user_id), Some(OwnedDeviceId::from(device_id)), None, false)
},
}
},
AuthScheme::AccessTokenOptional => {
let token = token.unwrap_or("");
if token.is_empty() {
(None, None, None, false)
} else {
match services().users.find_from_token(token)? {
None => {
if metadata.authentication == AuthScheme::None {
match parts.uri.path() {
// TODO: can we check this better?
"/_matrix/client/v3/publicRooms" | "/_matrix/client/r0/publicRooms" => {
if !services()
.globals
.config
.allow_public_room_directory_without_auth
{
match token {
Token::Appservice(_) | Token::User(_) => {
// we should have validated the token above
// already
},
Token::None | Token::Invalid => {
return Err(Error::BadRequest(
ErrorKind::UnknownToken {
soft_logout: false,
},
"Unknown access token.",
))
},
Some((user_id, device_id)) => {
(Some(user_id), Some(OwnedDeviceId::from(device_id)), None, false)
ErrorKind::MissingToken,
"Missing or invalid access token.",
));
},
}
}
},
// treat non-appservice registrations as None authentication
AuthScheme::AppserviceToken => (None, None, None, false),
AuthScheme::ServerSignatures => {
if !services().globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled."));
}
_ => {},
};
}
let TypedHeader(Authorization(x_matrix)) =
parts.extract::<TypedHeader<Authorization<XMatrix>>>().await.map_err(|e| {
warn!("Missing or invalid Authorization header: {}", e);
let mut json_body = serde_json::from_slice::<CanonicalJsonValue>(&body).ok();
let msg = match e.reason() {
TypedHeaderRejectionReason::Missing => "Missing Authorization header.",
TypedHeaderRejectionReason::Error(_) => "Invalid X-Matrix signatures.",
_ => "Unknown header-related error",
};
Error::BadRequest(ErrorKind::Forbidden, msg)
})?;
let origin_signatures =
BTreeMap::from_iter([(x_matrix.key.clone(), CanonicalJsonValue::String(x_matrix.sig))]);
let signatures = BTreeMap::from_iter([(
x_matrix.origin.as_str().to_owned(),
CanonicalJsonValue::Object(origin_signatures),
)]);
let server_destination = services().globals.server_name().as_str().to_owned();
if let Some(destination) = x_matrix.destination.as_ref() {
if destination != &server_destination {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Invalid authorization."));
}
}
let mut request_map = BTreeMap::from_iter([
("method".to_owned(), CanonicalJsonValue::String(parts.method.to_string())),
("uri".to_owned(), CanonicalJsonValue::String(parts.uri.to_string())),
(
"origin".to_owned(),
CanonicalJsonValue::String(x_matrix.origin.as_str().to_owned()),
),
("destination".to_owned(), CanonicalJsonValue::String(server_destination)),
("signatures".to_owned(), CanonicalJsonValue::Object(signatures)),
]);
if let Some(json_body) = &json_body {
request_map.insert("content".to_owned(), json_body.clone());
};
let keys_result = services()
.rooms
.event_handler
.fetch_signing_keys_for_server(&x_matrix.origin, vec![x_matrix.key.clone()])
.await;
let keys = match keys_result {
Ok(b) => b,
Err(e) => {
warn!("Failed to fetch signing keys: {}", e);
return Err(Error::BadRequest(ErrorKind::Forbidden, "Failed to fetch signing keys."));
},
};
let pub_key_map = BTreeMap::from_iter([(x_matrix.origin.as_str().to_owned(), keys)]);
match ruma::signatures::verify_json(&pub_key_map, &request_map) {
Ok(()) => (None, None, Some(x_matrix.origin), false),
Err(e) => {
warn!(
"Failed to verify json request from {}: {}\n{:?}",
x_matrix.origin, e, request_map
);
if parts.uri.to_string().contains('@') {
warn!(
"Request uri contained '@' character. Make sure your reverse proxy gives Conduit \
the raw uri (apache: use nocanon)"
);
}
return Err(Error::BadRequest(
ErrorKind::Forbidden,
"Failed to verify X-Matrix signatures.",
));
},
}
},
AuthScheme::None => match parts.uri.path() {
// allow_public_room_directory_without_auth
"/_matrix/client/v3/publicRooms" | "/_matrix/client/r0/publicRooms" => {
if !services().globals.config.allow_public_room_directory_without_auth {
let token = match token {
Some(token) => token,
_ => return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token.")),
};
match services().users.find_from_token(token)? {
None => {
return Err(Error::BadRequest(
ErrorKind::UnknownToken {
soft_logout: false,
},
"Unknown access token.",
))
},
Some((user_id, device_id)) => {
(Some(user_id), Some(OwnedDeviceId::from(device_id)), None, false)
},
}
} else {
(None, None, None, false)
}
let (sender_user, sender_device, sender_servername, appservice_info) = match (metadata.authentication, token) {
(_, Token::Invalid) => {
return Err(Error::BadRequest(
ErrorKind::UnknownToken {
soft_logout: false,
},
_ => (None, None, None, false),
},
}
"Unknown access token.",
))
},
(AuthScheme::AccessToken | AuthScheme::AccessTokenOptional, Token::Appservice(info)) => {
let user_id = query_params
.user_id
.map_or_else(
|| {
UserId::parse_with_server_name(
info.registration.sender_localpart.as_str(),
services().globals.server_name(),
)
},
UserId::parse,
)
.map_err(|_| Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?;
if !info.is_user_match(&user_id) {
return Err(Error::BadRequest(ErrorKind::Exclusive, "User is not in namespace."));
}
if !services().users.exists(&user_id)? {
return Err(Error::BadRequest(ErrorKind::forbidden(), "User does not exist."));
}
(Some(user_id), None, None, Some(*info))
},
(AuthScheme::None | AuthScheme::AppserviceToken, Token::Appservice(info)) => {
(None, None, None, Some(*info))
},
(AuthScheme::AccessToken, Token::None) => {
return Err(Error::BadRequest(ErrorKind::MissingToken, "Missing access token."));
},
(
AuthScheme::AccessToken | AuthScheme::AccessTokenOptional | AuthScheme::None,
Token::User((user_id, device_id)),
) => (Some(user_id), Some(device_id), None, None),
(AuthScheme::ServerSignatures, Token::None) => {
if !services().globals.allow_federation() {
return Err(Error::bad_config("Federation is disabled."));
}
let TypedHeader(Authorization(x_matrix)) = parts
.extract::<TypedHeader<Authorization<XMatrix>>>()
.await
.map_err(|e| {
warn!("Missing or invalid Authorization header: {e}");
let msg = match e.reason() {
TypedHeaderRejectionReason::Missing => "Missing Authorization header.",
TypedHeaderRejectionReason::Error(_) => "Invalid X-Matrix signatures.",
_ => "Unknown header-related error",
};
Error::BadRequest(ErrorKind::forbidden(), msg)
})?;
let origin_signatures =
BTreeMap::from_iter([(x_matrix.key.clone(), CanonicalJsonValue::String(x_matrix.sig))]);
let signatures = BTreeMap::from_iter([(
x_matrix.origin.as_str().to_owned(),
CanonicalJsonValue::Object(origin_signatures),
)]);
let server_destination = services().globals.server_name().as_str().to_owned();
if let Some(destination) = x_matrix.destination.as_ref() {
if destination != &server_destination {
return Err(Error::BadRequest(ErrorKind::forbidden(), "Invalid authorization."));
}
}
let signature_uri = CanonicalJsonValue::String(
parts
.uri
.path_and_query()
.unwrap_or(&PathAndQuery::from_static("/"))
.to_string(),
);
let mut request_map = BTreeMap::from_iter([
("method".to_owned(), CanonicalJsonValue::String(parts.method.to_string())),
("uri".to_owned(), signature_uri),
(
"origin".to_owned(),
CanonicalJsonValue::String(x_matrix.origin.as_str().to_owned()),
),
("destination".to_owned(), CanonicalJsonValue::String(server_destination)),
("signatures".to_owned(), CanonicalJsonValue::Object(signatures)),
]);
if let Some(json_body) = &json_body {
request_map.insert("content".to_owned(), json_body.clone());
};
let keys_result = services()
.rooms
.event_handler
.fetch_signing_keys_for_server(&x_matrix.origin, vec![x_matrix.key.clone()])
.await;
let keys = keys_result.map_err(|e| {
warn!("Failed to fetch signing keys: {e}");
Error::BadRequest(ErrorKind::forbidden(), "Failed to fetch signing keys.")
})?;
let pub_key_map = BTreeMap::from_iter([(x_matrix.origin.as_str().to_owned(), keys)]);
match ruma::signatures::verify_json(&pub_key_map, &request_map) {
Ok(()) => (None, None, Some(x_matrix.origin), None),
Err(e) => {
warn!("Failed to verify json request from {}: {e}\n{request_map:?}", x_matrix.origin);
if parts.uri.to_string().contains('@') {
warn!(
"Request uri contained '@' character. Make sure your reverse proxy gives Conduit the \
raw uri (apache: use nocanon)"
);
}
return Err(Error::BadRequest(
ErrorKind::forbidden(),
"Failed to verify X-Matrix signatures.",
));
},
}
},
(AuthScheme::None | AuthScheme::AppserviceToken | AuthScheme::AccessTokenOptional, Token::None) => {
(None, None, None, None)
},
(AuthScheme::ServerSignatures, Token::Appservice(_) | Token::User(_)) => {
return Err(Error::BadRequest(
ErrorKind::Unauthorized,
"Only server signatures should be used on this endpoint.",
));
},
(AuthScheme::AppserviceToken, Token::User(_)) => {
return Err(Error::BadRequest(
ErrorKind::Unauthorized,
"Only appservice access tokens should be used on this endpoint.",
));
},
};
let mut http_request = Request::builder().uri(parts.uri).method(parts.method);
@@ -303,11 +308,16 @@ where
}
let http_request = http_request.body(&*body).unwrap();
debug!(
"{:?} {:?} {:?}",
http_request.method(),
http_request.uri(),
http_request.headers()
);
debug!("{:?}", http_request);
trace!("{:?} {:?} {:?}", http_request.method(), http_request.uri(), json_body);
let body = T::try_from_http_request(http_request, &path_params).map_err(|e| {
warn!("try_from_http_request failed: {:?}", e);
warn!("try_from_http_request failed: {e:?}\nPath parameters: {path_params:?}",);
debug!("JSON body: {:?}", json_body);
Error::BadRequest(ErrorKind::BadJson, "Failed to deserialize request.")
})?;
@@ -317,8 +327,8 @@ where
sender_user,
sender_device,
sender_servername,
from_appservice,
json_body,
appservice_info,
})
}
}
@@ -339,7 +349,9 @@ impl Credentials for XMatrix {
"HeaderValue to decode should start with \"X-Matrix ..\", received = {value:?}",
);
let parameters = str::from_utf8(&value.as_bytes()["X-Matrix ".len()..]).ok()?.trim_start();
let parameters = str::from_utf8(&value.as_bytes()["X-Matrix ".len()..])
.ok()?
.trim_start();
let mut origin = None;
let mut destination = None;
@@ -351,7 +363,10 @@ impl Credentials for XMatrix {
// It's not at all clear why some fields are quoted and others not in the spec,
// let's simply accept either form for every field.
let value = value.strip_prefix('"').and_then(|rest| rest.strip_suffix('"')).unwrap_or(value);
let value = value
.strip_prefix('"')
.and_then(|rest| rest.strip_suffix('"'))
.unwrap_or(value);
// FIXME: Catch multiple fields of the same name
match name {
@@ -359,7 +374,7 @@ impl Credentials for XMatrix {
"key" => key = Some(value.to_owned()),
"sig" => sig = Some(value.to_owned()),
"destination" => destination = Some(value.to_owned()),
_ => debug!("Unexpected field `{}` in X-Matrix Authorization header", name),
_ => debug!("Unexpected field `{name}` in X-Matrix Authorization header"),
}
}
+2 -3
View File
@@ -2,9 +2,8 @@ use std::ops::Deref;
use ruma::{api::client::uiaa::UiaaResponse, CanonicalJsonValue, OwnedDeviceId, OwnedServerName, OwnedUserId};
use crate::Error;
use crate::{service::appservice::RegistrationInfo, Error};
#[cfg(feature = "conduit_bin")]
mod axum;
/// Extractor for Ruma request structs
@@ -15,7 +14,7 @@ pub struct Ruma<T> {
pub sender_servername: Option<OwnedServerName>,
// This is None when body is not a valid string
pub json_body: Option<CanonicalJsonValue>,
pub from_appservice: bool,
pub appservice_info: Option<RegistrationInfo>,
}
impl<T> Deref for Ruma<T> {
+950 -843
View File
File diff suppressed because it is too large Load Diff
+18 -39
View File
@@ -2,53 +2,32 @@
use std::path::PathBuf;
use clap::{Parser, Subcommand};
use clap::Parser;
/// Returns the current version of the crate with extra info if supplied
///
/// Set the environment variable `CONDUIT_VERSION_EXTRA` to any UTF-8 string to
/// include it in parenthesis after the SemVer version. A common value are git
/// commit hashes.
#[allow(clippy::doc_markdown)]
fn version() -> String {
let cargo_pkg_version = env!("CARGO_PKG_VERSION");
match option_env!("CONDUIT_VERSION_EXTRA") {
Some(x) => format!("{} ({})", cargo_pkg_version, x),
None => cargo_pkg_version.to_owned(),
}
}
/// Commandline arguments
#[derive(Parser, Debug)]
#[clap(version, about, long_about = None)]
#[clap(version = version(), about, long_about = None)]
pub struct Args {
#[arg(short, long)]
/// Optional argument to the path of a conduwuit config TOML file
pub config: Option<PathBuf>,
#[clap(subcommand)]
/// Optional subcommand to export the homeserver signing key and exit
pub signing_key: Option<SigningKey>,
}
#[derive(Debug, Subcommand)]
pub enum SigningKey {
/// Filesystem path to export the homeserver signing key to.
/// The output will be: `ed25519 <version> <keypair base64 encoded>` which
/// is Synapse's format
ExportPath {
path: PathBuf,
},
/// Filesystem path for conduwuit to attempt to read and import the
/// homeserver signing key. The expected format is Synapse's format:
/// `ed25519 <version> <keypair base64 encoded>`
ImportPath {
path: PathBuf,
#[arg(long)]
/// Optional argument to import the key but don't overwrite our signing
/// key, and instead add it to `old_verify_keys`. This field tells other
/// servers that this is our old public key that can still be used to
/// sign old events.
///
/// See https://spec.matrix.org/v1.9/server-server-api/#get_matrixkeyv2server for more details.
add_to_old_public_keys: bool,
#[arg(long)]
/// Timestamp (`expired_ts`) in seconds since UNIX epoch that the old
/// homeserver signing key stopped being used.
///
/// See https://spec.matrix.org/v1.9/server-server-api/#get_matrixkeyv2server for more details.
timestamp: u64,
},
}
/// Parse commandline arguments into structured data
#[must_use]
pub fn parse() -> Args { Args::parse() }
+166
View File
@@ -0,0 +1,166 @@
#[cfg(unix)]
use std::path::Path; // not unix specific, just only for UNIX sockets stuff and *nix container checks
use tracing::{debug, error, info, warn};
use crate::{utils::error::Error, Config};
pub fn check(config: &Config) -> Result<(), Error> {
config.warn_deprecated();
config.warn_unknown_key();
if cfg!(feature = "hardened_malloc") && cfg!(feature = "jemalloc") {
warn!(
"hardened_malloc and jemalloc were built together, this causes neither to be used. Conduwuit will still \
function, but consider rebuilding and pick one as this is now no-op."
);
}
if config.unix_socket_path.is_some() && !cfg!(unix) {
return Err(Error::bad_config(
"UNIX socket support is only available on *nix platforms. Please remove \"unix_socket_path\" from your \
config.",
));
}
if config.address.is_loopback() && cfg!(unix) {
debug!(
"Found loopback listening address {}, running checks if we're in a container.",
config.address
);
#[cfg(unix)]
if Path::new("/proc/vz").exists() /* Guest */ && !Path::new("/proc/bz").exists()
/* Host */
{
error!(
"You are detected using OpenVZ with a loopback/localhost listening address of {}. If you are using \
OpenVZ for containers and you use NAT-based networking to communicate with the host and guest, this \
will NOT work. Please change this to \"0.0.0.0\". If this is expected, you can ignore.",
config.address
);
}
#[cfg(unix)]
if Path::new("/.dockerenv").exists() {
error!(
"You are detected using Docker with a loopback/localhost listening address of {}. If you are using a \
reverse proxy on the host and require communication to conduwuit in the Docker container via \
NAT-based networking, this will NOT work. Please change this to \"0.0.0.0\". If this is expected, \
you can ignore.",
config.address
);
}
#[cfg(unix)]
if Path::new("/run/.containerenv").exists() {
error!(
"You are detected using Podman with a loopback/localhost listening address of {}. If you are using a \
reverse proxy on the host and require communication to conduwuit in the Podman container via \
NAT-based networking, this will NOT work. Please change this to \"0.0.0.0\". If this is expected, \
you can ignore.",
config.address
);
}
}
// rocksdb does not allow max_log_files to be 0
if config.rocksdb_max_log_files == 0 && cfg!(feature = "rocksdb") {
return Err(Error::bad_config(
"When using RocksDB, rocksdb_max_log_files cannot be 0. Please set a value at least 1.",
));
}
// yeah, unless the user built a debug build hopefully for local testing only
if config.server_name == "your.server.name" && !cfg!(debug_assertions) {
return Err(Error::bad_config(
"You must specify a valid server name for production usage of conduwuit.",
));
}
if cfg!(debug_assertions) {
info!("Note: conduwuit was built without optimisations (i.e. debug build)");
}
// check if the user specified a registration token as `""`
if config.registration_token == Some(String::new()) {
return Err(Error::bad_config("Registration token was specified but is empty (\"\")"));
}
if config.max_request_size < 16384 {
return Err(Error::bad_config("Max request size is less than 16KB. Please increase it."));
}
// check if user specified valid IP CIDR ranges on startup
for cidr in &config.ip_range_denylist {
if let Err(e) = ipaddress::IPAddress::parse(cidr) {
error!("Error parsing specified IP CIDR range from string: {e}");
return Err(Error::bad_config("Error parsing specified IP CIDR ranges from strings"));
}
}
if config.allow_registration
&& !config.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse
&& config.registration_token.is_none()
{
return Err(Error::bad_config(
"!! You have `allow_registration` enabled without a token configured in your config which means you are \
allowing ANYONE to register on your conduwuit instance without any 2nd-step (e.g. registration token).\n
If this is not the intended behaviour, please set a registration token with the `registration_token` config option.\n
For security and safety reasons, conduwuit will shut down. If you are extra sure this is the desired behaviour you \
want, please set the following config option to true:
`yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse`",
));
}
if config.allow_registration
&& config.yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse
&& config.registration_token.is_none()
{
warn!(
"Open registration is enabled via setting \
`yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse` and `allow_registration` to \
true without a registration token configured. You are expected to be aware of the risks now.\n
If this is not the desired behaviour, please set a registration token."
);
}
if config.allow_outgoing_presence && !config.allow_local_presence {
return Err(Error::bad_config(
"Outgoing presence requires allowing local presence. Please enable \"allow_local_presence\".",
));
}
if config
.url_preview_domain_contains_allowlist
.contains(&"*".to_owned())
{
warn!(
"All URLs are allowed for URL previews via setting \"url_preview_domain_contains_allowlist\" to \"*\". \
This opens up significant attack surface to your server. You are expected to be aware of the risks by \
doing this."
);
}
if config
.url_preview_domain_explicit_allowlist
.contains(&"*".to_owned())
{
warn!(
"All URLs are allowed for URL previews via setting \"url_preview_domain_explicit_allowlist\" to \"*\". \
This opens up significant attack surface to your server. You are expected to be aware of the risks by \
doing this."
);
}
if config
.url_preview_url_contains_allowlist
.contains(&"*".to_owned())
{
warn!(
"All URLs are allowed for URL previews via setting \"url_preview_url_contains_allowlist\" to \"*\". This \
opens up significant attack surface to your server. You are expected to be aware of the risks by doing \
this."
);
}
Ok(())
}
+486 -36
View File
@@ -1,21 +1,31 @@
use std::{
collections::BTreeMap,
fmt,
fmt::Write as _,
net::{IpAddr, Ipv4Addr},
fmt::{self, Write as _},
net::{IpAddr, Ipv4Addr, SocketAddr},
path::PathBuf,
};
use either::Either;
use figment::Figment;
use either::{
Either,
Either::{Left, Right},
};
use figment::{
providers::{Env, Format, Toml},
Figment,
};
use itertools::Itertools;
use regex::RegexSet;
use ruma::{OwnedServerName, RoomVersionId};
use ruma::{
api::client::discovery::discover_support::ContactRole, OwnedRoomId, OwnedServerName, OwnedUserId, RoomVersionId,
};
use serde::{de::IgnoredAny, Deserialize};
use tracing::{debug, error, warn};
use url::Url;
use self::proxy::ProxyConfig;
use crate::utils::error::Error;
mod check;
mod proxy;
#[derive(Deserialize, Clone, Debug)]
@@ -27,6 +37,7 @@ pub struct ListeningPort {
/// all the config options for conduwuit
#[derive(Clone, Debug, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct Config {
/// [`IpAddr`] conduwuit will listen on (can be IPv4 or IPv6)
#[serde(default = "default_address")]
@@ -41,25 +52,90 @@ pub struct Config {
pub server_name: OwnedServerName,
#[serde(default = "default_database_backend")]
pub database_backend: String,
pub database_path: String,
pub database_path: PathBuf,
pub database_backup_path: Option<PathBuf>,
#[serde(default = "default_database_backups_to_keep")]
pub database_backups_to_keep: i16,
#[serde(default = "default_db_cache_capacity_mb")]
pub db_cache_capacity_mb: f64,
#[serde(default = "default_new_user_displayname_suffix")]
pub new_user_displayname_suffix: String,
#[serde(default)]
pub allow_check_for_updates: bool,
#[serde(default = "default_conduit_cache_capacity_modifier")]
pub conduit_cache_capacity_modifier: f64,
#[serde(default = "default_pdu_cache_capacity")]
pub pdu_cache_capacity: u32,
#[serde(default = "default_conduit_cache_capacity_modifier")]
pub conduit_cache_capacity_modifier: f64,
#[serde(default = "default_auth_chain_cache_capacity")]
pub auth_chain_cache_capacity: u32,
#[serde(default = "default_shorteventid_cache_capacity")]
pub shorteventid_cache_capacity: u32,
#[serde(default = "default_eventidshort_cache_capacity")]
pub eventidshort_cache_capacity: u32,
#[serde(default = "default_shortstatekey_cache_capacity")]
pub shortstatekey_cache_capacity: u32,
#[serde(default = "default_statekeyshort_cache_capacity")]
pub statekeyshort_cache_capacity: u32,
#[serde(default = "default_server_visibility_cache_capacity")]
pub server_visibility_cache_capacity: u32,
#[serde(default = "default_user_visibility_cache_capacity")]
pub user_visibility_cache_capacity: u32,
#[serde(default = "default_stateinfo_cache_capacity")]
pub stateinfo_cache_capacity: u32,
#[serde(default = "default_roomid_spacehierarchy_cache_capacity")]
pub roomid_spacehierarchy_cache_capacity: u32,
#[serde(default = "default_cleanup_second_interval")]
pub cleanup_second_interval: u32,
#[serde(default = "default_dns_cache_entries")]
pub dns_cache_entries: u32,
#[serde(default = "default_dns_min_ttl")]
pub dns_min_ttl: u64,
#[serde(default = "default_dns_min_ttl_nxdomain")]
pub dns_min_ttl_nxdomain: u64,
#[serde(default = "default_dns_attempts")]
pub dns_attempts: u16,
#[serde(default = "default_dns_timeout")]
pub dns_timeout: u64,
#[serde(default = "true_fn")]
pub dns_tcp_fallback: bool,
#[serde(default = "true_fn")]
pub query_all_nameservers: bool,
#[serde(default = "default_max_request_size")]
pub max_request_size: u32,
#[serde(default = "default_max_concurrent_requests")]
pub max_concurrent_requests: u16,
#[serde(default = "default_max_fetch_prev_events")]
pub max_fetch_prev_events: u16,
#[serde(default = "default_request_conn_timeout")]
pub request_conn_timeout: u64,
#[serde(default = "default_request_timeout")]
pub request_timeout: u64,
#[serde(default = "default_request_idle_per_host")]
pub request_idle_per_host: u16,
#[serde(default = "default_request_idle_timeout")]
pub request_idle_timeout: u64,
#[serde(default = "default_well_known_conn_timeout")]
pub well_known_conn_timeout: u64,
#[serde(default = "default_well_known_timeout")]
pub well_known_timeout: u64,
#[serde(default = "default_federation_timeout")]
pub federation_timeout: u64,
#[serde(default = "default_federation_idle_per_host")]
pub federation_idle_per_host: u16,
#[serde(default = "default_federation_idle_timeout")]
pub federation_idle_timeout: u64,
#[serde(default = "default_sender_timeout")]
pub sender_timeout: u64,
#[serde(default = "default_sender_idle_timeout")]
pub sender_idle_timeout: u64,
#[serde(default = "default_appservice_timeout")]
pub appservice_timeout: u64,
#[serde(default = "default_appservice_idle_timeout")]
pub appservice_idle_timeout: u64,
#[serde(default = "default_pusher_idle_timeout")]
pub pusher_idle_timeout: u64,
#[serde(default)]
pub allow_registration: bool,
#[serde(default)]
@@ -74,15 +150,19 @@ pub struct Config {
#[serde(default)]
pub allow_public_room_directory_without_auth: bool,
#[serde(default)]
pub lockdown_public_room_directory: bool,
#[serde(default)]
pub allow_device_name_federation: bool,
#[serde(default = "true_fn")]
pub allow_profile_lookup_federation_requests: bool,
#[serde(default = "true_fn")]
pub allow_room_creation: bool,
#[serde(default = "true_fn")]
pub allow_unstable_room_versions: bool,
#[serde(default = "default_default_room_version")]
pub default_room_version: RoomVersionId,
pub well_known_client: Option<String>,
pub well_known_server: Option<String>,
#[serde(default)]
pub well_known: WellKnownConfig,
#[serde(default)]
pub allow_jaeger: bool,
#[serde(default)]
@@ -107,8 +187,13 @@ pub struct Config {
#[serde(default = "default_turn_ttl")]
pub turn_ttl: u64,
#[serde(default = "Vec::new")]
pub auto_join_rooms: Vec<OwnedRoomId>,
#[serde(default = "default_rocksdb_log_level")]
pub rocksdb_log_level: String,
#[serde(default)]
pub rocksdb_log_stderr: bool,
#[serde(default = "default_rocksdb_max_log_file_size")]
pub rocksdb_max_log_file_size: usize,
#[serde(default = "default_rocksdb_log_time_to_roll")]
@@ -127,34 +212,69 @@ pub struct Config {
pub rocksdb_bottommost_compression_level: i32,
#[serde(default)]
pub rocksdb_bottommost_compression: bool,
#[serde(default = "default_rocksdb_recovery_mode")]
pub rocksdb_recovery_mode: u8,
#[serde(default)]
pub rocksdb_repair: bool,
#[serde(default)]
pub rocksdb_read_only: bool,
#[serde(default)]
pub rocksdb_periodic_cleanup: bool,
pub emergency_password: Option<String>,
#[serde(default = "default_notification_push_path")]
pub notification_push_path: String,
#[serde(default)]
#[serde(default = "true_fn")]
pub allow_local_presence: bool,
#[serde(default)]
#[serde(default = "true_fn")]
pub allow_incoming_presence: bool,
#[serde(default)]
#[serde(default = "true_fn")]
pub allow_outgoing_presence: bool,
#[serde(default = "default_presence_idle_timeout_s")]
pub presence_idle_timeout_s: u64,
#[serde(default = "default_presence_offline_timeout_s")]
pub presence_offline_timeout_s: u64,
#[serde(default = "true_fn")]
pub presence_timeout_remote_users: bool,
#[serde(default = "true_fn")]
pub allow_incoming_read_receipts: bool,
#[serde(default = "true_fn")]
pub allow_outgoing_read_receipts: bool,
#[serde(default = "true_fn")]
pub allow_outgoing_typing: bool,
#[serde(default = "true_fn")]
pub allow_incoming_typing: bool,
#[serde(default = "default_typing_federation_timeout_s")]
pub typing_federation_timeout_s: u64,
#[serde(default = "default_typing_client_timeout_min_s")]
pub typing_client_timeout_min_s: u64,
#[serde(default = "default_typing_client_timeout_max_s")]
pub typing_client_timeout_max_s: u64,
#[serde(default)]
pub zstd_compression: bool,
#[serde(default)]
pub gzip_compression: bool,
#[serde(default)]
pub brotli_compression: bool,
#[serde(default)]
pub allow_guest_registration: bool,
#[serde(default)]
pub log_guest_registrations: bool,
#[serde(default)]
pub allow_guests_auto_join_rooms: bool,
#[serde(default = "Vec::new")]
pub prevent_media_downloads_from: Vec<OwnedServerName>,
#[serde(default = "Vec::new")]
pub forbidden_remote_server_names: Vec<OwnedServerName>,
#[serde(default = "Vec::new")]
pub forbidden_remote_room_directory_server_names: Vec<OwnedServerName>,
#[serde(default = "default_ip_range_denylist")]
pub ip_range_denylist: Vec<String>,
@@ -164,6 +284,8 @@ pub struct Config {
#[serde(default = "Vec::new")]
pub url_preview_domain_explicit_allowlist: Vec<String>,
#[serde(default = "Vec::new")]
pub url_preview_domain_explicit_denylist: Vec<String>,
#[serde(default = "Vec::new")]
pub url_preview_url_contains_allowlist: Vec<String>,
#[serde(default = "default_url_preview_max_spider_size")]
pub url_preview_max_spider_size: usize,
@@ -172,16 +294,29 @@ pub struct Config {
#[serde(default = "RegexSet::empty")]
#[serde(with = "serde_regex")]
pub forbidden_room_names: RegexSet,
pub forbidden_alias_names: RegexSet,
#[serde(default = "RegexSet::empty")]
#[serde(with = "serde_regex")]
pub forbidden_usernames: RegexSet,
#[serde(default = "true_fn")]
pub startup_netburst: bool,
#[serde(default = "default_startup_netburst_keep")]
pub startup_netburst_keep: i64,
#[serde(default)]
pub block_non_admin_invites: bool,
#[serde(default)]
pub sentry: bool,
#[serde(default)]
pub sentry_send_server_name: bool,
#[serde(default = "default_sentry_traces_sample_rate")]
pub sentry_traces_sample_rate: f32,
#[serde(flatten)]
#[allow(clippy::zero_sized_map_values)] // this is a catchall, the map shouldn't be zero at runtime
pub catchall: BTreeMap<String, IgnoredAny>,
}
@@ -196,23 +331,74 @@ pub struct TlsConfig {
pub dual_protocol: bool,
}
const DEPRECATED_KEYS: &[&str] = &["cache_capacity"];
#[derive(Clone, Debug, Deserialize, Default)]
pub struct WellKnownConfig {
pub client: Option<Url>,
pub server: Option<OwnedServerName>,
pub support_page: Option<Url>,
pub support_role: Option<ContactRole>,
pub support_email: Option<String>,
pub support_mxid: Option<OwnedUserId>,
}
const DEPRECATED_KEYS: &[&str] = &[
"cache_capacity",
"well_known_client",
"well_known_server",
"well_known_support_page",
"well_known_support_role",
"well_known_support_email",
"well_known_support_mxid",
];
impl Config {
/// Initialize config
pub fn new(path: Option<PathBuf>) -> Result<Self, Error> {
let raw_config = if let Some(config_file_env) = Env::var("CONDUIT_CONFIG") {
Figment::new()
.merge(Toml::file(config_file_env).nested())
.merge(Env::prefixed("CONDUIT_").global())
} else if let Some(config_file_arg) = path {
Figment::new()
.merge(Toml::file(config_file_arg).nested())
.merge(Env::prefixed("CONDUIT_").global())
} else {
Figment::new().merge(Env::prefixed("CONDUIT_").global())
};
let config = match raw_config.extract::<Config>() {
Err(e) => return Err(Error::BadConfig(format!("{e}"))),
Ok(config) => config,
};
check::check(&config)?;
// don't start if we're listening on both UNIX sockets and TCP at same time
if config.is_dual_listening(&raw_config) {
return Err(Error::bad_config("dual listening on UNIX and TCP sockets not allowed."));
};
Ok(config)
}
/// Iterates over all the keys in the config file and warns if there is a
/// deprecated key specified
pub fn warn_deprecated(&self) {
debug!("Checking for deprecated config keys");
let mut was_deprecated = false;
for key in self.catchall.keys().filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key)) {
for key in self
.catchall
.keys()
.filter(|key| DEPRECATED_KEYS.iter().any(|s| s == key))
{
warn!("Config parameter \"{}\" is deprecated, ignoring.", key);
was_deprecated = true;
}
if was_deprecated {
warn!(
"Read conduit documentation and check your configuration if any new configuration parameters should \
be adjusted"
"Read conduwuit config documentation at https://conduwuit.puppyirl.gay/configuration.html and check \
your configuration if any new configuration parameters should be adjusted"
);
}
}
@@ -221,8 +407,10 @@ impl Config {
/// if there are any.
pub fn warn_unknown_key(&self) {
debug!("Checking for unknown config keys");
for key in
self.catchall.keys().filter(|key| "config".to_owned().ne(key.to_owned()) /* "config" is expected */)
for key in self
.catchall
.keys()
.filter(|key| "config".to_owned().ne(key.to_owned()) /* "config" is expected */)
{
warn!("Config parameter \"{}\" is unknown to conduwuit, ignoring.", key);
}
@@ -230,7 +418,7 @@ impl Config {
/// Checks the presence of the `address` and `unix_socket_path` keys in the
/// raw_config, exiting the process if both keys were detected.
pub fn is_dual_listening(&self, raw_config: &Figment) -> bool {
fn is_dual_listening(&self, raw_config: &Figment) -> bool {
let check_address = raw_config.find_value("address");
let check_unix_socket = raw_config.find_value("unix_socket_path");
@@ -243,6 +431,27 @@ impl Config {
false
}
#[must_use]
pub fn get_bind_addrs(&self) -> Vec<SocketAddr> {
match &self.port.ports {
Left(port) => {
// Left is only 1 value, so make a vec with 1 value only
let port_vec = [port];
port_vec
.iter()
.copied()
.map(|port| SocketAddr::from((self.address, *port)))
.collect::<Vec<_>>()
},
Right(ports) => ports
.iter()
.copied()
.map(|port| SocketAddr::from((self.address, port)))
.collect::<Vec<_>>(),
}
}
}
impl fmt::Display for Config {
@@ -251,13 +460,60 @@ impl fmt::Display for Config {
let lines = [
("Server name", self.server_name.host()),
("Database backend", &self.database_backend),
("Database path", &self.database_path),
("Database path", &self.database_path.to_string_lossy()),
(
"Database backup path",
match &self.database_backup_path {
Some(path) => path.to_str().unwrap(),
None => "",
},
),
("Database backups to keep", &self.database_backups_to_keep.to_string()),
("Database cache capacity (MB)", &self.db_cache_capacity_mb.to_string()),
("Cache capacity modifier", &self.conduit_cache_capacity_modifier.to_string()),
("PDU cache capacity", &self.pdu_cache_capacity.to_string()),
("Auth chain cache capacity", &self.auth_chain_cache_capacity.to_string()),
("Short eventid cache capacity", &self.shorteventid_cache_capacity.to_string()),
("Eventid short cache capacity", &self.eventidshort_cache_capacity.to_string()),
("Short statekey cache capacity", &self.shortstatekey_cache_capacity.to_string()),
("Statekey short cache capacity", &self.statekeyshort_cache_capacity.to_string()),
(
"Server visibility cache capacity",
&self.server_visibility_cache_capacity.to_string(),
),
(
"User visibility cache capacity",
&self.user_visibility_cache_capacity.to_string(),
),
("Stateinfo cache capacity", &self.stateinfo_cache_capacity.to_string()),
(
"Roomid space hierarchy cache capacity",
&self.roomid_spacehierarchy_cache_capacity.to_string(),
),
("Cleanup interval in seconds", &self.cleanup_second_interval.to_string()),
("DNS cache entry limit", &self.dns_cache_entries.to_string()),
("DNS minimum ttl", &self.dns_min_ttl.to_string()),
("DNS minimum nxdomain ttl", &self.dns_min_ttl_nxdomain.to_string()),
("DNS attempts", &self.dns_attempts.to_string()),
("DNS timeout", &self.dns_timeout.to_string()),
("DNS fallback to TCP", &self.dns_tcp_fallback.to_string()),
("Query all nameservers", &self.query_all_nameservers.to_string()),
("Maximum request size (bytes)", &self.max_request_size.to_string()),
("Maximum concurrent requests", &self.max_concurrent_requests.to_string()),
("Request connect timeout", &self.request_conn_timeout.to_string()),
("Request timeout", &self.request_timeout.to_string()),
("Idle connections per host", &self.request_idle_per_host.to_string()),
("Request pool idle timeout", &self.request_idle_timeout.to_string()),
("Well_known connect timeout", &self.well_known_conn_timeout.to_string()),
("Well_known timeout", &self.well_known_timeout.to_string()),
("Federation timeout", &self.federation_timeout.to_string()),
("Federation pool idle per host", &self.federation_idle_per_host.to_string()),
("Federation pool idle timeout", &self.federation_idle_timeout.to_string()),
("Sender timeout", &self.sender_timeout.to_string()),
("Sender pool idle timeout", &self.sender_idle_timeout.to_string()),
("Appservice timeout", &self.appservice_timeout.to_string()),
("Appservice pool idle timeout", &self.appservice_idle_timeout.to_string()),
("Pusher pool idle timeout", &self.pusher_idle_timeout.to_string()),
("Allow registration", &self.allow_registration.to_string()),
(
"Registration token",
@@ -270,6 +526,14 @@ impl fmt::Display for Config {
"Allow guest registration (inherently false if allow registration is false)",
&self.allow_guest_registration.to_string(),
),
(
"Log guest registrations in admin room",
&self.log_guest_registrations.to_string(),
),
(
"Allow guests to auto join rooms",
&self.allow_guests_auto_join_rooms.to_string(),
),
("New user display name suffix", &self.new_user_displayname_suffix),
("Allow encryption", &self.allow_encryption.to_string()),
("Allow federation", &self.allow_federation.to_string()),
@@ -289,11 +553,27 @@ impl fmt::Display for Config {
"Allow incoming remote read receipts",
&self.allow_incoming_read_receipts.to_string(),
),
(
"Allow outgoing remote read receipts",
&self.allow_outgoing_read_receipts.to_string(),
),
(
"Block non-admin room invites (local and remote, admins can still send and receive invites)",
&self.block_non_admin_invites.to_string(),
),
("Allow outgoing federated typing", &self.allow_outgoing_typing.to_string()),
("Allow incoming federated typing", &self.allow_incoming_typing.to_string()),
(
"Incoming federated typing timeout",
&self.typing_federation_timeout_s.to_string(),
),
("Client typing timeout minimum", &self.typing_client_timeout_min_s.to_string()),
("Client typing timeout maxmimum", &self.typing_client_timeout_max_s.to_string()),
("Allow device name federation", &self.allow_device_name_federation.to_string()),
(
"Allow incoming profile lookup federation requests",
&self.allow_profile_lookup_federation_requests.to_string(),
),
("Notification push path", &self.notification_push_path),
("Allow room creation", &self.allow_room_creation.to_string()),
(
@@ -304,6 +584,10 @@ impl fmt::Display for Config {
"Allow public room directory without authentication",
&self.allow_public_room_directory_without_auth.to_string(),
),
(
"Lockdown public room directory (only allow admins to publish)",
&self.lockdown_public_room_directory.to_string(),
),
(
"JWT secret",
match self.jwt_secret {
@@ -353,17 +637,30 @@ impl fmt::Display for Config {
}
&lst.join(", ")
}),
#[cfg(feature = "compression-zstd")]
("zstd Response Body Compression", &self.zstd_compression.to_string()),
("Auto Join Rooms", {
let mut lst = vec![];
for room in &self.auto_join_rooms {
lst.push(room);
}
&lst.into_iter().join(", ")
}),
#[cfg(feature = "zstd_compression")]
("Zstd HTTP Compression", &self.zstd_compression.to_string()),
#[cfg(feature = "gzip_compression")]
("Gzip HTTP Compression", &self.gzip_compression.to_string()),
#[cfg(feature = "brotli_compression")]
("Brotli HTTP Compression", &self.brotli_compression.to_string()),
#[cfg(feature = "rocksdb")]
("RocksDB database log level", &self.rocksdb_log_level),
("RocksDB database LOG level", &self.rocksdb_log_level),
#[cfg(feature = "rocksdb")]
("RocksDB database log time-to-roll", &self.rocksdb_log_time_to_roll.to_string()),
("RocksDB database LOG to stderr", &self.rocksdb_log_stderr.to_string()),
#[cfg(feature = "rocksdb")]
("RocksDB database LOG time-to-roll", &self.rocksdb_log_time_to_roll.to_string()),
#[cfg(feature = "rocksdb")]
("RocksDB Max LOG Files", &self.rocksdb_max_log_files.to_string()),
#[cfg(feature = "rocksdb")]
(
"RocksDB database max log file size",
"RocksDB database max LOG file size",
&self.rocksdb_max_log_file_size.to_string(),
),
#[cfg(feature = "rocksdb")]
@@ -387,6 +684,11 @@ impl fmt::Display for Config {
"RocksDB Bottommost Level Compression",
&self.rocksdb_bottommost_compression.to_string(),
),
#[cfg(feature = "rocksdb")]
("RocksDB Recovery Mode", &self.rocksdb_recovery_mode.to_string()),
("RocksDB Repair Mode", &self.rocksdb_repair.to_string()),
("RocksDB Read-only Mode", &self.rocksdb_read_only.to_string()),
("RocksDB Periodic Cleanup", &self.rocksdb_periodic_cleanup.to_string()),
("Prevent Media Downloads From", {
let mut lst = vec![];
for domain in &self.prevent_media_downloads_from {
@@ -394,6 +696,20 @@ impl fmt::Display for Config {
}
&lst.join(", ")
}),
("Forbidden Remote Server Names (\"Global\" ACLs)", {
let mut lst = vec![];
for domain in &self.forbidden_remote_server_names {
lst.push(domain.host());
}
&lst.join(", ")
}),
("Forbidden Remote Room Directory Server Names", {
let mut lst = vec![];
for domain in &self.forbidden_remote_room_directory_server_names {
lst.push(domain.host());
}
&lst.join(", ")
}),
("Outbound Request IP Range Denylist", {
let mut lst = vec![];
for item in self.ip_range_denylist.iter().cloned().enumerate() {
@@ -405,8 +721,8 @@ impl fmt::Display for Config {
("Forbidden usernames", {
&self.forbidden_usernames.patterns().iter().join(", ")
}),
("Forbidden room names", {
&self.forbidden_room_names.patterns().iter().join(", ")
("Forbidden room aliases", {
&self.forbidden_alias_names.patterns().iter().join(", ")
}),
(
"URL preview domain contains allowlist",
@@ -416,12 +732,67 @@ impl fmt::Display for Config {
"URL preview domain explicit allowlist",
&self.url_preview_domain_explicit_allowlist.join(", "),
),
(
"URL preview domain explicit denylist",
&self.url_preview_domain_explicit_denylist.join(", "),
),
(
"URL preview URL contains allowlist",
&self.url_preview_url_contains_allowlist.join(", "),
),
("URL preview maximum spider size", &self.url_preview_max_spider_size.to_string()),
("URL preview check root domain", &self.url_preview_check_root_domain.to_string()),
(
"Allow check for updates / announcements check",
&self.allow_check_for_updates.to_string(),
),
("Enable netburst on startup", &self.startup_netburst.to_string()),
#[cfg(feature = "sentry_telemetry")]
("Sentry.io reporting and tracing", &self.sentry.to_string()),
#[cfg(feature = "sentry_telemetry")]
("Sentry.io send server_name in logs", &self.sentry_send_server_name.to_string()),
#[cfg(feature = "sentry_telemetry")]
("Sentry.io tracing sample rate", &self.sentry_traces_sample_rate.to_string()),
(
"Well-known server name",
&if let Some(server) = &self.well_known.server {
server.to_string()
} else {
String::new()
},
),
(
"Well-known support email",
&if let Some(support_email) = &self.well_known.support_email {
support_email.to_string()
} else {
String::new()
},
),
(
"Well-known support Matrix ID",
&if let Some(support_mxid) = &self.well_known.support_mxid {
support_mxid.to_string()
} else {
String::new()
},
),
(
"Well-known support role",
&if let Some(support_role) = &self.well_known.support_role {
support_role.to_string()
} else {
String::new()
},
),
(
"Well-known support page/URL",
&if let Some(support_page) = &self.well_known.support_page {
support_page.to_string()
} else {
String::new()
},
),
];
let mut msg: String = "Active config values:\n\n".to_owned();
@@ -440,35 +811,100 @@ fn default_address() -> IpAddr { Ipv4Addr::LOCALHOST.into() }
fn default_port() -> ListeningPort {
ListeningPort {
ports: Either::Left(8008),
ports: Left(8008),
}
}
fn default_unix_socket_perms() -> u32 { 660 }
fn default_database_backups_to_keep() -> i16 { 1 }
fn default_database_backend() -> String { "rocksdb".to_owned() }
fn default_db_cache_capacity_mb() -> f64 { 300.0 }
fn default_db_cache_capacity_mb() -> f64 { 256.0 }
fn default_pdu_cache_capacity() -> u32 { 150_000 }
fn default_conduit_cache_capacity_modifier() -> f64 { 1.0 }
fn default_pdu_cache_capacity() -> u32 { 150_000 }
fn default_auth_chain_cache_capacity() -> u32 { 100_000 }
fn default_shorteventid_cache_capacity() -> u32 { 500_000 }
fn default_eventidshort_cache_capacity() -> u32 { 100_000 }
fn default_shortstatekey_cache_capacity() -> u32 { 100_000 }
fn default_statekeyshort_cache_capacity() -> u32 { 100_000 }
fn default_server_visibility_cache_capacity() -> u32 { 100 }
fn default_user_visibility_cache_capacity() -> u32 { 100 }
fn default_stateinfo_cache_capacity() -> u32 { 100 }
fn default_roomid_spacehierarchy_cache_capacity() -> u32 { 100 }
fn default_cleanup_second_interval() -> u32 {
1800 // every 30 minutes
}
fn default_dns_cache_entries() -> u32 { 12288 }
fn default_dns_min_ttl() -> u64 { 60 * 180 }
fn default_dns_min_ttl_nxdomain() -> u64 { 60 * 60 * 24 }
fn default_dns_attempts() -> u16 { 10 }
fn default_dns_timeout() -> u64 { 10 }
fn default_max_request_size() -> u32 {
20 * 1024 * 1024 // Default to 20 MB
}
fn default_max_concurrent_requests() -> u16 { 500 }
fn default_request_conn_timeout() -> u64 { 10 }
fn default_request_timeout() -> u64 { 35 }
fn default_request_idle_per_host() -> u16 { 1 }
fn default_request_idle_timeout() -> u64 { 5 }
fn default_well_known_conn_timeout() -> u64 { 6 }
fn default_well_known_timeout() -> u64 { 10 }
fn default_federation_timeout() -> u64 { 300 }
fn default_federation_idle_per_host() -> u16 { 1 }
fn default_federation_idle_timeout() -> u64 { 25 }
fn default_sender_timeout() -> u64 { 180 }
fn default_sender_idle_timeout() -> u64 { 180 }
fn default_appservice_timeout() -> u64 { 120 }
fn default_appservice_idle_timeout() -> u64 { 300 }
fn default_pusher_idle_timeout() -> u64 { 15 }
fn default_max_fetch_prev_events() -> u16 { 100_u16 }
fn default_trusted_servers() -> Vec<OwnedServerName> { vec![OwnedServerName::try_from("matrix.org").unwrap()] }
fn default_log() -> String { "warn,state_res=warn".to_owned() }
fn default_log() -> String {
// do debug logging by default for debug builds
if cfg!(debug_assertions) {
"debug".to_owned()
} else {
"warn,ruma_state_res=warn".to_owned()
}
}
fn default_notification_push_path() -> String { "/_matrix/push/v1/notify".to_owned() }
@@ -478,6 +914,14 @@ fn default_presence_idle_timeout_s() -> u64 { 5 * 60 }
fn default_presence_offline_timeout_s() -> u64 { 30 * 60 }
fn default_typing_federation_timeout_s() -> u64 { 30 }
fn default_typing_client_timeout_min_s() -> u64 { 15 }
fn default_typing_client_timeout_max_s() -> u64 { 45 }
fn default_rocksdb_recovery_mode() -> u8 { 1 }
fn default_rocksdb_log_level() -> String { "error".to_owned() }
fn default_rocksdb_log_time_to_roll() -> usize { 0 }
@@ -489,18 +933,20 @@ fn default_rocksdb_max_log_file_size() -> usize {
4 * 1024 * 1024
}
fn default_rocksdb_parallelism_threads() -> usize { num_cpus::get_physical() / 2 }
fn default_rocksdb_parallelism_threads() -> usize { 0 }
fn default_rocksdb_compression_algo() -> String { "zstd".to_owned() }
/// Default RocksDB compression level is 32767, which is internally read by
/// RocksDB as the default magic number and translated to the library's default
/// compression level as they all differ. See their `kDefaultCompressionLevel`.
#[allow(clippy::doc_markdown)]
fn default_rocksdb_compression_level() -> i32 { 32767 }
/// Default RocksDB compression level is 32767, which is internally read by
/// RocksDB as the default magic number and translated to the library's default
/// compression level as they all differ. See their `kDefaultCompressionLevel`.
#[allow(clippy::doc_markdown)]
fn default_rocksdb_bottommost_compression_level() -> i32 { 32767 }
// I know, it's a great name
@@ -531,7 +977,11 @@ fn default_ip_range_denylist() -> Vec<String> {
}
fn default_url_preview_max_spider_size() -> usize {
1_000_000 // 1MB
384_000 // 384KB
}
fn default_new_user_displayname_suffix() -> String { "🏳️‍⚧️".to_owned() }
fn default_sentry_traces_sample_rate() -> f32 { 0.15 }
fn default_startup_netburst_keep() -> i64 { 50 }
+1 -1
View File
@@ -131,7 +131,7 @@ impl std::str::FromStr for WildCardedDomain {
Ok(if s.starts_with("*.") {
WildCardedDomain::WildCarded(s[1..].to_owned())
} else if s == "*" {
WildCardedDomain::WildCarded("".to_owned())
WildCardedDomain::WildCarded(String::new())
} else {
WildCardedDomain::Exact(s.to_owned())
})
-68
View File
@@ -1,68 +0,0 @@
use std::{future::Future, pin::Pin, sync::Arc};
use super::Config;
use crate::Result;
#[cfg(feature = "sqlite")]
pub mod sqlite;
#[cfg(feature = "rocksdb")]
pub(crate) mod rocksdb;
#[cfg(any(feature = "sqlite", feature = "rocksdb"))]
pub(crate) mod watchers;
pub(crate) trait KeyValueDatabaseEngine: Send + Sync {
fn open(config: &Config) -> Result<Self>
where
Self: Sized;
fn open_tree(&self, name: &'static str) -> Result<Arc<dyn KvTree>>;
fn flush(&self) -> Result<()>;
fn cleanup(&self) -> Result<()> { Ok(()) }
fn memory_usage(&self) -> Result<String> {
Ok("Current database engine does not support memory usage reporting.".to_owned())
}
#[allow(dead_code)]
fn clear_caches(&self) {}
}
pub(crate) trait KvTree: Send + Sync {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
#[allow(dead_code)]
#[cfg(feature = "rocksdb")]
fn multi_get(
&self, _iter: Vec<(&Arc<rust_rocksdb::BoundColumnFamily<'_>>, Vec<u8>)>,
) -> Vec<std::result::Result<Option<Vec<u8>>, rust_rocksdb::Error>> {
unimplemented!()
}
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()>;
fn insert_batch(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()>;
fn remove(&self, key: &[u8]) -> Result<()>;
#[allow(dead_code)]
#[cfg(feature = "rocksdb")]
fn remove_batch(&self, _iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> { unimplemented!() }
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
fn iter_from<'a>(&'a self, from: &[u8], backwards: bool) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
fn increment(&self, key: &[u8]) -> Result<Vec<u8>>;
fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()>;
fn scan_prefix<'a>(&'a self, prefix: Vec<u8>) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a>;
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
fn clear(&self) -> Result<()> {
for (key, _) in self.iter() {
self.remove(&key)?;
}
Ok(())
}
}
-361
View File
@@ -1,361 +0,0 @@
use std::{
future::Future,
pin::Pin,
sync::{Arc, RwLock},
};
use rust_rocksdb::{
LogLevel::{Debug, Error, Fatal, Info, Warn},
WriteBatchWithTransaction,
};
use tracing::{debug, info};
use super::{super::Config, watchers::Watchers, KeyValueDatabaseEngine, KvTree};
use crate::{utils, Result};
pub(crate) struct Engine {
rocks: rust_rocksdb::DBWithThreadMode<rust_rocksdb::MultiThreaded>,
cache: rust_rocksdb::Cache,
old_cfs: Vec<String>,
config: Config,
}
struct RocksDbEngineTree<'a> {
db: Arc<Engine>,
name: &'a str,
watchers: Watchers,
write_lock: RwLock<()>,
}
fn db_options(rocksdb_cache: &rust_rocksdb::Cache, config: &Config) -> rust_rocksdb::Options {
// block-based options: https://docs.rs/rocksdb/latest/rocksdb/struct.BlockBasedOptions.html#
let mut block_based_options = rust_rocksdb::BlockBasedOptions::default();
block_based_options.set_block_cache(rocksdb_cache);
// "Difference of spinning disk"
// https://zhangyuchi.gitbooks.io/rocksdbbook/content/RocksDB-Tuning-Guide.html
block_based_options.set_block_size(64 * 1024);
block_based_options.set_cache_index_and_filter_blocks(true);
block_based_options.set_bloom_filter(10.0, false);
block_based_options.set_pin_l0_filter_and_index_blocks_in_cache(true);
block_based_options.set_optimize_filters_for_memory(true);
// database options: https://docs.rs/rocksdb/latest/rocksdb/struct.Options.html#
let mut db_opts = rust_rocksdb::Options::default();
let rocksdb_log_level = match config.rocksdb_log_level.as_ref() {
"debug" => Debug,
"info" => Info,
"warn" => Warn,
"fatal" => Fatal,
_ => Error,
};
let rocksdb_compression_algo = match config.rocksdb_compression_algo.as_ref() {
"zstd" => rust_rocksdb::DBCompressionType::Zstd,
"zlib" => rust_rocksdb::DBCompressionType::Zlib,
"lz4" => rust_rocksdb::DBCompressionType::Lz4,
"bz2" => rust_rocksdb::DBCompressionType::Bz2,
_ => rust_rocksdb::DBCompressionType::Zstd,
};
let threads = if config.rocksdb_parallelism_threads == 0 {
num_cpus::get_physical() // max cores if user specified 0
} else {
config.rocksdb_parallelism_threads
};
db_opts.set_log_level(rocksdb_log_level);
db_opts.set_max_log_file_size(config.rocksdb_max_log_file_size);
db_opts.set_log_file_time_to_roll(config.rocksdb_log_time_to_roll);
db_opts.set_keep_log_file_num(config.rocksdb_max_log_files);
if config.rocksdb_optimize_for_spinning_disks {
db_opts.set_skip_stats_update_on_db_open(true); // speeds up opening DB on hard drives
db_opts.set_compaction_readahead_size(4 * 1024 * 1024); // "If youre running RocksDB on spinning disks, you should set this to at least
// 2MB. That way RocksDBs compaction is doing sequential instead of random
// reads."
db_opts.set_target_file_size_base(256 * 1024 * 1024);
} else {
db_opts.set_max_bytes_for_level_base(512 * 1024 * 1024);
db_opts.set_use_direct_reads(true);
db_opts.set_use_direct_io_for_flush_and_compaction(true);
}
if config.rocksdb_bottommost_compression {
db_opts.set_bottommost_compression_type(rocksdb_compression_algo);
db_opts.set_bottommost_zstd_max_train_bytes(0, true);
// -14 w_bits is only read by zlib.
db_opts.set_bottommost_compression_options(-14, config.rocksdb_bottommost_compression_level, 0, 0, true);
}
// -14 w_bits is only read by zlib.
db_opts.set_compression_options(-14, config.rocksdb_compression_level, 0, 0);
db_opts.set_block_based_table_factory(&block_based_options);
db_opts.create_if_missing(true);
db_opts.increase_parallelism(
threads.try_into().expect("Failed to convert \"rocksdb_parallelism_threads\" usize into i32"),
);
db_opts.set_compression_type(rocksdb_compression_algo);
// https://github.com/facebook/rocksdb/wiki/Setup-Options-and-Basic-Tuning
db_opts.set_level_compaction_dynamic_level_bytes(true);
db_opts.set_max_background_jobs(6);
db_opts.set_bytes_per_sync(1_048_576);
// https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes#ktoleratecorruptedtailrecords
//
// Unclean shutdowns of a Matrix homeserver are likely to be fine when
// recovered in this manner as it's likely any lost information will be
// restored via federation.
db_opts.set_wal_recovery_mode(rust_rocksdb::DBRecoveryMode::TolerateCorruptedTailRecords);
// TODO: remove me? https://gitlab.com/famedly/conduit/-/merge_requests/602/diffs#a3a261d6a9014330581b5bdecd586dab5ae00245_62_54
let prefix_extractor = rust_rocksdb::SliceTransform::create_fixed_prefix(1);
db_opts.set_prefix_extractor(prefix_extractor);
db_opts
}
impl KeyValueDatabaseEngine for Arc<Engine> {
fn open(config: &Config) -> Result<Self> {
let cache_capacity_bytes = (config.db_cache_capacity_mb * 1024.0 * 1024.0) as usize;
let rocksdb_cache = rust_rocksdb::Cache::new_lru_cache(cache_capacity_bytes);
let db_opts = db_options(&rocksdb_cache, config);
debug!("Listing column families in database");
let cfs =
rust_rocksdb::DBWithThreadMode::<rust_rocksdb::MultiThreaded>::list_cf(&db_opts, &config.database_path)
.unwrap_or_default();
debug!("Opening column family descriptors in database");
info!("RocksDB database compaction will take place now, a delay in startup is expected");
let db = rust_rocksdb::DBWithThreadMode::<rust_rocksdb::MultiThreaded>::open_cf_descriptors(
&db_opts,
&config.database_path,
cfs.iter().map(|name| rust_rocksdb::ColumnFamilyDescriptor::new(name, db_options(&rocksdb_cache, config))),
)?;
Ok(Arc::new(Engine {
rocks: db,
cache: rocksdb_cache,
old_cfs: cfs,
config: config.clone(),
}))
}
fn open_tree(&self, name: &'static str) -> Result<Arc<dyn KvTree>> {
if !self.old_cfs.contains(&name.to_owned()) {
// Create if it didn't exist
debug!("Creating new column family in database: {}", name);
let _ = self.rocks.create_cf(name, &db_options(&self.cache, &self.config));
}
Ok(Arc::new(RocksDbEngineTree {
name,
db: Arc::clone(self),
watchers: Watchers::default(),
write_lock: RwLock::new(()),
}))
}
fn flush(&self) -> Result<()> {
debug!("Running flush_wal (no sync)");
rust_rocksdb::DBCommon::flush_wal(&self.rocks, false)?;
Ok(())
}
fn memory_usage(&self) -> Result<String> {
let stats = rust_rocksdb::perf::get_memory_usage_stats(Some(&[&self.rocks]), Some(&[&self.cache]))?;
Ok(format!(
"Approximate memory usage of all the mem-tables: {:.3} MB\nApproximate memory usage of un-flushed \
mem-tables: {:.3} MB\nApproximate memory usage of all the table readers: {:.3} MB\nApproximate memory \
usage by cache: {:.3} MB\nApproximate memory usage by cache pinned: {:.3} MB\n",
stats.mem_table_total as f64 / 1024.0 / 1024.0,
stats.mem_table_unflushed as f64 / 1024.0 / 1024.0,
stats.mem_table_readers_total as f64 / 1024.0 / 1024.0,
stats.cache_total as f64 / 1024.0 / 1024.0,
self.cache.get_pinned_usage() as f64 / 1024.0 / 1024.0,
))
}
fn cleanup(&self) -> Result<()> {
debug!("Running flush_opt");
let flushoptions = rust_rocksdb::FlushOptions::default();
rust_rocksdb::DBCommon::flush_opt(&self.rocks, &flushoptions)?;
Ok(())
}
// TODO: figure out if this is needed for rocksdb
#[allow(dead_code)]
fn clear_caches(&self) {}
}
impl RocksDbEngineTree<'_> {
fn cf(&self) -> Arc<rust_rocksdb::BoundColumnFamily<'_>> { self.db.rocks.cf_handle(self.name).unwrap() }
}
impl KvTree for RocksDbEngineTree<'_> {
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
Ok(self.db.rocks.get_cf_opt(&self.cf(), key, &readoptions)?)
}
fn multi_get(
&self, iter: Vec<(&Arc<rust_rocksdb::BoundColumnFamily<'_>>, Vec<u8>)>,
) -> Vec<std::result::Result<Option<Vec<u8>>, rust_rocksdb::Error>> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
self.db.rocks.multi_get_cf_opt(iter, &readoptions)
}
fn insert(&self, key: &[u8], value: &[u8]) -> Result<()> {
let writeoptions = rust_rocksdb::WriteOptions::default();
let lock = self.write_lock.read().unwrap();
self.db.rocks.put_cf_opt(&self.cf(), key, value, &writeoptions)?;
drop(lock);
self.watchers.wake(key);
Ok(())
}
fn insert_batch(&self, iter: &mut dyn Iterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<()> {
let writeoptions = rust_rocksdb::WriteOptions::default();
let mut batch = WriteBatchWithTransaction::<false>::default();
for (key, value) in iter {
batch.put_cf(&self.cf(), key, value);
}
Ok(self.db.rocks.write_opt(batch, &writeoptions)?)
}
fn remove(&self, key: &[u8]) -> Result<()> {
let writeoptions = rust_rocksdb::WriteOptions::default();
Ok(self.db.rocks.delete_cf_opt(&self.cf(), key, &writeoptions)?)
}
fn remove_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> {
let writeoptions = rust_rocksdb::WriteOptions::default();
let mut batch = WriteBatchWithTransaction::<false>::default();
for key in iter {
batch.delete_cf(&self.cf(), key);
}
Ok(self.db.rocks.write_opt(batch, &writeoptions)?)
}
fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
Box::new(
self.db
.rocks
.iterator_cf_opt(&self.cf(), readoptions, rust_rocksdb::IteratorMode::Start)
.map(std::result::Result::unwrap)
.map(|(k, v)| (Vec::from(k), Vec::from(v))),
)
}
fn iter_from<'a>(&'a self, from: &[u8], backwards: bool) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
Box::new(
self.db
.rocks
.iterator_cf_opt(
&self.cf(),
readoptions,
rust_rocksdb::IteratorMode::From(
from,
if backwards {
rust_rocksdb::Direction::Reverse
} else {
rust_rocksdb::Direction::Forward
},
),
)
.map(std::result::Result::unwrap)
.map(|(k, v)| (Vec::from(k), Vec::from(v))),
)
}
fn increment(&self, key: &[u8]) -> Result<Vec<u8>> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
let writeoptions = rust_rocksdb::WriteOptions::default();
let lock = self.write_lock.write().unwrap();
let old = self.db.rocks.get_cf_opt(&self.cf(), key, &readoptions)?;
let new = utils::increment(old.as_deref()).unwrap();
self.db.rocks.put_cf_opt(&self.cf(), key, &new, &writeoptions)?;
drop(lock);
Ok(new)
}
fn increment_batch(&self, iter: &mut dyn Iterator<Item = Vec<u8>>) -> Result<()> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
let writeoptions = rust_rocksdb::WriteOptions::default();
let mut batch = WriteBatchWithTransaction::<false>::default();
let lock = self.write_lock.write().unwrap();
for key in iter {
let old = self.db.rocks.get_cf_opt(&self.cf(), &key, &readoptions)?;
let new = utils::increment(old.as_deref()).unwrap();
batch.put_cf(&self.cf(), key, new);
}
self.db.rocks.write_opt(batch, &writeoptions)?;
drop(lock);
Ok(())
}
fn scan_prefix<'a>(&'a self, prefix: Vec<u8>) -> Box<dyn Iterator<Item = (Vec<u8>, Vec<u8>)> + 'a> {
let mut readoptions = rust_rocksdb::ReadOptions::default();
readoptions.set_total_order_seek(true);
Box::new(
self.db
.rocks
.iterator_cf_opt(
&self.cf(),
readoptions,
rust_rocksdb::IteratorMode::From(&prefix, rust_rocksdb::Direction::Forward),
)
.map(std::result::Result::unwrap)
.map(|(k, v)| (Vec::from(k), Vec::from(v)))
.take_while(move |(k, _)| k.starts_with(&prefix)),
)
}
fn watch_prefix<'a>(&'a self, prefix: &[u8]) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
self.watchers.watch(prefix)
}
}
+32
View File
@@ -0,0 +1,32 @@
use std::sync::Arc;
use super::KeyValueDatabaseEngine;
pub struct Cork {
db: Arc<dyn KeyValueDatabaseEngine>,
flush: bool,
sync: bool,
}
impl Cork {
pub(crate) fn new(db: &Arc<dyn KeyValueDatabaseEngine>, flush: bool, sync: bool) -> Self {
db.cork().unwrap();
Cork {
db: db.clone(),
flush,
sync,
}
}
}
impl Drop for Cork {
fn drop(&mut self) {
self.db.uncork().ok();
if self.flush {
self.db.flush().ok();
}
if self.sync {
self.db.sync().ok();
}
}
}
+22 -5
View File
@@ -18,7 +18,11 @@ impl service::account_data::Data for KeyValueDatabase {
&self, room_id: Option<&RoomId>, user_id: &UserId, event_type: RoomAccountDataEventType,
data: &serde_json::Value,
) -> Result<()> {
let mut prefix = room_id.map(ToString::to_string).unwrap_or_default().as_bytes().to_vec();
let mut prefix = room_id
.map(ToString::to_string)
.unwrap_or_default()
.as_bytes()
.to_vec();
prefix.push(0xFF);
prefix.extend_from_slice(user_id.as_bytes());
prefix.push(0xFF);
@@ -45,7 +49,8 @@ impl service::account_data::Data for KeyValueDatabase {
let prev = self.roomusertype_roomuserdataid.get(&key)?;
self.roomusertype_roomuserdataid.insert(&key, &roomuserdataid)?;
self.roomusertype_roomuserdataid
.insert(&key, &roomuserdataid)?;
// Remove old entry
if let Some(prev) = prev {
@@ -60,7 +65,11 @@ impl service::account_data::Data for KeyValueDatabase {
fn get(
&self, room_id: Option<&RoomId>, user_id: &UserId, kind: RoomAccountDataEventType,
) -> Result<Option<Box<serde_json::value::RawValue>>> {
let mut key = room_id.map(ToString::to_string).unwrap_or_default().as_bytes().to_vec();
let mut key = room_id
.map(ToString::to_string)
.unwrap_or_default()
.as_bytes()
.to_vec();
key.push(0xFF);
key.extend_from_slice(user_id.as_bytes());
key.push(0xFF);
@@ -68,7 +77,11 @@ impl service::account_data::Data for KeyValueDatabase {
self.roomusertype_roomuserdataid
.get(&key)?
.and_then(|roomuserdataid| self.roomuserdataid_accountdata.get(&roomuserdataid).transpose())
.and_then(|roomuserdataid| {
self.roomuserdataid_accountdata
.get(&roomuserdataid)
.transpose()
})
.transpose()?
.map(|data| serde_json::from_slice(&data).map_err(|_| Error::bad_database("could not deserialize")))
.transpose()
@@ -81,7 +94,11 @@ impl service::account_data::Data for KeyValueDatabase {
) -> Result<HashMap<RoomAccountDataEventType, Raw<AnyEphemeralRoomEvent>>> {
let mut userdata = HashMap::new();
let mut prefix = room_id.map(ToString::to_string).unwrap_or_default().as_bytes().to_vec();
let mut prefix = room_id
.map(ToString::to_string)
.unwrap_or_default()
.as_bytes()
.to_vec();
prefix.push(0xFF);
prefix.extend_from_slice(user_id.as_bytes());
prefix.push(0xFF);
+14 -19
View File
@@ -6,8 +6,8 @@ impl service::appservice::Data for KeyValueDatabase {
/// Registers an appservice and returns the ID to the caller
fn register_appservice(&self, yaml: Registration) -> Result<String> {
let id = yaml.id.as_str();
self.id_appserviceregistrations.insert(id.as_bytes(), serde_yaml::to_string(&yaml).unwrap().as_bytes())?;
self.cached_registrations.write().unwrap().insert(id.to_owned(), yaml.clone());
self.id_appserviceregistrations
.insert(id.as_bytes(), serde_yaml::to_string(&yaml).unwrap().as_bytes())?;
Ok(id.to_owned())
}
@@ -18,25 +18,19 @@ impl service::appservice::Data for KeyValueDatabase {
///
/// * `service_name` - the name you send to register the service previously
fn unregister_appservice(&self, service_name: &str) -> Result<()> {
self.id_appserviceregistrations.remove(service_name.as_bytes())?;
self.cached_registrations.write().unwrap().remove(service_name);
self.id_appserviceregistrations
.remove(service_name.as_bytes())?;
Ok(())
}
fn get_registration(&self, id: &str) -> Result<Option<Registration>> {
self.cached_registrations.read().unwrap().get(id).map_or_else(
|| {
self.id_appserviceregistrations
.get(id.as_bytes())?
.map(|bytes| {
serde_yaml::from_slice(&bytes).map_err(|_| {
Error::bad_database("Invalid registration bytes in id_appserviceregistrations.")
})
})
.transpose()
},
|r| Ok(Some(r.clone())),
)
self.id_appserviceregistrations
.get(id.as_bytes())?
.map(|bytes| {
serde_yaml::from_slice(&bytes)
.map_err(|_| Error::bad_database("Invalid registration bytes in id_appserviceregistrations."))
})
.transpose()
}
fn iter_ids<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<String>> + 'a>> {
@@ -48,11 +42,12 @@ impl service::appservice::Data for KeyValueDatabase {
fn all(&self) -> Result<Vec<(String, Registration)>> {
self.iter_ids()?
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.map(move |id| {
Ok((
id.clone(),
self.get_registration(&id)?.expect("iter_ids only returns appservices that exist"),
self.get_registration(&id)?
.expect("iter_ids only returns appservices that exist"),
))
})
.collect()
+80 -61
View File
@@ -8,9 +8,11 @@ use ruma::{
signatures::Ed25519KeyPair,
DeviceId, MilliSecondsSinceUnixEpoch, OwnedServerSigningKeyId, ServerName, UserId,
};
use tracing::debug;
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
use crate::{
database::{Cork, KeyValueDatabase},
service, services, utils, Error, Result,
};
const COUNTER: &[u8] = b"c";
const LAST_CHECK_FOR_UPDATES_COUNT: &[u8] = b"u";
@@ -29,14 +31,17 @@ impl service::globals::Data for KeyValueDatabase {
}
fn last_check_for_updates_id(&self) -> Result<u64> {
self.global.get(LAST_CHECK_FOR_UPDATES_COUNT)?.map_or(Ok(0_u64), |bytes| {
utils::u64_from_bytes(&bytes)
.map_err(|_| Error::bad_database("last check for updates count has invalid bytes."))
})
self.global
.get(LAST_CHECK_FOR_UPDATES_COUNT)?
.map_or(Ok(0_u64), |bytes| {
utils::u64_from_bytes(&bytes)
.map_err(|_| Error::bad_database("last check for updates count has invalid bytes."))
})
}
fn update_check_for_updates_id(&self, id: u64) -> Result<()> {
self.global.insert(LAST_CHECK_FOR_UPDATES_COUNT, &id.to_be_bytes())?;
self.global
.insert(LAST_CHECK_FOR_UPDATES_COUNT, &id.to_be_bytes())?;
Ok(())
}
@@ -60,11 +65,19 @@ impl service::globals::Data for KeyValueDatabase {
futures.push(self.userroomid_joined.watch_prefix(&userid_prefix));
futures.push(self.userroomid_invitestate.watch_prefix(&userid_prefix));
futures.push(self.userroomid_leftstate.watch_prefix(&userid_prefix));
futures.push(self.userroomid_notificationcount.watch_prefix(&userid_prefix));
futures.push(
self.userroomid_notificationcount
.watch_prefix(&userid_prefix),
);
futures.push(self.userroomid_highlightcount.watch_prefix(&userid_prefix));
// Events for rooms we are in
for room_id in services().rooms.state_cache.rooms_joined(user_id).filter_map(Result::ok) {
for room_id in services()
.rooms
.state_cache
.rooms_joined(user_id)
.filter_map(Result::ok)
{
let short_roomid = services()
.rooms
.short
@@ -83,7 +96,9 @@ impl service::globals::Data for KeyValueDatabase {
futures.push(self.pduid_pdu.watch_prefix(&short_roomid));
// EDUs
futures.push(self.roomid_lasttypingupdate.watch_prefix(&roomid_bytes));
futures.push(Box::pin(async move {
let _result = services().rooms.typing.wait_for_update(&room_id).await;
}));
futures.push(self.readreceiptid_readreceipt.watch_prefix(&roomid_prefix));
@@ -94,13 +109,19 @@ impl service::globals::Data for KeyValueDatabase {
let mut roomuser_prefix = roomid_prefix.clone();
roomuser_prefix.extend_from_slice(&userid_prefix);
futures.push(self.roomusertype_roomuserdataid.watch_prefix(&roomuser_prefix));
futures.push(
self.roomusertype_roomuserdataid
.watch_prefix(&roomuser_prefix),
);
}
let mut globaluserdata_prefix = vec![0xFF];
globaluserdata_prefix.extend_from_slice(&userid_prefix);
futures.push(self.roomusertype_roomuserdataid.watch_prefix(&globaluserdata_prefix));
futures.push(
self.roomusertype_roomuserdataid
.watch_prefix(&globaluserdata_prefix),
);
// More key changes (used when user is not joined to any rooms)
futures.push(self.keychangeid_userid.watch_prefix(&userid_prefix));
@@ -120,26 +141,29 @@ impl service::globals::Data for KeyValueDatabase {
fn flush(&self) -> Result<()> { self.db.flush() }
fn cork(&self) -> Result<Cork> { Ok(Cork::new(&self.db, false, false)) }
fn cork_and_flush(&self) -> Result<Cork> { Ok(Cork::new(&self.db, true, false)) }
fn cork_and_sync(&self) -> Result<Cork> { Ok(Cork::new(&self.db, true, true)) }
fn memory_usage(&self) -> String {
let pdu_cache = self.pdu_cache.lock().unwrap().len();
let shorteventid_cache = self.shorteventid_cache.lock().unwrap().len();
let auth_chain_cache = self.auth_chain_cache.lock().unwrap().len();
let eventidshort_cache = self.eventidshort_cache.lock().unwrap().len();
let statekeyshort_cache = self.statekeyshort_cache.lock().unwrap().len();
let our_real_users_cache = self.our_real_users_cache.read().unwrap().len();
let appservice_in_room_cache = self.appservice_in_room_cache.read().unwrap().len();
let lasttimelinecount_cache = self.lasttimelinecount_cache.lock().unwrap().len();
let max_auth_chain_cache = self.auth_chain_cache.lock().unwrap().capacity();
let max_our_real_users_cache = self.our_real_users_cache.read().unwrap().capacity();
let max_appservice_in_room_cache = self.appservice_in_room_cache.read().unwrap().capacity();
let max_lasttimelinecount_cache = self.lasttimelinecount_cache.lock().unwrap().capacity();
let mut response = format!(
"\
pdu_cache: {pdu_cache}
shorteventid_cache: {shorteventid_cache}
auth_chain_cache: {auth_chain_cache}
eventidshort_cache: {eventidshort_cache}
statekeyshort_cache: {statekeyshort_cache}
our_real_users_cache: {our_real_users_cache}
appservice_in_room_cache: {appservice_in_room_cache}
lasttimelinecount_cache: {lasttimelinecount_cache}\n"
auth_chain_cache: {auth_chain_cache} / {max_auth_chain_cache}
our_real_users_cache: {our_real_users_cache} / {max_our_real_users_cache}
appservice_in_room_cache: {appservice_in_room_cache} / {max_appservice_in_room_cache}
lasttimelinecount_cache: {lasttimelinecount_cache} / {max_lasttimelinecount_cache}\n\n"
);
if let Ok(db_stats) = self.db.memory_usage() {
response += &db_stats;
@@ -149,35 +173,19 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
}
fn clear_caches(&self, amount: u32) {
if amount > 0 {
let c = &mut *self.pdu_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 1 {
let c = &mut *self.shorteventid_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 2 {
let c = &mut *self.auth_chain_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 3 {
let c = &mut *self.eventidshort_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 4 {
let c = &mut *self.statekeyshort_cache.lock().unwrap();
*c = LruCache::new(c.capacity());
}
if amount > 5 {
if amount > 2 {
let c = &mut *self.our_real_users_cache.write().unwrap();
*c = HashMap::new();
}
if amount > 6 {
if amount > 3 {
let c = &mut *self.appservice_in_room_cache.write().unwrap();
*c = HashMap::new();
}
if amount > 7 {
if amount > 4 {
let c = &mut *self.lasttimelinecount_cache.lock().unwrap();
*c = HashMap::new();
}
@@ -186,9 +194,7 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
fn load_keypair(&self) -> Result<Ed25519KeyPair> {
let keypair_bytes = self.global.get(b"keypair")?.map_or_else(
|| {
debug!("No keypair found in database, assuming this is a new deployment and generating one.");
let keypair = utils::generate_keypair();
debug!("Generated keypair bytes: {:?}", keypair);
self.global.insert(b"keypair", &keypair)?;
Ok::<_, Error>(keypair)
},
@@ -199,11 +205,12 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
utils::string_from_bytes(
// 1. version
parts.next().expect("splitn always returns at least one element"),
parts
.next()
.expect("splitn always returns at least one element"),
)
.map_err(|_| Error::bad_database("Invalid version bytes in keypair."))
.and_then(|version| {
debug!("Keypair version: {version}");
// 2. key
parts
.next()
@@ -211,11 +218,8 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
.map(|key| (version, key))
})
.and_then(|(version, key)| {
debug!("Keypair bytes: {:?}", key);
let keypair = Ed25519KeyPair::from_der(key, version)
.map_err(|_| Error::bad_database("Private or public keys are invalid."));
debug!("Private and public key: {keypair:?}");
keypair
Ed25519KeyPair::from_der(key, version)
.map_err(|_| Error::bad_database("Private or public keys are invalid."))
})
}
@@ -227,10 +231,12 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
// Not atomic, but this is not critical
let signingkeys = self.server_signingkeys.get(origin.as_bytes())?;
let mut keys = signingkeys.and_then(|keys| serde_json::from_slice(&keys).ok()).unwrap_or_else(|| {
// Just insert "now", it doesn't matter
ServerSigningKeys::new(origin.to_owned(), MilliSecondsSinceUnixEpoch::now())
});
let mut keys = signingkeys
.and_then(|keys| serde_json::from_slice(&keys).ok())
.unwrap_or_else(|| {
// Just insert "now", it doesn't matter
ServerSigningKeys::new(origin.to_owned(), MilliSecondsSinceUnixEpoch::now())
});
let ServerSigningKeys {
verify_keys,
@@ -247,7 +253,11 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
)?;
let mut tree = keys.verify_keys;
tree.extend(keys.old_verify_keys.into_iter().map(|old| (old.0, VerifyKey::new(old.1.key))));
tree.extend(
keys.old_verify_keys
.into_iter()
.map(|old| (old.0, VerifyKey::new(old.1.key))),
);
Ok(tree)
}
@@ -259,12 +269,15 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
.server_signingkeys
.get(origin.as_bytes())?
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.map(|keys: ServerSigningKeys| {
.map_or_else(BTreeMap::new, |keys: ServerSigningKeys| {
let mut tree = keys.verify_keys;
tree.extend(keys.old_verify_keys.into_iter().map(|old| (old.0, VerifyKey::new(old.1.key))));
tree.extend(
keys.old_verify_keys
.into_iter()
.map(|old| (old.0, VerifyKey::new(old.1.key))),
);
tree
})
.unwrap_or_else(BTreeMap::new);
});
Ok(signingkeys)
}
@@ -279,4 +292,10 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
self.global.insert(b"version", &new_version.to_be_bytes())?;
Ok(())
}
fn backup(&self) -> Result<(), Box<dyn std::error::Error>> { self.db.backup() }
fn backup_list(&self) -> Result<String> { self.db.backup_list() }
fn file_list(&self) -> Result<String> { self.db.file_list() }
}
+57 -32
View File
@@ -23,7 +23,8 @@ impl service::key_backups::Data for KeyValueDatabase {
&key,
&serde_json::to_vec(backup_metadata).expect("BackupAlgorithm::to_vec always works"),
)?;
self.backupid_etag.insert(&key, &services().globals.next_count()?.to_be_bytes())?;
self.backupid_etag
.insert(&key, &services().globals.next_count()?.to_be_bytes())?;
Ok(version)
}
@@ -53,8 +54,10 @@ impl service::key_backups::Data for KeyValueDatabase {
return Err(Error::BadRequest(ErrorKind::NotFound, "Tried to update nonexistent backup."));
}
self.backupid_algorithm.insert(&key, backup_metadata.json().get().as_bytes())?;
self.backupid_etag.insert(&key, &services().globals.next_count()?.to_be_bytes())?;
self.backupid_algorithm
.insert(&key, backup_metadata.json().get().as_bytes())?;
self.backupid_etag
.insert(&key, &services().globals.next_count()?.to_be_bytes())?;
Ok(version.to_owned())
}
@@ -69,8 +72,12 @@ impl service::key_backups::Data for KeyValueDatabase {
.take_while(move |(k, _)| k.starts_with(&prefix))
.next()
.map(|(key, _)| {
utils::string_from_bytes(key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element"))
.map_err(|_| Error::bad_database("backupid_algorithm key is invalid."))
utils::string_from_bytes(
key.rsplit(|&b| b == 0xFF)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| Error::bad_database("backupid_algorithm key is invalid."))
})
.transpose()
}
@@ -87,7 +94,9 @@ impl service::key_backups::Data for KeyValueDatabase {
.next()
.map(|(key, value)| {
let version = utils::string_from_bytes(
key.rsplit(|&b| b == 0xFF).next().expect("rsplit always returns an element"),
key.rsplit(|&b| b == 0xFF)
.next()
.expect("rsplit always returns an element"),
)
.map_err(|_| Error::bad_database("backupid_algorithm key is invalid."))?;
@@ -105,10 +114,12 @@ impl service::key_backups::Data for KeyValueDatabase {
key.push(0xFF);
key.extend_from_slice(version.as_bytes());
self.backupid_algorithm.get(&key)?.map_or(Ok(None), |bytes| {
serde_json::from_slice(&bytes)
.map_err(|_| Error::bad_database("Algorithm in backupid_algorithm is invalid."))
})
self.backupid_algorithm
.get(&key)?
.map_or(Ok(None), |bytes| {
serde_json::from_slice(&bytes)
.map_err(|_| Error::bad_database("Algorithm in backupid_algorithm is invalid."))
})
}
fn add_key(
@@ -122,14 +133,16 @@ impl service::key_backups::Data for KeyValueDatabase {
return Err(Error::BadRequest(ErrorKind::NotFound, "Tried to update nonexistent backup."));
}
self.backupid_etag.insert(&key, &services().globals.next_count()?.to_be_bytes())?;
self.backupid_etag
.insert(&key, &services().globals.next_count()?.to_be_bytes())?;
key.push(0xFF);
key.extend_from_slice(room_id.as_bytes());
key.push(0xFF);
key.extend_from_slice(session_id.as_bytes());
self.backupkeyid_backup.insert(&key, key_data.json().get().as_bytes())?;
self.backupkeyid_backup
.insert(&key, key_data.json().get().as_bytes())?;
Ok(())
}
@@ -148,7 +161,10 @@ impl service::key_backups::Data for KeyValueDatabase {
key.extend_from_slice(version.as_bytes());
Ok(utils::u64_from_bytes(
&self.backupid_etag.get(&key)?.ok_or_else(|| Error::bad_database("Backup has no etag."))?,
&self
.backupid_etag
.get(&key)?
.ok_or_else(|| Error::bad_database("Backup has no etag."))?,
)
.map_err(|_| Error::bad_database("etag in backupid_etag invalid."))?
.to_string())
@@ -162,27 +178,34 @@ impl service::key_backups::Data for KeyValueDatabase {
let mut rooms = BTreeMap::<OwnedRoomId, RoomKeyBackup>::new();
for result in self.backupkeyid_backup.scan_prefix(prefix).map(|(key, value)| {
let mut parts = key.rsplit(|&b| b == 0xFF);
for result in self
.backupkeyid_backup
.scan_prefix(prefix)
.map(|(key, value)| {
let mut parts = key.rsplit(|&b| b == 0xFF);
let session_id = utils::string_from_bytes(
parts.next().ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?,
)
.map_err(|_| Error::bad_database("backupkeyid_backup session_id is invalid."))?;
let room_id = RoomId::parse(
utils::string_from_bytes(
parts.next().ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?,
let session_id = utils::string_from_bytes(
parts
.next()
.ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?,
)
.map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid."))?,
)
.map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid room id."))?;
.map_err(|_| Error::bad_database("backupkeyid_backup session_id is invalid."))?;
let key_data = serde_json::from_slice(&value)
.map_err(|_| Error::bad_database("KeyBackupData in backupkeyid_backup is invalid."))?;
let room_id = RoomId::parse(
utils::string_from_bytes(
parts
.next()
.ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?,
)
.map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid."))?,
)
.map_err(|_| Error::bad_database("backupkeyid_backup room_id is invalid room id."))?;
Ok::<_, Error>((room_id, session_id, key_data))
}) {
let key_data = serde_json::from_slice(&value)
.map_err(|_| Error::bad_database("KeyBackupData in backupkeyid_backup is invalid."))?;
Ok::<_, Error>((room_id, session_id, key_data))
}) {
let (room_id, session_id, key_data) = result?;
rooms
.entry(room_id)
@@ -213,7 +236,9 @@ impl service::key_backups::Data for KeyValueDatabase {
let mut parts = key.rsplit(|&b| b == 0xFF);
let session_id = utils::string_from_bytes(
parts.next().ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?,
parts
.next()
.ok_or_else(|| Error::bad_database("backupkeyid_backup key is invalid."))?,
)
.map_err(|_| Error::bad_database("backupkeyid_backup session_id is invalid."))?;
@@ -222,7 +247,7 @@ impl service::key_backups::Data for KeyValueDatabase {
Ok::<_, Error>((session_id, key_data))
})
.filter_map(std::result::Result::ok)
.filter_map(Result::ok)
.collect())
}
+57 -13
View File
@@ -18,9 +18,19 @@ impl service::media::Data for KeyValueDatabase {
key.extend_from_slice(&width.to_be_bytes());
key.extend_from_slice(&height.to_be_bytes());
key.push(0xFF);
key.extend_from_slice(content_disposition.as_ref().map(|f| f.as_bytes()).unwrap_or_default());
key.extend_from_slice(
content_disposition
.as_ref()
.map(|f| f.as_bytes())
.unwrap_or_default(),
);
key.push(0xFF);
key.extend_from_slice(content_type.as_ref().map(|c| c.as_bytes()).unwrap_or_default());
key.extend_from_slice(
content_type
.as_ref()
.map(|c| c.as_bytes())
.unwrap_or_default(),
);
self.mediaid_file.insert(&key, &[])?;
@@ -107,8 +117,9 @@ impl service::media::Data for KeyValueDatabase {
})
.transpose()?;
let content_disposition_bytes =
parts.next().ok_or_else(|| Error::bad_database("Media ID in db is invalid."))?;
let content_disposition_bytes = parts
.next()
.ok_or_else(|| Error::bad_database("Media ID in db is invalid."))?;
let content_disposition = if content_disposition_bytes.is_empty() {
None
@@ -139,11 +150,26 @@ impl service::media::Data for KeyValueDatabase {
let mut value = Vec::<u8>::new();
value.extend_from_slice(&timestamp.as_secs().to_be_bytes());
value.push(0xFF);
value.extend_from_slice(data.title.as_ref().map(String::as_bytes).unwrap_or_default());
value.extend_from_slice(
data.title
.as_ref()
.map(String::as_bytes)
.unwrap_or_default(),
);
value.push(0xFF);
value.extend_from_slice(data.description.as_ref().map(String::as_bytes).unwrap_or_default());
value.extend_from_slice(
data.description
.as_ref()
.map(String::as_bytes)
.unwrap_or_default(),
);
value.push(0xFF);
value.extend_from_slice(data.image.as_ref().map(String::as_bytes).unwrap_or_default());
value.extend_from_slice(
data.image
.as_ref()
.map(String::as_bytes)
.unwrap_or_default(),
);
value.push(0xFF);
value.extend_from_slice(&data.image_size.unwrap_or(0).to_be_bytes());
value.push(0xFF);
@@ -166,27 +192,45 @@ impl service::media::Data for KeyValueDatabase {
x => x,
};*/
let title = match values.next().and_then(|b| String::from_utf8(b.to_vec()).ok()) {
let title = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
{
Some(s) if s.is_empty() => None,
x => x,
};
let description = match values.next().and_then(|b| String::from_utf8(b.to_vec()).ok()) {
let description = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
{
Some(s) if s.is_empty() => None,
x => x,
};
let image = match values.next().and_then(|b| String::from_utf8(b.to_vec()).ok()) {
let image = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
{
Some(s) if s.is_empty() => None,
x => x,
};
let image_size = match values.next().map(|b| usize::from_be_bytes(b.try_into().unwrap_or_default())) {
let image_size = match values
.next()
.map(|b| usize::from_be_bytes(b.try_into().unwrap_or_default()))
{
Some(0) => None,
x => x,
};
let image_width = match values.next().map(|b| u32::from_be_bytes(b.try_into().unwrap_or_default())) {
let image_width = match values
.next()
.map(|b| u32::from_be_bytes(b.try_into().unwrap_or_default()))
{
Some(0) => None,
x => x,
};
let image_height = match values.next().map(|b| u32::from_be_bytes(b.try_into().unwrap_or_default())) {
let image_height = match values
.next()
.map(|b| u32::from_be_bytes(b.try_into().unwrap_or_default()))
{
Some(0) => None,
x => x,
};
+1
View File
@@ -5,6 +5,7 @@ mod globals;
mod key_backups;
mod media;
//mod pdu;
mod presence;
mod pusher;
mod rooms;
mod sending;
+120
View File
@@ -0,0 +1,120 @@
use ruma::{events::presence::PresenceEvent, presence::PresenceState, OwnedUserId, UInt, UserId};
use tracing::debug;
use crate::{
database::KeyValueDatabase,
service::{self, presence::Presence},
services,
utils::{self, user_id_from_bytes},
Error, Result,
};
impl service::presence::Data for KeyValueDatabase {
fn get_presence(&self, user_id: &UserId) -> Result<Option<(u64, PresenceEvent)>> {
if let Some(count_bytes) = self.userid_presenceid.get(user_id.as_bytes())? {
let count = utils::u64_from_bytes(&count_bytes)
.map_err(|_e| Error::bad_database("No 'count' bytes in presence key"))?;
let key = presenceid_key(count, user_id);
self.presenceid_presence
.get(&key)?
.map(|presence_bytes| -> Result<(u64, PresenceEvent)> {
Ok((count, Presence::from_json_bytes(&presence_bytes)?.to_presence_event(user_id)?))
})
.transpose()
} else {
Ok(None)
}
}
fn set_presence(
&self, user_id: &UserId, presence_state: &PresenceState, currently_active: Option<bool>,
last_active_ago: Option<UInt>, status_msg: Option<String>,
) -> Result<()> {
let last_presence = self.get_presence(user_id)?;
let state_changed = match last_presence {
None => true,
Some(ref presence) => presence.1.content.presence != *presence_state,
};
let now = utils::millis_since_unix_epoch();
let last_last_active_ts = match last_presence {
None => 0,
Some((_, ref presence)) => now.saturating_sub(presence.content.last_active_ago.unwrap_or_default().into()),
};
let last_active_ts = match last_active_ago {
None => now,
Some(last_active_ago) => now.saturating_sub(last_active_ago.into()),
};
// tighten for state flicker?
if !state_changed && last_active_ts <= last_last_active_ts {
debug!(
"presence spam {:?} last_active_ts:{:?} <= {:?}",
user_id, last_active_ts, last_last_active_ts
);
return Ok(());
}
let presence = Presence::new(
presence_state.to_owned(),
currently_active.unwrap_or(false),
last_active_ts,
status_msg,
);
let count = services().globals.next_count()?;
let key = presenceid_key(count, user_id);
self.presenceid_presence
.insert(&key, &presence.to_json_bytes()?)?;
self.userid_presenceid
.insert(user_id.as_bytes(), &count.to_be_bytes())?;
if let Some((last_count, _)) = last_presence {
let key = presenceid_key(last_count, user_id);
self.presenceid_presence.remove(&key)?;
}
Ok(())
}
fn remove_presence(&self, user_id: &UserId) -> Result<()> {
if let Some(count_bytes) = self.userid_presenceid.get(user_id.as_bytes())? {
let count = utils::u64_from_bytes(&count_bytes)
.map_err(|_e| Error::bad_database("No 'count' bytes in presence key"))?;
let key = presenceid_key(count, user_id);
self.presenceid_presence.remove(&key)?;
self.userid_presenceid.remove(user_id.as_bytes())?;
}
Ok(())
}
fn presence_since<'a>(&'a self, since: u64) -> Box<dyn Iterator<Item = (OwnedUserId, u64, Vec<u8>)> + 'a> {
Box::new(
self.presenceid_presence
.iter()
.flat_map(|(key, presence_bytes)| -> Result<(OwnedUserId, u64, Vec<u8>)> {
let (count, user_id) = presenceid_parse(&key)?;
Ok((user_id, count, presence_bytes))
})
.filter(move |(_, count, _)| *count > since),
)
}
}
#[inline]
fn presenceid_key(count: u64, user_id: &UserId) -> Vec<u8> {
[count.to_be_bytes().to_vec(), user_id.as_bytes().to_vec()].concat()
}
#[inline]
fn presenceid_parse(key: &[u8]) -> Result<(u64, OwnedUserId)> {
let (count, user_id) = key.split_at(8);
let user_id = user_id_from_bytes(user_id)?;
let count = utils::u64_from_bytes(count).unwrap();
Ok((count, user_id))
}
+4 -2
View File
@@ -20,7 +20,7 @@ impl service::pusher::Data for KeyValueDatabase {
let mut key = sender.as_bytes().to_vec();
key.push(0xFF);
key.extend_from_slice(ids.pushkey.as_bytes());
self.senderkey_pusher.remove(&key).map(|_| ()).map_err(Into::into)
self.senderkey_pusher.remove(&key).map_err(Into::into)
},
}
}
@@ -53,7 +53,9 @@ impl service::pusher::Data for KeyValueDatabase {
Box::new(self.senderkey_pusher.scan_prefix(prefix).map(|(k, _)| {
let mut parts = k.splitn(2, |&b| b == 0xFF);
let _senderkey = parts.next();
let push_key = parts.next().ok_or_else(|| Error::bad_database("Invalid senderkey_pusher in db"))?;
let push_key = parts
.next()
.ok_or_else(|| Error::bad_database("Invalid senderkey_pusher in db"))?;
let push_key_string = utils::string_from_bytes(push_key)
.map_err(|_| Error::bad_database("Invalid pusher bytes in senderkey_pusher"))?;
+15 -10
View File
@@ -4,7 +4,8 @@ use crate::{database::KeyValueDatabase, service, services, utils, Error, Result}
impl service::rooms::alias::Data for KeyValueDatabase {
fn set_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> Result<()> {
self.alias_roomid.insert(alias.alias().as_bytes(), room_id.as_bytes())?;
self.alias_roomid
.insert(alias.alias().as_bytes(), room_id.as_bytes())?;
let mut aliasid = room_id.as_bytes().to_vec();
aliasid.push(0xFF);
aliasid.extend_from_slice(&services().globals.next_count()?.to_be_bytes());
@@ -55,16 +56,20 @@ impl service::rooms::alias::Data for KeyValueDatabase {
}
fn all_local_aliases<'a>(&'a self) -> Box<dyn Iterator<Item = Result<(OwnedRoomId, String)>> + 'a> {
Box::new(self.alias_roomid.iter().map(|(room_alias_bytes, room_id_bytes)| {
let room_alias_localpart = utils::string_from_bytes(&room_alias_bytes)
.map_err(|_| Error::bad_database("Invalid alias bytes in aliasid_alias."))?;
Box::new(
self.alias_roomid
.iter()
.map(|(room_alias_bytes, room_id_bytes)| {
let room_alias_localpart = utils::string_from_bytes(&room_alias_bytes)
.map_err(|_| Error::bad_database("Invalid alias bytes in aliasid_alias."))?;
let room_id = utils::string_from_bytes(&room_id_bytes)
.map_err(|_| Error::bad_database("Invalid room_id bytes in aliasid_alias."))?
.try_into()
.map_err(|_| Error::bad_database("Invalid room_id in aliasid_alias."))?;
let room_id = utils::string_from_bytes(&room_id_bytes)
.map_err(|_| Error::bad_database("Invalid room_id bytes in aliasid_alias."))?
.try_into()
.map_err(|_| Error::bad_database("Invalid room_id in aliasid_alias."))?;
Ok((room_id, room_alias_localpart))
}))
Ok((room_id, room_alias_localpart))
}),
)
}
}
+24 -14
View File
@@ -1,9 +1,9 @@
use std::{collections::HashSet, mem::size_of, sync::Arc};
use std::{mem::size_of, sync::Arc};
use crate::{database::KeyValueDatabase, service, utils, Result};
impl service::rooms::auth_chain::Data for KeyValueDatabase {
fn get_cached_eventid_authchain(&self, key: &[u64]) -> Result<Option<Arc<HashSet<u64>>>> {
fn get_cached_eventid_authchain(&self, key: &[u64]) -> Result<Option<Arc<[u64]>>> {
// Check RAM cache
if let Some(result) = self.auth_chain_cache.lock().unwrap().get_mut(key) {
return Ok(Some(Arc::clone(result)));
@@ -12,18 +12,22 @@ impl service::rooms::auth_chain::Data for KeyValueDatabase {
// We only save auth chains for single events in the db
if key.len() == 1 {
// Check DB cache
let chain = self.shorteventid_authchain.get(&key[0].to_be_bytes())?.map(|chain| {
chain
.chunks_exact(size_of::<u64>())
.map(|chunk| utils::u64_from_bytes(chunk).expect("byte length is correct"))
.collect()
});
let chain = self
.shorteventid_authchain
.get(&key[0].to_be_bytes())?
.map(|chain| {
chain
.chunks_exact(size_of::<u64>())
.map(|chunk| utils::u64_from_bytes(chunk).expect("byte length is correct"))
.collect::<Arc<[u64]>>()
});
if let Some(chain) = chain {
let chain = Arc::new(chain);
// Cache in RAM
self.auth_chain_cache.lock().unwrap().insert(vec![key[0]], Arc::clone(&chain));
self.auth_chain_cache
.lock()
.unwrap()
.insert(vec![key[0]], Arc::clone(&chain));
return Ok(Some(chain));
}
@@ -32,17 +36,23 @@ impl service::rooms::auth_chain::Data for KeyValueDatabase {
Ok(None)
}
fn cache_auth_chain(&self, key: Vec<u64>, auth_chain: Arc<HashSet<u64>>) -> Result<()> {
fn cache_auth_chain(&self, key: Vec<u64>, auth_chain: Arc<[u64]>) -> Result<()> {
// Only persist single events in db
if key.len() == 1 {
self.shorteventid_authchain.insert(
&key[0].to_be_bytes(),
&auth_chain.iter().flat_map(|s| s.to_be_bytes().to_vec()).collect::<Vec<u8>>(),
&auth_chain
.iter()
.flat_map(|s| s.to_be_bytes().to_vec())
.collect::<Vec<u8>>(),
)?;
}
// Cache in RAM
self.auth_chain_cache.lock().unwrap().insert(key, auth_chain);
self.auth_chain_cache
.lock()
.unwrap()
.insert(key, auth_chain);
Ok(())
}
-7
View File
@@ -1,7 +0,0 @@
mod presence;
mod read_receipt;
mod typing;
use crate::{database::KeyValueDatabase, service};
impl service::rooms::edus::Data for KeyValueDatabase {}
@@ -1,155 +0,0 @@
use std::time::Duration;
use ruma::{events::presence::PresenceEvent, presence::PresenceState, OwnedUserId, RoomId, UInt, UserId};
use tracing::error;
use crate::{
database::KeyValueDatabase,
service::{self, rooms::edus::presence::Presence},
services,
utils::{self, user_id_from_bytes},
Error, Result,
};
impl service::rooms::edus::presence::Data for KeyValueDatabase {
fn get_presence(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<PresenceEvent>> {
let key = presence_key(room_id, user_id);
self.roomuserid_presence
.get(&key)?
.map(|presence_bytes| -> Result<PresenceEvent> {
Presence::from_json_bytes(&presence_bytes)?.to_presence_event(user_id)
})
.transpose()
}
fn ping_presence(&self, user_id: &UserId, new_state: PresenceState) -> Result<()> {
let now = utils::millis_since_unix_epoch();
let mut state_changed = false;
for room_id in services().rooms.state_cache.rooms_joined(user_id) {
let key = presence_key(&room_id?, user_id);
let presence_bytes = self.roomuserid_presence.get(&key)?;
if let Some(presence_bytes) = presence_bytes {
let presence = Presence::from_json_bytes(&presence_bytes)?;
if presence.state != new_state {
state_changed = true;
break;
}
}
}
let count = if state_changed {
services().globals.next_count()?
} else {
services().globals.current_count()?
};
for room_id in services().rooms.state_cache.rooms_joined(user_id) {
let key = presence_key(&room_id?, user_id);
let presence_bytes = self.roomuserid_presence.get(&key)?;
let new_presence = match presence_bytes {
Some(presence_bytes) => {
let mut presence = Presence::from_json_bytes(&presence_bytes)?;
presence.state = new_state.clone();
presence.currently_active = presence.state == PresenceState::Online;
presence.last_active_ts = now;
presence.last_count = count;
presence
},
None => Presence::new(new_state.clone(), new_state == PresenceState::Online, now, count, None),
};
self.roomuserid_presence.insert(&key, &new_presence.to_json_bytes()?)?;
}
let timeout = match new_state {
PresenceState::Online => services().globals.config.presence_idle_timeout_s,
_ => services().globals.config.presence_offline_timeout_s,
};
self.presence_timer_sender.send((user_id.to_owned(), Duration::from_secs(timeout))).map_err(|e| {
error!("Failed to add presence timer: {}", e);
Error::bad_database("Failed to add presence timer")
})
}
fn set_presence(
&self, room_id: &RoomId, user_id: &UserId, presence_state: PresenceState, currently_active: Option<bool>,
last_active_ago: Option<UInt>, status_msg: Option<String>,
) -> Result<()> {
let now = utils::millis_since_unix_epoch();
let last_active_ts = match last_active_ago {
Some(last_active_ago) => now.saturating_sub(last_active_ago.into()),
None => now,
};
let key = presence_key(room_id, user_id);
let presence = Presence::new(
presence_state,
currently_active.unwrap_or(false),
last_active_ts,
services().globals.next_count()?,
status_msg,
);
let timeout = match presence.state {
PresenceState::Online => services().globals.config.presence_idle_timeout_s,
_ => services().globals.config.presence_offline_timeout_s,
};
self.presence_timer_sender.send((user_id.to_owned(), Duration::from_secs(timeout))).map_err(|e| {
error!("Failed to add presence timer: {}", e);
Error::bad_database("Failed to add presence timer")
})?;
self.roomuserid_presence.insert(&key, &presence.to_json_bytes()?)?;
Ok(())
}
fn remove_presence(&self, user_id: &UserId) -> Result<()> {
for room_id in services().rooms.state_cache.rooms_joined(user_id) {
let key = presence_key(&room_id?, user_id);
self.roomuserid_presence.remove(&key)?;
}
Ok(())
}
fn presence_since<'a>(
&'a self, room_id: &RoomId, since: u64,
) -> Box<dyn Iterator<Item = (OwnedUserId, u64, PresenceEvent)> + 'a> {
let prefix = [room_id.as_bytes(), &[0xFF]].concat();
Box::new(
self.roomuserid_presence
.scan_prefix(prefix)
.flat_map(|(key, presence_bytes)| -> Result<(OwnedUserId, u64, PresenceEvent)> {
let user_id = user_id_from_bytes(
key.rsplit(|byte| *byte == 0xFF)
.next()
.ok_or_else(|| Error::bad_database("No UserID bytes in presence key"))?,
)?;
let presence = Presence::from_json_bytes(&presence_bytes)?;
let presence_event = presence.to_presence_event(&user_id)?;
Ok((user_id, presence.last_count, presence_event))
})
.filter(move |(_, count, _)| *count > since),
)
}
}
#[inline]
fn presence_key(room_id: &RoomId, user_id: &UserId) -> Vec<u8> {
[room_id.as_bytes(), &[0xFF], user_id.as_bytes()].concat()
}
-115
View File
@@ -1,115 +0,0 @@
use std::{collections::HashSet, mem};
use ruma::{OwnedUserId, RoomId, UserId};
use crate::{database::KeyValueDatabase, service, services, utils, Error, Result};
impl service::rooms::edus::typing::Data for KeyValueDatabase {
fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF);
let count = services().globals.next_count()?.to_be_bytes();
let mut room_typing_id = prefix;
room_typing_id.extend_from_slice(&timeout.to_be_bytes());
room_typing_id.push(0xFF);
room_typing_id.extend_from_slice(&count);
self.typingid_userid.insert(&room_typing_id, user_id.as_bytes())?;
self.roomid_lasttypingupdate.insert(room_id.as_bytes(), &count)?;
Ok(())
}
fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF);
let user_id = user_id.to_string();
let mut found_outdated = false;
// Maybe there are multiple ones from calling roomtyping_add multiple times
for outdated_edu in self.typingid_userid.scan_prefix(prefix).filter(|(_, v)| &**v == user_id.as_bytes()) {
self.typingid_userid.remove(&outdated_edu.0)?;
found_outdated = true;
}
if found_outdated {
self.roomid_lasttypingupdate.insert(room_id.as_bytes(), &services().globals.next_count()?.to_be_bytes())?;
}
Ok(())
}
fn typings_maintain(&self, room_id: &RoomId) -> Result<()> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF);
let current_timestamp = utils::millis_since_unix_epoch();
let mut found_outdated = false;
// Find all outdated edus before inserting a new one
for outdated_edu in self
.typingid_userid
.scan_prefix(prefix)
.map(|(key, _)| {
Ok::<_, Error>((
key.clone(),
utils::u64_from_bytes(
&key.splitn(2, |&b| b == 0xFF)
.nth(1)
.ok_or_else(|| Error::bad_database("RoomTyping has invalid timestamp or delimiters."))?[0..mem::size_of::<u64>()],
)
.map_err(|_| Error::bad_database("RoomTyping has invalid timestamp bytes."))?,
))
})
.filter_map(std::result::Result::ok)
.take_while(|&(_, timestamp)| timestamp < current_timestamp)
{
// This is an outdated edu (time > timestamp)
self.typingid_userid.remove(&outdated_edu.0)?;
found_outdated = true;
}
if found_outdated {
self.roomid_lasttypingupdate.insert(room_id.as_bytes(), &services().globals.next_count()?.to_be_bytes())?;
}
Ok(())
}
fn last_typing_update(&self, room_id: &RoomId) -> Result<u64> {
Ok(self
.roomid_lasttypingupdate
.get(room_id.as_bytes())?
.map(|bytes| {
utils::u64_from_bytes(&bytes)
.map_err(|_| Error::bad_database("Count in roomid_lastroomactiveupdate is invalid."))
})
.transpose()?
.unwrap_or(0))
}
fn typings_all(&self, room_id: &RoomId) -> Result<HashSet<OwnedUserId>> {
let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xFF);
let mut user_ids = HashSet::new();
for (_, user_id) in self.typingid_userid.scan_prefix(prefix) {
let user_id = UserId::parse(
utils::string_from_bytes(&user_id)
.map_err(|_| Error::bad_database("User ID in typingid_userid is invalid unicode."))?,
)
.map_err(|_| Error::bad_database("User ID in typingid_userid is invalid."))?;
user_ids.insert(user_id);
}
Ok(user_ids)
}
}
+6 -1
View File
@@ -11,7 +11,12 @@ impl service::rooms::metadata::Data for KeyValueDatabase {
};
// Look for PDUs in that room.
Ok(self.pduid_pdu.iter_from(&prefix, false).next().filter(|(k, _)| k.starts_with(&prefix)).is_some())
Ok(self
.pduid_pdu
.iter_from(&prefix, false)
.next()
.filter(|(k, _)| k.starts_with(&prefix))
.is_some())
}
fn iter_ids<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> {
+1 -1
View File
@@ -1,11 +1,11 @@
mod alias;
mod auth_chain;
mod directory;
mod edus;
mod lazy_load;
mod metadata;
mod outlier;
mod pdu_metadata;
mod read_receipt;
mod search;
mod short;
mod state;

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