diff --git a/src/admin/federation/commands.rs b/src/admin/federation/commands.rs index 331231ae..d6ecd3f7 100644 --- a/src/admin/federation/commands.rs +++ b/src/admin/federation/commands.rs @@ -90,7 +90,7 @@ pub(super) async fn remote_user_in_rooms(_body: Vec<&str>, user_id: Box) .state_cache .rooms_joined(&user_id) .filter_map(Result::ok) - .map(|room_id| get_room_info(&room_id)) + .map(|room_id| get_room_info(services(), &room_id)) .collect(); if rooms.is_empty() { diff --git a/src/admin/mod.rs b/src/admin/mod.rs index c57659c1..b183f3f6 100644 --- a/src/admin/mod.rs +++ b/src/admin/mod.rs @@ -19,7 +19,7 @@ extern crate conduit_core as conduit; extern crate conduit_service as service; pub(crate) use conduit::{mod_ctor, mod_dtor, Result}; -pub(crate) use service::{services, user_is_local}; +pub(crate) use service::services; pub(crate) use crate::utils::{escape_html, get_room_info}; diff --git a/src/admin/room/room_commands.rs b/src/admin/room/room_commands.rs index d47edce2..1a387c7e 100644 --- a/src/admin/room/room_commands.rs +++ b/src/admin/room/room_commands.rs @@ -39,7 +39,7 @@ pub(super) async fn list( true }) - .map(|room_id| get_room_info(&room_id)) + .map(|room_id| get_room_info(services(), &room_id)) }) .collect::>(); rooms.sort_by_key(|r| r.1); diff --git a/src/admin/room/room_directory_commands.rs b/src/admin/room/room_directory_commands.rs index 5e81bd89..c9b4eb9e 100644 --- a/src/admin/room/room_directory_commands.rs +++ b/src/admin/room/room_directory_commands.rs @@ -29,7 +29,7 @@ pub(super) async fn process(command: RoomDirectoryCommand, _body: Vec<&str>) -> .directory .public_rooms() .filter_map(Result::ok) - .map(|id: OwnedRoomId| get_room_info(&id)) + .map(|id: OwnedRoomId| get_room_info(services(), &id)) .collect::>(); rooms.sort_by_key(|r| r.1); rooms.reverse(); diff --git a/src/admin/room/room_moderation_commands.rs b/src/admin/room/room_moderation_commands.rs index 46354c0f..8ad8295b 100644 --- a/src/admin/room/room_moderation_commands.rs +++ b/src/admin/room/room_moderation_commands.rs @@ -1,9 +1,9 @@ use api::client::leave_room; +use conduit::{debug, error, info, warn, Result}; use ruma::{events::room::message::RoomMessageEventContent, OwnedRoomId, RoomAliasId, RoomId, RoomOrAliasId}; -use tracing::{debug, error, info, warn}; use super::RoomModerationCommand; -use crate::{get_room_info, services, user_is_local, Result}; +use crate::{get_room_info, services}; pub(super) async fn process(command: RoomModerationCommand, body: Vec<&str>) -> Result { match command { @@ -110,11 +110,11 @@ async fn ban_room( .room_members(&room_id) .filter_map(|user| { user.ok().filter(|local_user| { - user_is_local(local_user) + services().globals.user_is_local(local_user) // additional wrapped check here is to avoid adding remote users // who are in the admin room to the list of local users (would // fail auth check) - && (user_is_local(local_user) + && (services().globals.user_is_local(local_user) // since this is a force operation, assume user is an admin // if somehow this fails && services() @@ -484,7 +484,7 @@ async fn list_banned_rooms(_body: Vec<&str>) -> Result let mut rooms = room_ids .into_iter() - .map(|room_id| get_room_info(&room_id)) + .map(|room_id| get_room_info(services(), &room_id)) .collect::>(); rooms.sort_by_key(|r| r.1); rooms.reverse(); diff --git a/src/admin/user/commands.rs b/src/admin/user/commands.rs index fa1c5288..69019d79 100644 --- a/src/admin/user/commands.rs +++ b/src/admin/user/commands.rs @@ -36,7 +36,7 @@ pub(super) async fn create( _body: Vec<&str>, username: String, password: Option, ) -> Result { // Validate user id - let user_id = parse_local_user_id(&username)?; + let user_id = parse_local_user_id(services(), &username)?; if services().users.exists(&user_id)? { return Ok(RoomMessageEventContent::text_plain(format!("Userid {user_id} already exists"))); @@ -134,7 +134,7 @@ pub(super) async fn deactivate( _body: Vec<&str>, no_leave_rooms: bool, user_id: String, ) -> Result { // Validate user id - let user_id = parse_local_user_id(&user_id)?; + let user_id = parse_local_user_id(services(), &user_id)?; // don't deactivate the server service account if user_id == services().globals.server_user { @@ -170,7 +170,7 @@ pub(super) async fn deactivate( } pub(super) async fn reset_password(_body: Vec<&str>, username: String) -> Result { - let user_id = parse_local_user_id(&username)?; + let user_id = parse_local_user_id(services(), &username)?; if user_id == services().globals.server_user { return Ok(RoomMessageEventContent::text_plain( @@ -211,7 +211,7 @@ pub(super) async fn deactivate_all( let mut admins = Vec::new(); for username in usernames { - match parse_active_local_user_id(username) { + match parse_active_local_user_id(services(), username) { Ok(user_id) => { if services().users.is_admin(&user_id)? && !force { services() @@ -292,14 +292,14 @@ pub(super) async fn deactivate_all( pub(super) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Result { // Validate user id - let user_id = parse_local_user_id(&user_id)?; + let user_id = parse_local_user_id(services(), &user_id)?; let mut rooms: Vec<(OwnedRoomId, u64, String)> = services() .rooms .state_cache .rooms_joined(&user_id) .filter_map(Result::ok) - .map(|room_id| get_room_info(&room_id)) + .map(|room_id| get_room_info(services(), &room_id)) .collect(); if rooms.is_empty() { @@ -344,10 +344,13 @@ pub(super) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Resu pub(super) async fn force_join_room( _body: Vec<&str>, user_id: String, room_id: OwnedRoomOrAliasId, ) -> Result { - let user_id = parse_local_user_id(&user_id)?; + let user_id = parse_local_user_id(services(), &user_id)?; let room_id = services().rooms.alias.resolve(&room_id).await?; - assert!(service::user_is_local(&user_id), "Parsed user_id must be a local user"); + assert!( + services().globals.user_is_local(&user_id), + "Parsed user_id must be a local user" + ); join_room_by_id_helper(services(), &user_id, &room_id, None, &[], None).await?; Ok(RoomMessageEventContent::notice_markdown(format!( @@ -356,13 +359,16 @@ pub(super) async fn force_join_room( } pub(super) async fn make_user_admin(_body: Vec<&str>, user_id: String) -> Result { - let user_id = parse_local_user_id(&user_id)?; + let user_id = parse_local_user_id(services(), &user_id)?; let displayname = services() .users .displayname(&user_id)? .unwrap_or_else(|| user_id.to_string()); - assert!(service::user_is_local(&user_id), "Parsed user_id must be a local user"); + assert!( + services().globals.user_is_local(&user_id), + "Parsed user_id must be a local user" + ); services() .admin .make_user_admin(&user_id, displayname) @@ -376,7 +382,7 @@ pub(super) async fn make_user_admin(_body: Vec<&str>, user_id: String) -> Result pub(super) async fn put_room_tag( _body: Vec<&str>, user_id: String, room_id: Box, tag: String, ) -> Result { - let user_id = parse_active_local_user_id(&user_id)?; + let user_id = parse_active_local_user_id(services(), &user_id)?; let event = services() .account_data @@ -411,7 +417,7 @@ pub(super) async fn put_room_tag( pub(super) async fn delete_room_tag( _body: Vec<&str>, user_id: String, room_id: Box, tag: String, ) -> Result { - let user_id = parse_active_local_user_id(&user_id)?; + let user_id = parse_active_local_user_id(services(), &user_id)?; let event = services() .account_data @@ -443,7 +449,7 @@ pub(super) async fn delete_room_tag( pub(super) async fn get_room_tags( _body: Vec<&str>, user_id: String, room_id: Box, ) -> Result { - let user_id = parse_active_local_user_id(&user_id)?; + let user_id = parse_active_local_user_id(services(), &user_id)?; let event = services() .account_data diff --git a/src/admin/utils.rs b/src/admin/utils.rs index fda42e6e..8d3d15ae 100644 --- a/src/admin/utils.rs +++ b/src/admin/utils.rs @@ -1,8 +1,6 @@ -use conduit_core::{err, Err}; +use conduit_core::{err, Err, Result}; use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId}; -use service::user_is_local; - -use crate::{services, Result}; +use service::Services; pub(crate) fn escape_html(s: &str) -> String { s.replace('&', "&") @@ -10,17 +8,17 @@ pub(crate) fn escape_html(s: &str) -> String { .replace('>', ">") } -pub(crate) fn get_room_info(id: &RoomId) -> (OwnedRoomId, u64, String) { +pub(crate) fn get_room_info(services: &Services, id: &RoomId) -> (OwnedRoomId, u64, String) { ( id.into(), - services() + services .rooms .state_cache .room_joined_count(id) .ok() .flatten() .unwrap_or(0), - services() + services .rooms .state_accessor .get_name(id) @@ -31,16 +29,16 @@ pub(crate) fn get_room_info(id: &RoomId) -> (OwnedRoomId, u64, String) { } /// Parses user ID -pub(crate) fn parse_user_id(user_id: &str) -> Result { - UserId::parse_with_server_name(user_id.to_lowercase(), services().globals.server_name()) +pub(crate) fn parse_user_id(services: &Services, user_id: &str) -> Result { + UserId::parse_with_server_name(user_id.to_lowercase(), services.globals.server_name()) .map_err(|e| err!("The supplied username is not a valid username: {e}")) } /// Parses user ID as our local user -pub(crate) fn parse_local_user_id(user_id: &str) -> Result { - let user_id = parse_user_id(user_id)?; +pub(crate) fn parse_local_user_id(services: &Services, user_id: &str) -> Result { + let user_id = parse_user_id(services, user_id)?; - if !user_is_local(&user_id) { + if !services.globals.user_is_local(&user_id) { return Err!("User {user_id:?} does not belong to our server."); } @@ -48,14 +46,14 @@ pub(crate) fn parse_local_user_id(user_id: &str) -> Result { } /// Parses user ID that is an active (not guest or deactivated) local user -pub(crate) fn parse_active_local_user_id(user_id: &str) -> Result { - let user_id = parse_local_user_id(user_id)?; +pub(crate) fn parse_active_local_user_id(services: &Services, user_id: &str) -> Result { + let user_id = parse_local_user_id(services, user_id)?; - if !services().users.exists(&user_id)? { + if !services.users.exists(&user_id)? { return Err!("User {user_id:?} does not exist on this server."); } - if services().users.is_deactivated(&user_id)? { + if services.users.is_deactivated(&user_id)? { return Err!("User {user_id:?} is deactivated."); } diff --git a/src/api/client/account.rs b/src/api/client/account.rs index b3495b42..7c2bb0b6 100644 --- a/src/api/client/account.rs +++ b/src/api/client/account.rs @@ -2,7 +2,7 @@ use std::fmt::Write; use axum::extract::State; use axum_client_ip::InsecureClientIp; -use conduit::debug_info; +use conduit::{debug_info, error, info, utils, warn, Error, Result}; use register::RegistrationKind; use ruma::{ api::client::{ @@ -18,14 +18,9 @@ use ruma::{ events::{room::message::RoomMessageEventContent, GlobalAccountDataEventType}, push, OwnedRoomId, UserId, }; -use tracing::{error, info, warn}; use super::{join_room_by_id_helper, DEVICE_ID_LENGTH, SESSION_ID_LENGTH, TOKEN_LENGTH}; -use crate::{ - service::user_is_local, - utils::{self}, - Error, Result, Ruma, -}; +use crate::Ruma; const RANDOM_USER_ID_LENGTH: usize = 10; @@ -48,7 +43,7 @@ pub(crate) async fn get_register_available_route( // Validate user id let user_id = UserId::parse_with_server_name(body.username.to_lowercase(), services.globals.server_name()) .ok() - .filter(|user_id| !user_id.is_historical() && user_is_local(user_id)) + .filter(|user_id| !user_id.is_historical() && services.globals.user_is_local(user_id)) .ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?; // Check if username is creative enough @@ -136,7 +131,7 @@ pub(crate) async fn register_route( let proposed_user_id = UserId::parse_with_server_name(username.to_lowercase(), services.globals.server_name()) .ok() - .filter(|user_id| !user_id.is_historical() && user_is_local(user_id)) + .filter(|user_id| !user_id.is_historical() && services.globals.user_is_local(user_id)) .ok_or(Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid."))?; if services.users.exists(&proposed_user_id)? { diff --git a/src/api/client/alias.rs b/src/api/client/alias.rs index 11617a0e..dbc75e64 100644 --- a/src/api/client/alias.rs +++ b/src/api/client/alias.rs @@ -1,4 +1,5 @@ use axum::extract::State; +use conduit::{debug, Error, Result}; use rand::seq::SliceRandom; use ruma::{ api::client::{ @@ -7,12 +8,9 @@ use ruma::{ }, OwnedServerName, RoomAliasId, RoomId, }; -use tracing::debug; +use service::Services; -use crate::{ - service::{server_is_ours, Services}, - Error, Result, Ruma, -}; +use crate::Ruma; /// # `PUT /_matrix/client/v3/directory/room/{roomAlias}` /// @@ -142,7 +140,7 @@ fn room_available_servers( // prefer the room alias server first if let Some(server_index) = servers .iter() - .position(|server_name| server_is_ours(server_name)) + .position(|server_name| services.globals.server_is_ours(server_name)) { servers.swap_remove(server_index); servers.insert(0, services.globals.server_name().to_owned()); diff --git a/src/api/client/directory.rs b/src/api/client/directory.rs index deebd250..cb30b60a 100644 --- a/src/api/client/directory.rs +++ b/src/api/client/directory.rs @@ -20,11 +20,9 @@ use ruma::{ }, uint, RoomId, ServerName, UInt, UserId, }; +use service::Services; -use crate::{ - service::{server_is_ours, Services}, - Ruma, -}; +use crate::Ruma; /// # `POST /_matrix/client/v3/publicRooms` /// @@ -187,7 +185,7 @@ pub(crate) async fn get_public_rooms_filtered_helper( services: &Services, server: Option<&ServerName>, limit: Option, since: Option<&str>, filter: &Filter, _network: &RoomNetwork, ) -> Result { - if let Some(other_server) = server.filter(|server_name| !server_is_ours(server_name)) { + if let Some(other_server) = server.filter(|server_name| !services.globals.server_is_ours(server_name)) { let response = services .sending .send_federation_request( diff --git a/src/api/client/keys.rs b/src/api/client/keys.rs index 728ea7a9..8489dde3 100644 --- a/src/api/client/keys.rs +++ b/src/api/client/keys.rs @@ -4,7 +4,7 @@ use std::{ }; use axum::extract::State; -use conduit::{utils, utils::math::continue_exponential_backoff_secs, Error, Result}; +use conduit::{debug, utils, utils::math::continue_exponential_backoff_secs, Error, Result}; use futures_util::{stream::FuturesUnordered, StreamExt}; use ruma::{ api::{ @@ -19,8 +19,6 @@ use ruma::{ DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId, }; use serde_json::json; -use service::user_is_local; -use tracing::debug; use super::SESSION_ID_LENGTH; use crate::{service::Services, Ruma}; @@ -266,7 +264,7 @@ pub(crate) async fn get_keys_helper bool + Send>( for (user_id, device_ids) in device_keys_input { let user_id: &UserId = user_id; - if !user_is_local(user_id) { + if !services.globals.user_is_local(user_id) { get_over_federation .entry(user_id.server_name()) .or_insert_with(Vec::new) @@ -459,7 +457,7 @@ pub(crate) async fn claim_keys_helper( let mut get_over_federation = BTreeMap::new(); for (user_id, map) in one_time_keys_input { - if !user_is_local(user_id) { + if !services.globals.user_is_local(user_id) { get_over_federation .entry(user_id.server_name()) .or_insert_with(Vec::new) diff --git a/src/api/client/media.rs b/src/api/client/media.rs index e219e457..78463fc6 100644 --- a/src/api/client/media.rs +++ b/src/api/client/media.rs @@ -4,7 +4,15 @@ use std::{io::Cursor, time::Duration}; use axum::extract::State; use axum_client_ip::InsecureClientIp; -use conduit::{debug, error, utils::math::ruma_from_usize, warn}; +use conduit::{ + debug, debug_warn, error, + utils::{ + self, + content_disposition::{content_disposition_type, make_content_disposition, sanitise_filename}, + math::ruma_from_usize, + }, + warn, Error, Result, +}; use image::io::Reader as ImgReader; use ipaddress::IPAddress; use reqwest::Url; @@ -15,20 +23,13 @@ use ruma::api::client::{ get_media_preview, }, }; +use service::{ + media::{FileMeta, UrlPreviewData}, + Services, +}; use webpage::HTML; -use crate::{ - debug_warn, - service::{ - media::{FileMeta, UrlPreviewData}, - server_is_ours, Services, - }, - utils::{ - self, - content_disposition::{content_disposition_type, make_content_disposition, sanitise_filename}, - }, - Error, Result, Ruma, RumaResponse, -}; +use crate::{Ruma, RumaResponse}; /// generated MXC ID (`media-id`) length const MXC_LENGTH: usize = 32; @@ -218,7 +219,7 @@ pub(crate) async fn get_content_route( cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()), cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()), }) - } else if !server_is_ours(&body.server_name) && body.allow_remote { + } else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { let response = get_remote_content( services, &mxc, @@ -308,7 +309,7 @@ pub(crate) async fn get_content_as_filename_route( cross_origin_resource_policy: Some(CORP_CROSS_ORIGIN.to_owned()), cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()), }) - } else if !server_is_ours(&body.server_name) && body.allow_remote { + } else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { match get_remote_content( services, &mxc, @@ -408,7 +409,7 @@ pub(crate) async fn get_content_thumbnail_route( cache_control: Some(CACHE_CONTROL_IMMUTABLE.into()), content_disposition, }) - } else if !server_is_ours(&body.server_name) && body.allow_remote { + } else if !services.globals.server_is_ours(&body.server_name) && body.allow_remote { if services .globals .prevent_media_downloads_from() diff --git a/src/api/client/membership.rs b/src/api/client/membership.rs index e3630c72..d3b2d8f6 100644 --- a/src/api/client/membership.rs +++ b/src/api/client/membership.rs @@ -8,8 +8,11 @@ use std::{ use axum::extract::State; use axum_client_ip::InsecureClientIp; use conduit::{ - debug, debug_warn, error, info, trace, utils, utils::math::continue_exponential_backoff_secs, warn, Error, - PduEvent, Result, + debug, debug_warn, error, info, + pdu::{gen_event_id_canonical_json, PduBuilder}, + trace, utils, + utils::math::continue_exponential_backoff_secs, + warn, Error, PduEvent, Result, }; use ruma::{ api::{ @@ -36,15 +39,11 @@ use ruma::{ OwnedUserId, RoomId, RoomVersionId, ServerName, UserId, }; use serde_json::value::{to_raw_value, RawValue as RawJsonValue}; +use service::{rooms::state::RoomMutexGuard, Services}; use tokio::sync::RwLock; use crate::{ client::{update_avatar_url, update_displayname}, - service::{ - pdu::{gen_event_id_canonical_json, PduBuilder}, - rooms::state::RoomMutexGuard, - server_is_ours, user_is_local, Services, - }, Ruma, }; @@ -675,7 +674,7 @@ pub async fn join_room_by_id_helper( .state_cache .server_in_room(services.globals.server_name(), room_id)? || servers.is_empty() - || (servers.len() == 1 && server_is_ours(&servers[0])) + || (servers.len() == 1 && services.globals.server_is_ours(&servers[0])) { join_room_by_id_helper_local(services, sender_user, room_id, reason, servers, third_party_signed, state_lock) .await @@ -1049,7 +1048,7 @@ async fn join_room_by_id_helper_local( .state_cache .room_members(room_id) .filter_map(Result::ok) - .filter(|user| user_is_local(user)) + .filter(|user| services.globals.user_is_local(user)) .collect::>(); let mut join_authorized_via_users_server: Option = None; @@ -1110,7 +1109,7 @@ async fn join_room_by_id_helper_local( if !restriction_rooms.is_empty() && servers .iter() - .any(|server_name| !server_is_ours(server_name)) + .any(|server_name| !services.globals.server_is_ours(server_name)) { warn!("We couldn't do the join locally, maybe federation can help to satisfy the restricted join requirements"); let (make_join_response, remote_server) = make_join_request(services, sender_user, room_id, servers).await?; @@ -1259,7 +1258,7 @@ async fn make_join_request( let mut incompatible_room_version_count: u8 = 0; for remote_server in servers { - if server_is_ours(remote_server) { + if services.globals.server_is_ours(remote_server) { continue; } info!("Asking {remote_server} for make_join ({make_join_counter})"); @@ -1389,7 +1388,7 @@ pub(crate) async fn invite_helper( )); } - if !user_is_local(user_id) { + if !services.globals.user_is_local(user_id) { let (pdu, pdu_json, invite_room_state) = { let state_lock = services.rooms.state.mutex.lock(room_id).await; let content = to_raw_value(&RoomMemberEventContent { diff --git a/src/api/client/profile.rs b/src/api/client/profile.rs index 3b2c32ec..9e9bcf8e 100644 --- a/src/api/client/profile.rs +++ b/src/api/client/profile.rs @@ -1,4 +1,5 @@ use axum::extract::State; +use conduit::{pdu::PduBuilder, warn, Error, Result}; use ruma::{ api::{ client::{ @@ -12,12 +13,9 @@ use ruma::{ OwnedMxcUri, OwnedRoomId, OwnedUserId, }; use serde_json::value::to_raw_value; -use tracing::warn; +use service::Services; -use crate::{ - service::{pdu::PduBuilder, user_is_local, Services}, - Error, Result, Ruma, -}; +use crate::Ruma; /// # `PUT /_matrix/client/r0/profile/{userId}/displayname` /// @@ -56,7 +54,7 @@ pub(crate) async fn set_displayname_route( pub(crate) async fn get_displayname_route( State(services): State, body: Ruma, ) -> Result { - if !user_is_local(&body.user_id) { + if !services.globals.user_is_local(&body.user_id) { // Create and update our local copy of the user if let Ok(response) = services .sending @@ -147,7 +145,7 @@ pub(crate) async fn set_avatar_url_route( pub(crate) async fn get_avatar_url_route( State(services): State, body: Ruma, ) -> Result { - if !user_is_local(&body.user_id) { + if !services.globals.user_is_local(&body.user_id) { // Create and update our local copy of the user if let Ok(response) = services .sending @@ -205,7 +203,7 @@ pub(crate) async fn get_avatar_url_route( pub(crate) async fn get_profile_route( State(services): State, body: Ruma, ) -> Result { - if !user_is_local(&body.user_id) { + if !services.globals.user_is_local(&body.user_id) { // Create and update our local copy of the user if let Ok(response) = services .sending diff --git a/src/api/client/state.rs b/src/api/client/state.rs index 56ffd2ac..7af4f5f9 100644 --- a/src/api/client/state.rs +++ b/src/api/client/state.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use axum::extract::State; -use conduit::{debug_info, error}; +use conduit::{debug_info, error, pdu::PduBuilder, Error, Result}; use ruma::{ api::client::{ error::ErrorKind, @@ -18,11 +18,9 @@ use ruma::{ serde::Raw, EventId, RoomId, UserId, }; +use service::Services; -use crate::{ - service::{pdu::PduBuilder, server_is_ours, Services}, - Error, Result, Ruma, RumaResponse, -}; +use crate::{Ruma, RumaResponse}; /// # `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}` /// @@ -250,7 +248,7 @@ async fn allowed_to_send_state_event( } for alias in aliases { - if !server_is_ours(alias.server_name()) + if !services.globals.server_is_ours(alias.server_name()) || services .rooms .alias diff --git a/src/api/client/to_device.rs b/src/api/client/to_device.rs index 8476ff41..1f557ad7 100644 --- a/src/api/client/to_device.rs +++ b/src/api/client/to_device.rs @@ -1,6 +1,7 @@ use std::collections::BTreeMap; use axum::extract::State; +use conduit::{Error, Result}; use ruma::{ api::{ client::{error::ErrorKind, to_device::send_event_to_device}, @@ -9,7 +10,7 @@ use ruma::{ to_device::DeviceIdOrAllDevices, }; -use crate::{user_is_local, Error, Result, Ruma}; +use crate::Ruma; /// # `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}` /// @@ -31,7 +32,7 @@ pub(crate) async fn send_event_to_device_route( for (target_user_id, map) in &body.messages { for (target_device_id_maybe, event) in map { - if !user_is_local(target_user_id) { + if !services.globals.user_is_local(target_user_id) { let mut map = BTreeMap::new(); map.insert(target_device_id_maybe.clone(), event.clone()); let mut messages = BTreeMap::new(); diff --git a/src/api/mod.rs b/src/api/mod.rs index 0d80e581..c7411b6c 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -7,8 +7,8 @@ pub mod server; extern crate conduit_core as conduit; extern crate conduit_service as service; -pub(crate) use conduit::{debug_info, debug_warn, pdu::PduEvent, utils, Error, Result}; -pub(crate) use service::{services, user_is_local}; +pub(crate) use conduit::{debug_info, pdu::PduEvent, utils, Error, Result}; +pub(crate) use service::services; pub use crate::router::State; pub(crate) use crate::router::{Ruma, RumaResponse}; diff --git a/src/api/server/invite.rs b/src/api/server/invite.rs index 17e21920..688e026c 100644 --- a/src/api/server/invite.rs +++ b/src/api/server/invite.rs @@ -7,7 +7,6 @@ use ruma::{ serde::JsonObject, CanonicalJsonValue, EventId, OwnedUserId, }; -use service::server_is_ours; use crate::Ruma; @@ -88,7 +87,7 @@ pub(crate) async fn create_invite_route( ) .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "state_key is not a user ID."))?; - if !server_is_ours(invited_user.server_name()) { + if !services.globals.server_is_ours(invited_user.server_name()) { return Err(Error::BadRequest( ErrorKind::InvalidParam, "User does not belong to this homeserver.", diff --git a/src/api/server/query.rs b/src/api/server/query.rs index dddf23e7..5712f46a 100644 --- a/src/api/server/query.rs +++ b/src/api/server/query.rs @@ -1,4 +1,5 @@ use axum::extract::State; +use conduit::{Error, Result}; use get_profile_information::v1::ProfileField; use rand::seq::SliceRandom; use ruma::{ @@ -9,7 +10,7 @@ use ruma::{ OwnedServerName, }; -use crate::{service::server_is_ours, Error, Result, Ruma}; +use crate::Ruma; /// # `GET /_matrix/federation/v1/query/directory` /// @@ -64,7 +65,7 @@ pub(crate) async fn get_profile_information_route( )); } - if !server_is_ours(body.user_id.server_name()) { + if !services.globals.server_is_ours(body.user_id.server_name()) { return Err(Error::BadRequest( ErrorKind::InvalidParam, "User does not belong to this server.", diff --git a/src/api/server/send_join.rs b/src/api/server/send_join.rs index 7f79a1d9..4cd29795 100644 --- a/src/api/server/send_join.rs +++ b/src/api/server/send_join.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use axum::extract::State; -use conduit::{Error, Result}; +use conduit::{pdu::gen_event_id_canonical_json, warn, Error, Result}; use ruma::{ api::{client::error::ErrorKind, federation::membership::create_join_event}, events::{ @@ -13,9 +13,8 @@ use ruma::{ CanonicalJsonValue, OwnedServerName, OwnedUserId, RoomId, ServerName, }; use serde_json::value::{to_raw_value, RawValue as RawJsonValue}; -use service::{pdu::gen_event_id_canonical_json, user_is_local, Services}; +use service::Services; use tokio::sync::RwLock; -use tracing::warn; use crate::Ruma; @@ -126,7 +125,7 @@ async fn create_join_event( if content .join_authorized_via_users_server - .is_some_and(|user| user_is_local(&user)) + .is_some_and(|user| services.globals.user_is_local(&user)) && super::user_can_perform_restricted_join(services, &sender, room_id, &room_version_id).unwrap_or_default() { ruma::signatures::hash_and_sign_event( diff --git a/src/api/server/send_leave.rs b/src/api/server/send_leave.rs index f7484a33..b1b8fec8 100644 --- a/src/api/server/send_leave.rs +++ b/src/api/server/send_leave.rs @@ -3,6 +3,7 @@ use std::collections::BTreeMap; use axum::extract::State; +use conduit::{Error, Result}; use ruma::{ api::{client::error::ErrorKind, federation::membership::create_leave_event}, events::{ @@ -15,8 +16,8 @@ use serde_json::value::RawValue as RawJsonValue; use tokio::sync::RwLock; use crate::{ - service::{pdu::gen_event_id_canonical_json, server_is_ours, Services}, - Error, Result, Ruma, + service::{pdu::gen_event_id_canonical_json, Services}, + Ruma, }; /// # `PUT /_matrix/federation/v1/send_leave/{roomId}/{eventId}` @@ -174,7 +175,7 @@ async fn create_leave_event( .state_cache .room_servers(room_id) .filter_map(Result::ok) - .filter(|server| !server_is_ours(server)); + .filter(|server| !services.globals.server_is_ours(server)); services.sending.send_pdu_servers(servers, &pdu_id)?; diff --git a/src/api/server/user.rs b/src/api/server/user.rs index 949e5f38..bd0372e6 100644 --- a/src/api/server/user.rs +++ b/src/api/server/user.rs @@ -1,4 +1,5 @@ use axum::extract::State; +use conduit::{Error, Result}; use ruma::api::{ client::error::ErrorKind, federation::{ @@ -9,8 +10,7 @@ use ruma::api::{ use crate::{ client::{claim_keys_helper, get_keys_helper}, - service::user_is_local, - Error, Result, Ruma, + Ruma, }; /// # `GET /_matrix/federation/v1/user/devices/{userId}` @@ -19,7 +19,7 @@ use crate::{ pub(crate) async fn get_devices_route( State(services): State, body: Ruma, ) -> Result { - if !user_is_local(&body.user_id) { + if !services.globals.user_is_local(&body.user_id) { return Err(Error::BadRequest( ErrorKind::InvalidParam, "Tried to access user from other server.", @@ -72,7 +72,11 @@ pub(crate) async fn get_devices_route( pub(crate) async fn get_keys_route( State(services): State, body: Ruma, ) -> Result { - if body.device_keys.iter().any(|(u, _)| !user_is_local(u)) { + if body + .device_keys + .iter() + .any(|(u, _)| !services.globals.user_is_local(u)) + { return Err(Error::BadRequest( ErrorKind::InvalidParam, "User does not belong to this server.", @@ -101,7 +105,11 @@ pub(crate) async fn get_keys_route( pub(crate) async fn claim_keys_route( State(services): State, body: Ruma, ) -> Result { - if body.one_time_keys.iter().any(|(u, _)| !user_is_local(u)) { + if body + .one_time_keys + .iter() + .any(|(u, _)| !services.globals.user_is_local(u)) + { return Err(Error::BadRequest( ErrorKind::InvalidParam, "Tried to access user from other server.", diff --git a/src/core/server.rs b/src/core/server.rs index bf0ab99d..89f1dea5 100644 --- a/src/core/server.rs +++ b/src/core/server.rs @@ -109,4 +109,7 @@ impl Server { #[inline] pub fn running(&self) -> bool { !self.stopping.load(Ordering::Acquire) } + + #[inline] + pub fn is_ours(&self, name: &str) -> bool { name == self.config.server_name } } diff --git a/src/service/admin/mod.rs b/src/service/admin/mod.rs index 8b9473a2..1d51bf38 100644 --- a/src/service/admin/mod.rs +++ b/src/service/admin/mod.rs @@ -22,7 +22,7 @@ use ruma::{ use serde_json::value::to_raw_value; use tokio::sync::{Mutex, RwLock}; -use crate::{globals, rooms, rooms::state::RoomMutexGuard, user_is_local, Dep}; +use crate::{globals, rooms, rooms::state::RoomMutexGuard, Dep}; pub struct Service { services: Services, @@ -301,7 +301,7 @@ impl Service { } // only allow public escaped commands by local admins - if is_public_escape && !user_is_local(&pdu.sender) { + if is_public_escape && !self.services.globals.user_is_local(&pdu.sender) { return false; } diff --git a/src/service/globals/mod.rs b/src/service/globals/mod.rs index eab156ee..c2c7d969 100644 --- a/src/service/globals/mod.rs +++ b/src/service/globals/mod.rs @@ -21,7 +21,7 @@ use ruma::{ use tokio::sync::Mutex; use url::Url; -use crate::{service, services}; +use crate::service; pub struct Service { pub db: Data, @@ -302,13 +302,11 @@ impl Service { true } + + /// checks if `user_id` is local to us via server_name comparison + #[inline] + pub fn user_is_local(&self, user_id: &UserId) -> bool { self.server_is_ours(user_id.server_name()) } + + #[inline] + pub fn server_is_ours(&self, server_name: &ServerName) -> bool { server_name == self.config.server_name } } - -#[inline] -#[must_use] -pub fn server_is_ours(server_name: &ServerName) -> bool { server_name == services().globals.config.server_name } - -/// checks if `user_id` is local to us via server_name comparison -#[inline] -#[must_use] -pub fn user_is_local(user_id: &UserId) -> bool { server_is_ours(user_id.server_name()) } diff --git a/src/service/mod.rs b/src/service/mod.rs index 6e749c99..ce106809 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -33,10 +33,7 @@ use conduit::{Result, Server}; use database::Database; pub(crate) use service::{Args, Dep, Service}; -pub use crate::{ - globals::{server_is_ours, user_is_local}, - services::Services, -}; +pub use crate::services::Services; conduit::mod_ctor! {} conduit::mod_dtor! {} diff --git a/src/service/presence/mod.rs b/src/service/presence/mod.rs index 705ac4ff..b8673304 100644 --- a/src/service/presence/mod.rs +++ b/src/service/presence/mod.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use tokio::{sync::Mutex, time::sleep}; use self::data::Data; -use crate::{user_is_local, users, Dep}; +use crate::{globals, users, Dep}; /// Represents data required to be kept in order to implement the presence /// specification. @@ -80,6 +80,7 @@ pub struct Service { struct Services { server: Arc, + globals: Dep, users: Dep, } @@ -93,6 +94,7 @@ impl crate::Service for Service { Ok(Arc::new(Self { services: Services { server: args.server.clone(), + globals: args.depend::("globals"), users: args.depend::("users"), }, db: Data::new(&args), @@ -185,7 +187,7 @@ impl Service { self.db .set_presence(user_id, presence_state, currently_active, last_active_ago, status_msg)?; - if self.timeout_remote_users || user_is_local(user_id) { + if self.timeout_remote_users || self.services.globals.user_is_local(user_id) { let timeout = match presence_state { PresenceState::Online => self.services.server.config.presence_idle_timeout_s, _ => self.services.server.config.presence_offline_timeout_s, diff --git a/src/service/rooms/alias/mod.rs b/src/service/rooms/alias/mod.rs index 344ab6d2..f2e01ab5 100644 --- a/src/service/rooms/alias/mod.rs +++ b/src/service/rooms/alias/mod.rs @@ -14,7 +14,7 @@ use ruma::{ }; use self::data::Data; -use crate::{admin, appservice, appservice::RegistrationInfo, globals, rooms, sending, server_is_ours, Dep}; +use crate::{admin, appservice, appservice::RegistrationInfo, globals, rooms, sending, Dep}; pub struct Service { db: Data, @@ -85,7 +85,10 @@ impl Service { pub async fn resolve_alias( &self, room_alias: &RoomAliasId, servers: Option<&Vec>, ) -> Result<(OwnedRoomId, Option>)> { - if !server_is_ours(room_alias.server_name()) + if !self + .services + .globals + .server_is_ours(room_alias.server_name()) && (!servers .as_ref() .is_some_and(|servers| servers.contains(&self.services.globals.server_name().to_owned())) @@ -195,7 +198,11 @@ impl Service { pub async fn appservice_checks( &self, room_alias: &RoomAliasId, appservice_info: &Option, ) -> Result<()> { - if !server_is_ours(room_alias.server_name()) { + if !self + .services + .globals + .server_is_ours(room_alias.server_name()) + { return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server.")); } diff --git a/src/service/rooms/state_cache/data.rs b/src/service/rooms/state_cache/data.rs index cbda73cf..19c73ea1 100644 --- a/src/service/rooms/state_cache/data.rs +++ b/src/service/rooms/state_cache/data.rs @@ -12,7 +12,7 @@ use ruma::{ OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, ServerName, UserId, }; -use crate::{appservice::RegistrationInfo, globals, user_is_local, users, Dep}; +use crate::{appservice::RegistrationInfo, globals, users, Dep}; type StrippedStateEventIter<'a> = Box>)>> + 'a>; type AnySyncStateEventIter<'a> = Box>)>> + 'a>; @@ -355,7 +355,7 @@ impl Data { Box::new( self.room_members(room_id) .filter_map(Result::ok) - .filter(|user| user_is_local(user)), + .filter(|user| self.services.globals.user_is_local(user)), ) } diff --git a/src/service/rooms/state_cache/mod.rs b/src/service/rooms/state_cache/mod.rs index ac2f688e..71899ceb 100644 --- a/src/service/rooms/state_cache/mod.rs +++ b/src/service/rooms/state_cache/mod.rs @@ -21,7 +21,7 @@ use ruma::{ OwnedRoomId, OwnedServerName, OwnedUserId, RoomId, ServerName, UserId, }; -use crate::{account_data, appservice::RegistrationInfo, rooms, user_is_local, users, Dep}; +use crate::{account_data, appservice::RegistrationInfo, globals, rooms, users, Dep}; pub struct Service { services: Services, @@ -30,6 +30,7 @@ pub struct Service { struct Services { account_data: Dep, + globals: Dep, state_accessor: Dep, users: Dep, } @@ -39,6 +40,7 @@ impl crate::Service for Service { Ok(Arc::new(Self { services: Services { account_data: args.depend::("account_data"), + globals: args.depend::("globals"), state_accessor: args.depend::("rooms::state_accessor"), users: args.depend::("users"), }, @@ -65,7 +67,7 @@ impl Service { // TODO: use futures to update remote profiles without blocking the membership // update #[allow(clippy::collapsible_if)] - if !user_is_local(user_id) { + if !self.services.globals.user_is_local(user_id) { if !self.services.users.exists(user_id)? { self.services.users.create(user_id, None)?; } diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index 50d29475..82b1cd0c 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -41,7 +41,7 @@ use tokio::sync::RwLock; use self::data::Data; use crate::{ account_data, admin, appservice, appservice::NamespaceRegex, globals, pusher, rooms, - rooms::state_compressor::CompressedStateEvent, sending, server_is_ours, Dep, + rooms::state_compressor::CompressedStateEvent, sending, Dep, }; // Update Relationships @@ -846,7 +846,7 @@ impl Service { .state_cache .room_members(room_id) .filter_map(Result::ok) - .filter(|m| server_is_ours(m.server_name()) && m != target) + .filter(|m| self.services.globals.server_is_ours(m.server_name()) && m != target) .count(); if count < 2 { warn!("Last admin cannot leave from admins room"); @@ -871,7 +871,7 @@ impl Service { .state_cache .room_members(room_id) .filter_map(Result::ok) - .filter(|m| server_is_ours(m.server_name()) && m != target) + .filter(|m| self.services.globals.server_is_ours(m.server_name()) && m != target) .count(); if count < 2 { warn!("Last admin cannot be banned in admins room"); @@ -1092,7 +1092,7 @@ impl Service { .unwrap_or_default(); let room_mods = power_levels.users.iter().filter_map(|(user_id, level)| { - if level > &power_levels.users_default && !server_is_ours(user_id.server_name()) { + if level > &power_levels.users_default && !self.services.globals.user_is_local(user_id) { Some(user_id.server_name().to_owned()) } else { None @@ -1106,7 +1106,7 @@ impl Service { .filter_map(|alias| { alias .ok() - .filter(|alias| !server_is_ours(alias.server_name())) + .filter(|alias| !self.services.globals.server_is_ours(alias.server_name())) .map(|alias| alias.server_name().to_owned()) }); @@ -1114,7 +1114,7 @@ impl Service { .chain(room_alias_servers) .chain(self.services.server.config.trusted_servers.clone()) .filter(|server_name| { - if server_is_ours(server_name) { + if self.services.globals.server_is_ours(server_name) { return false; } diff --git a/src/service/rooms/typing/mod.rs b/src/service/rooms/typing/mod.rs index d863f217..3cf1cdd5 100644 --- a/src/service/rooms/typing/mod.rs +++ b/src/service/rooms/typing/mod.rs @@ -8,7 +8,7 @@ use ruma::{ }; use tokio::sync::{broadcast, RwLock}; -use crate::{globals, sending, user_is_local, Dep}; +use crate::{globals, sending, Dep}; pub struct Service { server: Arc, @@ -63,7 +63,7 @@ impl Service { } // update federation - if user_is_local(user_id) { + if self.services.globals.user_is_local(user_id) { self.federation_send(room_id, user_id, true)?; } @@ -89,7 +89,7 @@ impl Service { } // update federation - if user_is_local(user_id) { + if self.services.globals.user_is_local(user_id) { self.federation_send(room_id, user_id, false)?; } @@ -145,7 +145,7 @@ impl Service { // update federation for user in removable { - if user_is_local(&user) { + if self.services.globals.user_is_local(&user) { self.federation_send(room_id, &user, false)?; } } @@ -184,7 +184,11 @@ impl Service { } fn federation_send(&self, room_id: &RoomId, user_id: &UserId, typing: bool) -> Result<()> { - debug_assert!(user_is_local(user_id), "tried to broadcast typing status of remote user",); + debug_assert!( + self.services.globals.user_is_local(user_id), + "tried to broadcast typing status of remote user", + ); + if !self.server.config.allow_outgoing_typing { return Ok(()); } diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index 6f091b04..fc32d04f 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -13,7 +13,7 @@ use ruma::{ }; use tokio::sync::Mutex; -use crate::{account_data, client, globals, presence, pusher, resolver, rooms, server_is_ours, users, Dep}; +use crate::{account_data, client, globals, presence, pusher, resolver, rooms, users, Dep}; pub struct Service { server: Arc, @@ -136,7 +136,7 @@ impl Service { .state_cache .room_servers(room_id) .filter_map(Result::ok) - .filter(|server_name| !server_is_ours(server_name)); + .filter(|server_name| !self.services.globals.server_is_ours(server_name)); self.send_pdu_servers(servers, pdu_id) } @@ -185,7 +185,7 @@ impl Service { .state_cache .room_servers(room_id) .filter_map(Result::ok) - .filter(|server_name| !server_is_ours(server_name)); + .filter(|server_name| !self.services.globals.server_is_ours(server_name)); self.send_edu_servers(servers, serialized) } @@ -222,7 +222,7 @@ impl Service { .state_cache .room_servers(room_id) .filter_map(Result::ok) - .filter(|server_name| !server_is_ours(server_name)); + .filter(|server_name| !self.services.globals.server_is_ours(server_name)); self.flush_servers(servers) } diff --git a/src/service/sending/sender.rs b/src/service/sending/sender.rs index 0668ce24..9fbc30ea 100644 --- a/src/service/sending/sender.rs +++ b/src/service/sending/sender.rs @@ -29,7 +29,6 @@ use serde_json::value::{to_raw_value, RawValue as RawJsonValue}; use tokio::time::sleep_until; use super::{appservice, Destination, Msg, SendingEvent, Service}; -use crate::user_is_local; #[derive(Debug)] enum TransactionStatus { @@ -264,7 +263,7 @@ impl Service { .users .keys_changed(room_id.as_ref(), since, None) .filter_map(Result::ok) - .filter(|user_id| user_is_local(user_id)), + .filter(|user_id| self.services.globals.user_is_local(user_id)), ); if self.server.config.allow_outgoing_read_receipts @@ -306,7 +305,7 @@ impl Service { for (user_id, count, presence_bytes) in self.services.presence.presence_since(since) { *max_edu_count = cmp::max(count, *max_edu_count); - if !user_is_local(&user_id) { + if !self.services.globals.user_is_local(&user_id) { continue; } @@ -358,7 +357,7 @@ impl Service { let (user_id, count, read_receipt) = r?; *max_edu_count = cmp::max(count, *max_edu_count); - if !user_is_local(&user_id) { + if !self.services.globals.user_is_local(&user_id) { continue; }