Compare commits

...
Author SHA1 Message Date
timedout a2e294fa8d feat: Implement MSC4524 2026-10-04 23:28:38 +00:00
Jade Ellis 1e34bd2ed9 style: Run formatting 2026-10-05 00:27:12 +01:00
21 changed files with 391 additions and 114 deletions

No files matched your search

Generated
+1
View File
@@ -950,6 +950,7 @@ dependencies = [
"log",
"resolvematrix",
"ruma",
"ruminuwuity",
"serde-saphyr",
"serde_json",
"tokio",
+40 -39
View File
@@ -11,65 +11,65 @@ version.workspace = true
[lib]
path = "mod.rs"
crate-type = [
"rlib",
# "dylib",
"rlib",
# "dylib",
]
[features]
brotli_compression = [
"conduwuit-api/brotli_compression",
"conduwuit-core/brotli_compression",
"conduwuit-service/brotli_compression",
"conduwuit-api/brotli_compression",
"conduwuit-core/brotli_compression",
"conduwuit-service/brotli_compression",
]
gzip_compression = [
"conduwuit-api/gzip_compression",
"conduwuit-core/gzip_compression",
"conduwuit-service/gzip_compression",
"conduwuit-api/gzip_compression",
"conduwuit-core/gzip_compression",
"conduwuit-service/gzip_compression",
]
io_uring = [
"conduwuit-api/io_uring",
"conduwuit-database/io_uring",
"conduwuit-service/io_uring",
"conduwuit-api/io_uring",
"conduwuit-database/io_uring",
"conduwuit-service/io_uring",
]
jemalloc = [
"conduwuit-api/jemalloc",
"conduwuit-core/jemalloc",
"conduwuit-database/jemalloc",
"conduwuit-service/jemalloc",
"conduwuit-api/jemalloc",
"conduwuit-core/jemalloc",
"conduwuit-database/jemalloc",
"conduwuit-service/jemalloc",
]
jemalloc_conf = [
"conduwuit-api/jemalloc_conf",
"conduwuit-core/jemalloc_conf",
"conduwuit-database/jemalloc_conf",
"conduwuit-service/jemalloc_conf",
"conduwuit-api/jemalloc_conf",
"conduwuit-core/jemalloc_conf",
"conduwuit-database/jemalloc_conf",
"conduwuit-service/jemalloc_conf",
]
jemalloc_prof = [
"conduwuit-api/jemalloc_prof",
"conduwuit-core/jemalloc_prof",
"conduwuit-database/jemalloc_prof",
"conduwuit-service/jemalloc_prof",
"conduwuit-api/jemalloc_prof",
"conduwuit-core/jemalloc_prof",
"conduwuit-database/jemalloc_prof",
"conduwuit-service/jemalloc_prof",
]
jemalloc_stats = [
"conduwuit-api/jemalloc_stats",
"conduwuit-core/jemalloc_stats",
"conduwuit-database/jemalloc_stats",
"conduwuit-service/jemalloc_stats",
"conduwuit-api/jemalloc_stats",
"conduwuit-core/jemalloc_stats",
"conduwuit-database/jemalloc_stats",
"conduwuit-service/jemalloc_stats",
]
release_max_log_level = [
"conduwuit-api/release_max_log_level",
"conduwuit-core/release_max_log_level",
"conduwuit-database/release_max_log_level",
"conduwuit-service/release_max_log_level",
"tracing/max_level_trace",
"tracing/release_max_level_info",
"log/max_level_trace",
"log/release_max_level_info",
"conduwuit-api/release_max_log_level",
"conduwuit-core/release_max_log_level",
"conduwuit-database/release_max_log_level",
"conduwuit-service/release_max_log_level",
"tracing/max_level_trace",
"tracing/release_max_level_info",
"log/max_level_trace",
"log/release_max_level_info",
]
zstd_compression = [
"conduwuit-api/zstd_compression",
"conduwuit-core/zstd_compression",
"conduwuit-database/zstd_compression",
"conduwuit-service/zstd_compression",
"conduwuit-api/zstd_compression",
"conduwuit-core/zstd_compression",
"conduwuit-database/zstd_compression",
"conduwuit-service/zstd_compression",
]
[dependencies]
@@ -86,6 +86,7 @@ futures.workspace = true
lettre.workspace = true
log.workspace = true
ruma.workspace = true
ruminuwuity.workspace = true
serde_json.workspace = true
serde-saphyr.workspace = true
tokio.workspace = true
+51 -4
View File
@@ -6,7 +6,7 @@ use std::{
};
use conduwuit::{
Err, Result, at, debug_error, err, info,
Err, Result, at, debug_error, debug_info, err, info,
matrix::{
Event, StateKey,
pdu::{PduEvent, PduId, RawPduId},
@@ -14,6 +14,7 @@ use conduwuit::{
state_res::EventTypeExt,
trace, utils,
utils::{
random_string,
stream::{IterStream, ReadyExt},
string::EMPTY,
to_canonical_object,
@@ -28,8 +29,8 @@ use resolvematrix::{
};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId,
OwnedRoomOrAliasId, OwnedServerName, RoomId, RoomVersionId, UInt,
api::federation::event::get_room_state,
OwnedRoomOrAliasId, OwnedServerName, RoomId, RoomVersionId, ServerName, UInt,
api::{error::ErrorKind, federation::event::get_room_state},
events::{AnyStateEvent, StateEventType},
serde::Raw,
};
@@ -604,14 +605,60 @@ impl crate::Context<'_> {
if server == self.services.globals.server_name() {
return Err!("Not allowed to send federation requests to ourselves.");
}
let modern = self.modern_pingpong_ping(&server).await?;
if let Some(w) = modern {
self.write_str(&w).await
} else {
info!("{server} does not support msc4524, falling back to legacy ping");
self.legacy_ping(&server).await
}
}
async fn modern_pingpong_ping(&self, server: &ServerName) -> Result<Option<String>> {
let timer = tokio::time::Instant::now();
let question = &random_string(64);
let response = self
.services
.sending
.send_federation_request(
server,
ruminuwuity::api::federation::ping::unstable::Request::new(question.to_owned()),
)
.await;
let answer = match response {
| Ok(resp) => resp.answer,
| Err(e) =>
return if e.is_not_found() && e.kind() == ErrorKind::Unrecognized {
Ok(None)
} else {
Err!("Failed sending federation request to specified server:\n\n{e}")
},
};
let recv = self
.services
.federation
.register_ping_answer(answer.clone())?;
debug_info!("Waiting for a pong for up to 60 seconds");
let result = tokio::time::timeout(std::time::Duration::from_mins(1), recv).await;
match result {
| Err(e) => Err!(BadServerResponse("Remote did not answer the ping in time: {e:?}")),
| Ok(Err(e)) =>
Err!(BadServerResponse("Unexpectedly could not read from pong channel: {e:?}")),
| Ok(Ok(())) =>
Ok(Some(format!("Ping got a pong in {:?}: {answer}", timer.elapsed()))),
}
}
async fn legacy_ping(&self, server: &ServerName) -> Result {
let timer = tokio::time::Instant::now();
match self
.services
.sending
.send_unauthenticated_request(
&server,
server,
ruma::api::federation::discovery::get_server_version::v1::Request::new(),
)
.await
+10 -2
View File
@@ -267,11 +267,19 @@ pub(crate) async fn get_public_rooms_filtered_helper(
summary.into()
})
.ready_filter_map(|chunk: PublicRoomsChunk| {
if !filter.room_types.is_empty() && !filter.room_types.contains(&RoomTypeFilter::from(chunk.room_type.clone())) {
if !filter.room_types.is_empty()
&& !filter
.room_types
.contains(&RoomTypeFilter::from(chunk.room_type.clone()))
{
return None;
}
if let Some(query) = filter.generic_search_term.as_ref().map(|q| q.to_lowercase()) {
if let Some(query) = filter
.generic_search_term
.as_ref()
.map(|q| q.to_lowercase())
{
if let Some(name) = &chunk.name {
if name.to_lowercase().contains(&query) {
return Some(chunk);
+4 -1
View File
@@ -55,5 +55,8 @@ fn oauth_router() -> Router<crate::State> {
.route(concat!("/", JWKS_URI_PATH), get(async || Json(json!({"keys": []}))))
.route(concat!("/", TOKEN_PATH), post(token::token_route))
.route(concat!("/", TOKEN_REVOKE_PATH), post(token::revoke_token_route))
.route(concat!("/", DEVICE_AUTHORIZATION_PATH), post(device::device_authorization_route))
.route(
concat!("/", DEVICE_AUTHORIZATION_PATH),
post(device::device_authorization_route),
)
}
+17 -12
View File
@@ -1563,20 +1563,25 @@ where
// joined users
device_list_changes.extend(
services
.rooms
.state_cache
.room_members(room_id)
// Don't send key updates from the sender to the sender
.ready_filter(|user_id| sender_user != *user_id)
// Only send keys if the sender doesn't share an encrypted room with the target
// already
.filter_map(async |user_id| {
share_encrypted_room(services, sender_user, &user_id, Some(room_id))
.rooms
.state_cache
.room_members(room_id)
// Don't send key updates from the sender to the sender
.ready_filter(|user_id| sender_user != *user_id)
// Only send keys if the sender doesn't share an encrypted room with
// the target already
.filter_map(async |user_id| {
share_encrypted_room(
services,
sender_user,
&user_id,
Some(room_id),
)
.map(|res| res.or_some(user_id.clone()))
.await
})
.collect::<Vec<_>>()
.await,
})
.collect::<Vec<_>>()
.await,
);
}
}
+12 -7
View File
@@ -21,7 +21,7 @@ use crate::{admin, client, server};
pub fn build(router: Router<State>, state: State) -> Router<State> {
let config = &state.server.config;
let mut router = router
.ruma_route(&client::appservice_ping)
.ruma_route(&client::appservice_ping)
.ruma_route(&client::get_supported_versions_route)
.ruma_route(&client::get_register_available_route)
.ruma_route(&client::register::register_route)
@@ -61,8 +61,8 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::get_global_account_data_route)
.ruma_route(&client::get_room_account_data_route)
.ruma_route(&client::get_profile_field_route)
.ruma_route(&client::set_profile_field_route)
.ruma_route(&client::delete_profile_field_route)
.ruma_route(&client::set_profile_field_route)
.ruma_route(&client::delete_profile_field_route)
.ruma_route(&client::get_profile_route)
.ruma_route(&client::set_presence_route)
.ruma_route(&client::get_presence_route)
@@ -112,14 +112,17 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::search_users_route)
.ruma_route(&client::get_member_events_route)
.ruma_route(&client::get_protocols_route)
.route("/_matrix/client/unstable/thirdparty/protocols",
get(client::get_protocols_route_unstable))
.route(
"/_matrix/client/unstable/thirdparty/protocols",
get(client::get_protocols_route_unstable),
)
.ruma_route(&client::send_message_event_route)
.ruma_route(&client::send_state_event_for_key_route)
.ruma_route(&client::get_state_events_route)
.ruma_route(&client::get_state_event_for_key_route)
// Ruma doesn't have support for multiple paths for a single endpoint yet, and these routes
// share one Ruma request / response type pair with {get,send}_state_event_for_key_route
// Ruma doesn't have support for multiple paths for a single endpoint yet, and these
// routes share one Ruma request / response type pair with
// {get,send}_state_event_for_key_route
.route(
"/_matrix/client/r0/rooms/{room_id}/state/{event_type}",
get(client::get_state_events_for_empty_key_route)
@@ -226,6 +229,8 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&server::well_known_server)
.ruma_route(&server::get_content_route)
.ruma_route(&server::get_content_thumbnail_route)
.ruma_route(&server::ping)
.ruma_route(&server::pong)
.route("/_continuwuity/local_user_count", get(client::continuwuity_local_user_count));
} else {
router = router
+5 -1
View File
@@ -10,6 +10,8 @@ pub(super) mod make_knock;
pub(super) mod make_leave;
pub(super) mod media;
pub(super) mod openid;
pub(super) mod ping;
pub(super) mod pong;
pub(super) mod publicrooms;
pub(super) mod query;
pub(super) mod send;
@@ -34,6 +36,8 @@ pub(super) use make_knock::*;
pub(super) use make_leave::*;
pub(super) use media::*;
pub(super) use openid::*;
pub(super) use ping::ping;
pub(super) use pong::pong;
pub(super) use publicrooms::*;
pub(super) use query::*;
pub(super) use send::*;
@@ -45,6 +49,6 @@ pub(super) use state_ids::*;
pub(super) use user::*;
pub(super) use version::*;
pub(super) use well_known::*;
mod utils;
use utils::AccessCheck;
+55
View File
@@ -0,0 +1,55 @@
use std::{sync::Arc, time::Duration};
use axum::extract::State;
use conduwuit::{
Result, info,
utils::{random_string, time::jitter},
warn,
};
use ruma::{OwnedServerName, api::error::ErrorKind};
use ruminuwuity::api::federation::{
ping::unstable::{Request, Response},
pong,
};
use crate::Ruma;
/// # `GET /_matrix/federation/unstable/uk.timedout.msc0000.tabletennis/ping`
///
/// Initiates a ping
pub(crate) async fn ping(
State(services): State<crate::State>,
body: Ruma<Request>,
) -> Result<Response> {
// TODO: rate-limiting
// TODO: make answer stable based on question
let answer = random_string(64);
services.federation.register_ping_answer(answer.clone())?;
services
.server
.runtime()
.spawn(send_ping(Arc::new(services), body.identity, answer.clone()));
Ok(Response::new(answer))
}
async fn send_ping(services: Arc<crate::State>, target: OwnedServerName, answer: String) {
tokio::time::sleep(jitter(Duration::from_secs(1), 1.0..=10.0)).await;
info!(%answer, "Sending a federation pong to {target}");
match services
.sending
.send_federation_request(&target, pong::unstable::Request::new(answer))
.await
{
| Ok(_) => info!(%target, "Federation pong succeeded"),
| Err(e) =>
if e.is_not_found() {
if e.kind() == ErrorKind::Unrecognized {
warn!(%target, "Remote requested a ping but does not recognize the pong.");
} else {
info!(%target, "Ping expired by the time we ponged.");
}
} else {
warn!(%target, "Pong failed");
},
}
}
+17
View File
@@ -0,0 +1,17 @@
use axum::extract::State;
use conduwuit::Result;
use ruminuwuity::api::federation::pong;
use crate::Ruma;
/// # `GET /_matrix/federation/unstable/uk.timedout.msc0000.tabletennis/pong`
///
/// Responds to a ping
pub(crate) async fn pong(
State(services): State<crate::State>,
body: Ruma<pong::unstable::Request>,
) -> Result<pong::unstable::Response> {
// TODO: verify incoming question is already registered
services.federation.answer_ping(&body.question)?;
Ok(pong::unstable::Response::default())
}
+2
View File
@@ -0,0 +1,2 @@
pub mod ping;
pub mod pong;
+43
View File
@@ -0,0 +1,43 @@
//! `GET /_matrix/federation/*/ping`
//!
//! Initiate a federation ping
pub mod unstable {
use ruma::{
OwnedServerName,
api::{federation::authentication::ServerSignatures, request, response},
metadata,
};
metadata! {
method: POST,
rate_limited: true,
authentication: ServerSignatures, // TODO: Needs to be optional
path: "/_matrix/federation/unstable/uk.timedout.msc4524.tabletennis/ping"
}
#[request]
pub struct Request {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<OwnedServerName>,
pub question: String,
}
#[response]
pub struct Response {
pub answer: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<String>,
}
impl Request {
#[must_use]
pub fn new(question: String) -> Self { Self { question, origin: None } }
}
impl Response {
#[must_use]
pub fn new(answer: String) -> Self { Self { answer, details: vec![] } }
}
}
+30
View File
@@ -0,0 +1,30 @@
//! `GET /_matrix/federation/*/pong`
//!
//! Respond to a federation ping
pub mod unstable {
use ruma::{
api::{federation::authentication::ServerSignatures, request, response},
metadata,
};
metadata! {
method: POST,
rate_limited: false,
authentication: ServerSignatures,
path: "/_matrix/federation/unstable/uk.timedout.msc4524.tabletennis/ping"
}
#[request]
pub struct Request {
pub question: String,
}
#[response]
#[derive(Default)]
pub struct Response;
impl Request {
#[must_use]
pub fn new(question: String) -> Self { Self { question } }
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod federation;
pub use federation::*;
+1
View File
@@ -6,3 +6,4 @@ pub mod invite_permission_config;
pub mod meowlnir_antispam;
pub mod policy;
pub mod pushers;
pub mod api;
+35 -1
View File
@@ -8,7 +8,7 @@ use std::{
use assign::assign;
use async_trait::async_trait;
use conduwuit::{Error, Result, Server, SyncRwLock, debug, utils::millis_since_unix_epoch};
use conduwuit::{Err, Error, Result, Server, SyncRwLock, debug, err, error, utils::millis_since_unix_epoch};
pub(crate) use execute::FederationPathBuilderInput;
use http::StatusCode;
use ruma::{
@@ -22,6 +22,8 @@ pub struct Service {
services: Services,
pub remote_health: SyncRwLock<HashMap<OwnedServerName, (u32, u64)>>,
pub stale_destinations: SyncRwLock<HashSet<OwnedServerName>>,
/// A map of {answer: channel}
pingpongs: SyncRwLock<HashMap<String, tokio::sync::oneshot::Sender<()>>>,
}
struct Services {
@@ -43,6 +45,7 @@ impl crate::Service for Service {
},
remote_health: SyncRwLock::new(HashMap::new()),
stale_destinations: SyncRwLock::new(HashSet::new()),
pingpongs: SyncRwLock::new(HashMap::new()),
}))
}
@@ -207,4 +210,35 @@ impl Service {
pub fn stale_destinations(&self) -> HashSet<OwnedServerName> {
self.stale_destinations.read().clone()
}
/// Registers an outbound ping waiter based on the answer returned by the
/// remote. Returns a channel that is written to when the remote pongs.
pub fn register_ping_answer(
&self,
expected_answer: String,
) -> Result<tokio::sync::oneshot::Receiver<()>> {
let mut pingpongs = self.pingpongs.write();
if pingpongs.contains_key(&expected_answer) {
return Err!(Request(InvalidParam("Duplicate answer")));
}
let (tx, rx) = tokio::sync::oneshot::channel();
pingpongs.insert(expected_answer, tx);
Ok(rx)
}
/// "Answers" a registered outbound ping by sending an event to it. This is
/// called when the remote server that was pinged calls /pong.
///
/// `M_NOT_FOUND` is returned if the answer is not recognised.
pub fn answer_ping(&self, answer: &str) -> Result<()> {
let mut pingpongs = self.pingpongs.write();
let Some(tx) = pingpongs.remove(answer) else {
return Err!(Request(NotFound("Unknown answer")));
};
tx.send(()).map_err(|e| {
err!(BadServerResponse(error!(
error=?e, "Failed to handle pong"
)))
})
}
}
+2 -1
View File
@@ -571,7 +571,8 @@ impl Service {
));
}
let device_id = self.services
let device_id = self
.services
.users
.create_device(
&authorizing_user,
+6 -2
View File
@@ -72,7 +72,10 @@ impl std::fmt::Display for ValidTokenSource {
impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
let registration_tokens_from_file = args.server.config.registration_token_file
let registration_tokens_from_file = args
.server
.config
.registration_token_file
.clone()
// If the token file option was set, read the path it points to
.map(std::fs::read_to_string)
@@ -80,7 +83,8 @@ impl crate::Service for Service {
.map_err(|err| err!("Failed to read registration token file: {err}"))
.map(|tokens| {
if let Some(tokens) = tokens {
// If the token file option was set, return the file's lines as tokens
// If the token file option was set, return the file's lines
// as tokens
tokens.lines().map(ToOwned::to_owned).collect()
} else {
// Otherwise, if the option wasn't set, return no tokens
+44 -41
View File
@@ -164,12 +164,12 @@ impl Service {
}
let mut children: Vec<_> = summary
.children_state
.iter()
// Ignore deserialization failures
.flat_map(Raw::deserialize)
// Filter out non-suggested children if suggested_only is set
.filter(|child| !suggested_only || child.content.suggested)
.children_state
.iter()
// Ignore deserialization failures
.flat_map(Raw::deserialize)
// Filter out non-suggested children if suggested_only is set
.filter(|child| !suggested_only || child.content.suggested)
.collect();
children.sort();
let children = children
@@ -323,43 +323,46 @@ impl Service {
};
let (accessible_children, inaccessible_children) = children_state
.iter()
// Ignore deserialization failures
.flat_map(Raw::deserialize)
// Fetch summaries for the children in parallel
.stream()
.broad_then(async |child| {
let summary = {
if let Some(summary) = self.build_local_room_summary(&child.state_key).await {
if self.server_may_see_summary(querying_server, &summary).await {
Accessibility::Accessible(summary)
} else {
Accessibility::Inaccessible
}
} else {
Accessibility::NotFound
}
};
.iter()
// Ignore deserialization failures
.flat_map(Raw::deserialize)
// Fetch summaries for the children in parallel
.stream()
.broad_then(async |child| {
let summary = {
if let Some(summary) = self.build_local_room_summary(&child.state_key).await {
if self.server_may_see_summary(querying_server, &summary).await {
Accessibility::Accessible(summary)
} else {
Accessibility::Inaccessible
}
} else {
Accessibility::NotFound
}
};
(child.state_key, summary)
})
// Sort the children into two Vecs by accessibility
.ready_fold_default(|(mut accessible_children, mut inaccessible_children): (Vec<_>, Vec<_>), (room_id, summary)| {
match summary {
Accessibility::Accessible(summary) => {
accessible_children.push(summary);
},
Accessibility::Inaccessible => {
inaccessible_children.push(room_id);
},
Accessibility::NotFound => {
// Skip inaccessible children
}
}
(child.state_key, summary)
})
// Sort the children into two Vecs by accessibility
.ready_fold_default(
|(mut accessible_children, mut inaccessible_children): (Vec<_>, Vec<_>),
(room_id, summary)| {
match summary {
| Accessibility::Accessible(summary) => {
accessible_children.push(summary);
},
| Accessibility::Inaccessible => {
inaccessible_children.push(room_id);
},
| Accessibility::NotFound => {
// Skip inaccessible children
},
}
(accessible_children, inaccessible_children)
})
.await;
(accessible_children, inaccessible_children)
},
)
.await;
Accessibility::Accessible(assign!(
get_hierarchy::v1::Response::new(SpaceHierarchyParentSummary::new(summary, children_state)),
+7 -2
View File
@@ -449,7 +449,12 @@ impl super::Service {
// Don't notify the sender of their own events, and don't send from ignored users
.ready_filter(|user| *user != pdu.sender())
.filter_map(|recipient_user| async move {
(!self.services.users.user_is_ignored(pdu.sender(), &recipient_user).await).then_some(recipient_user)
(!self
.services
.users
.user_is_ignored(pdu.sender(), &recipient_user)
.await)
.then_some(recipient_user)
})
.collect()
.await;
@@ -806,7 +811,7 @@ impl super::Service {
.read()
.await
.values()
.map(ToOwned::to_owned) // TODO: is this to_owned expensive?
.map(ToOwned::to_owned) // TODO: is this to_owned expensive?
.collect::<Vec<_>>();
interested_appservices
.stream()
+6 -1
View File
@@ -449,7 +449,12 @@ impl super::Service {
.rooms_joined(user_id)
// Don't send key updates to unencrypted rooms
.filter_map(async |room_id| {
if self.services.state_accessor.is_encrypted_room(&room_id).await {
if self
.services
.state_accessor
.is_encrypted_room(&room_id)
.await
{
Some(room_id)
} else {
None