Upgrade Ruma #775

Closed
jplatte wants to merge 3 commits from jplatte/up-ruma into next
30 changed files with 470 additions and 419 deletions

501
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -21,7 +21,7 @@ tower-http = { version = "0.2.1", features = ["add-extension", "cors", "compress
# Used for matrix spec type definitions and helpers # 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"] } #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"] }
ruma = { git = "https://github.com/ruma/ruma", rev = "d614ad1422d6c4b3437ebc318ca8514ae338fd6d", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-pre-spec", "unstable-exhaustive-types"] } ruma = { git = "https://github.com/ruma/ruma", rev = "a8e7c47bbe00047adcd10b2e5e860fd4d8cbf9fe", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-msc2448", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { git = "https://github.com/timokoesters/ruma", rev = "50c1db7e0a3a21fc794b0cce3b64285a4c750c71", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] } #ruma = { git = "https://github.com/timokoesters/ruma", rev = "50c1db7e0a3a21fc794b0cce3b64285a4c750c71", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }
#ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] } #ruma = { path = "../ruma/crates/ruma", features = ["compat", "rand", "appservice-api-c", "client-api", "federation-api", "push-gateway-api-c", "state-res", "unstable-pre-spec", "unstable-exhaustive-types"] }

View file

@ -16,8 +16,10 @@ use ruma::{
uiaa::{AuthFlow, AuthType, UiaaInfo}, uiaa::{AuthFlow, AuthType, UiaaInfo},
}, },
events::{ events::{
room::member::{MembershipState, RoomMemberEventContent}, room::{
room::message::RoomMessageEventContent, member::{MembershipState, RoomMemberEventContent},
message::RoomMessageEventContent,
},
GlobalAccountDataEventType, RoomEventType, GlobalAccountDataEventType, RoomEventType,
}, },
push, UserId, push, UserId,
@ -345,12 +347,12 @@ pub async fn whoami_route(
body: Ruma<whoami::v3::Request>, body: Ruma<whoami::v3::Request>,
) -> Result<whoami::v3::Response> { ) -> Result<whoami::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let device_id = body.sender_device.as_ref().cloned(); let device_id = body.sender_device.clone();
Ok(whoami::v3::Response { Ok(whoami::v3::Response {
user_id: sender_user.clone(), user_id: sender_user.clone(),
device_id, device_id,
is_guest: db.users.is_deactivated(&sender_user)?, is_guest: db.users.is_deactivated(sender_user)?,
}) })
} }

View file

@ -285,9 +285,9 @@ pub(crate) async fn get_public_rooms_filtered_helper(
}) })
.transpose()? .transpose()?
.flatten() .flatten()
.ok_or(Error::bad_database( .ok_or_else(|| {
"Invalid room join rule event in database.", Error::bad_database("Invalid room join rule event in database.")
))?, })?,
room_id, room_id,
}; };
Ok(chunk) Ok(chunk)

View file

@ -14,7 +14,7 @@ use ruma::{
federation, federation,
}, },
serde::Raw, serde::Raw,
DeviceId, DeviceKeyAlgorithm, UserId, DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId, UserId,
}; };
use serde_json::json; use serde_json::json;
use std::collections::{BTreeMap, HashMap, HashSet}; use std::collections::{BTreeMap, HashMap, HashSet};
@ -257,7 +257,7 @@ pub async fn get_key_changes_route(
device_list_updates.extend( device_list_updates.extend(
db.users db.users
.keys_changed( .keys_changed(
&room_id.to_string(), room_id.as_str(),
body.from.parse().map_err(|_| { body.from.parse().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`.") Error::BadRequest(ErrorKind::InvalidParam, "Invalid `from`.")
})?, })?,
@ -276,7 +276,7 @@ pub async fn get_key_changes_route(
pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>( pub(crate) async fn get_keys_helper<F: Fn(&UserId) -> bool>(
sender_user: Option<&UserId>, sender_user: Option<&UserId>,
device_keys_input: &BTreeMap<Box<UserId>, Vec<Box<DeviceId>>>, device_keys_input: &BTreeMap<OwnedUserId, Vec<OwnedDeviceId>>,
allowed_signatures: F, allowed_signatures: F,
db: &Database, db: &Database,
) -> Result<get_keys::v3::Response> { ) -> Result<get_keys::v3::Response> {
@ -416,7 +416,7 @@ fn add_unsigned_device_display_name(
} }
pub(crate) async fn claim_keys_helper( pub(crate) async fn claim_keys_helper(
one_time_keys_input: &BTreeMap<Box<UserId>, BTreeMap<Box<DeviceId>, DeviceKeyAlgorithm>>, one_time_keys_input: &BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, DeviceKeyAlgorithm>>,
db: &Database, db: &Database,
) -> Result<claim_keys::v3::Response> { ) -> Result<claim_keys::v3::Response> {
let mut one_time_keys = BTreeMap::new(); let mut one_time_keys = BTreeMap::new();

View file

@ -83,7 +83,7 @@ pub async fn get_remote_content(
db.media db.media
.create( .create(
mxc.to_string(), mxc.to_owned(),
&db.globals, &db.globals,
&content_response.content_disposition.as_deref(), &content_response.content_disposition.as_deref(),
&content_response.content_type.as_deref(), &content_response.content_type.as_deref(),

View file

@ -25,7 +25,7 @@ use ruma::{
}, },
serde::{to_canonical_value, Base64, CanonicalJsonObject, CanonicalJsonValue}, serde::{to_canonical_value, Base64, CanonicalJsonObject, CanonicalJsonValue},
state_res::{self, RoomVersion}, state_res::{self, RoomVersion},
uint, EventId, RoomId, RoomVersionId, ServerName, UserId, uint, EventId, OwnedEventId, OwnedRoomId, OwnedServerName, RoomId, RoomVersionId, UserId,
}; };
use serde_json::value::{to_raw_value, RawValue as RawJsonValue}; use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use std::{ use std::{
@ -89,7 +89,7 @@ pub async fn join_room_by_id_or_alias_route(
let sender_user = body.sender_user.as_deref().expect("user is authenticated"); let sender_user = body.sender_user.as_deref().expect("user is authenticated");
let body = body.body; let body = body.body;
let (servers, room_id) = match Box::<RoomId>::try_from(body.room_id_or_alias) { let (servers, room_id) = match OwnedRoomId::try_from(body.room_id_or_alias) {
Ok(room_id) => { Ok(room_id) => {
let mut servers: HashSet<_> = db let mut servers: HashSet<_> = db
.rooms .rooms
@ -179,7 +179,7 @@ pub async fn kick_user_route(
.room_state_get( .room_state_get(
&body.room_id, &body.room_id,
&StateEventType::RoomMember, &StateEventType::RoomMember,
&body.user_id.to_string(), body.user_id.as_str(),
)? )?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::BadState, ErrorKind::BadState,
@ -240,7 +240,7 @@ pub async fn ban_user_route(
.room_state_get( .room_state_get(
&body.room_id, &body.room_id,
&StateEventType::RoomMember, &StateEventType::RoomMember,
&body.user_id.to_string(), body.user_id.as_str(),
)? )?
.map_or( .map_or(
Ok(RoomMemberEventContent { Ok(RoomMemberEventContent {
@ -308,7 +308,7 @@ pub async fn unban_user_route(
.room_state_get( .room_state_get(
&body.room_id, &body.room_id,
&StateEventType::RoomMember, &StateEventType::RoomMember,
&body.user_id.to_string(), body.user_id.as_str(),
)? )?
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::BadState, ErrorKind::BadState,
@ -416,7 +416,7 @@ pub async fn get_member_events_route(
.room_state_full(&body.room_id)? .room_state_full(&body.room_id)?
.iter() .iter()
.filter(|(key, _)| key.0 == StateEventType::RoomMember) .filter(|(key, _)| key.0 == StateEventType::RoomMember)
.map(|(_, pdu)| pdu.to_member_event().into()) .map(|(_, pdu)| pdu.to_member_event().cast())
.collect(), .collect(),
}) })
} }
@ -462,7 +462,7 @@ async fn join_room_by_id_helper(
db: &Database, db: &Database,
sender_user: Option<&UserId>, sender_user: Option<&UserId>,
room_id: &RoomId, room_id: &RoomId,
servers: &HashSet<Box<ServerName>>, servers: &HashSet<OwnedServerName>,
_third_party_signed: Option<&IncomingThirdPartySigned>, _third_party_signed: Option<&IncomingThirdPartySigned>,
) -> Result<join_room_by_id::v3::Response> { ) -> Result<join_room_by_id::v3::Response> {
let sender_user = sender_user.expect("user is authenticated"); let sender_user = sender_user.expect("user is authenticated");
@ -507,7 +507,7 @@ async fn join_room_by_id_helper(
let (make_join_response, remote_server) = make_join_response_and_server?; let (make_join_response, remote_server) = make_join_response_and_server?;
let room_version = match make_join_response.room_version { let room_version = match make_join_response.room_version {
Some(room_version) if db.rooms.is_supported_version(&db, &room_version) => room_version, Some(room_version) if db.rooms.is_supported_version(db, &room_version) => room_version,
_ => return Err(Error::BadServerResponse("Room version is not supported")), _ => return Err(Error::BadServerResponse("Room version is not supported")),
}; };
@ -726,7 +726,7 @@ fn validate_and_add_event_id(
room_version: &RoomVersionId, room_version: &RoomVersionId,
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>, pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
db: &Database, db: &Database,
) -> Result<(Box<EventId>, CanonicalJsonObject)> { ) -> Result<(OwnedEventId, CanonicalJsonObject)> {
let mut value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| { let mut value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| {
error!("Invalid PDU in server response: {:?}: {:?}", pdu, e); error!("Invalid PDU in server response: {:?}: {:?}", pdu, e);
Error::BadServerResponse("Invalid PDU in server response") Error::BadServerResponse("Invalid PDU in server response")
@ -975,8 +975,7 @@ pub(crate) async fn invite_helper<'a>(
let pub_key_map = RwLock::new(BTreeMap::new()); let pub_key_map = RwLock::new(BTreeMap::new());
// We do not add the event_id field to the pdu here because of signature and hashes checks // We do not add the event_id field to the pdu here because of signature and hashes checks
let (event_id, value) = match crate::pdu::gen_event_id_canonical_json(&response.event, &db) let (event_id, value) = match crate::pdu::gen_event_id_canonical_json(&response.event, db) {
{
Ok(t) => t, Ok(t) => t,
Err(_) => { Err(_) => {
// Event could not be converted to canonical json // Event could not be converted to canonical json
@ -991,7 +990,7 @@ pub(crate) async fn invite_helper<'a>(
warn!("Server {} changed invite event, that's not allowed in the spec: ours: {:?}, theirs: {:?}", user_id.server_name(), pdu_json, value); warn!("Server {} changed invite event, that's not allowed in the spec: ours: {:?}, theirs: {:?}", user_id.server_name(), pdu_json, value);
} }
let origin: Box<ServerName> = serde_json::from_value( let origin: OwnedServerName = serde_json::from_value(
serde_json::to_value(value.get("origin").ok_or(Error::BadRequest( serde_json::to_value(value.get("origin").ok_or(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Event needs an origin field.", "Event needs an origin field.",

View file

@ -4,7 +4,7 @@ use ruma::{
error::ErrorKind, error::ErrorKind,
message::{get_message_events, send_message_event}, message::{get_message_events, send_message_event},
}, },
events::{RoomEventType, StateEventType}, events::{MessageLikeEventType, StateEventType},
}; };
use std::{ use std::{
collections::{BTreeMap, HashSet}, collections::{BTreeMap, HashSet},
@ -36,9 +36,7 @@ pub async fn send_message_event_route(
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
// Forbid m.room.encrypted if encryption is disabled // Forbid m.room.encrypted if encryption is disabled
if RoomEventType::RoomEncrypted == body.event_type.to_string().into() if body.event_type == MessageLikeEventType::RoomEncrypted && !db.globals.allow_encryption() {
&& !db.globals.allow_encryption()
{
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::Forbidden, ErrorKind::Forbidden,
"Encryption has been disabled", "Encryption has been disabled",

View file

@ -39,7 +39,7 @@ pub async fn redact_event_route(
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
state_key: None, state_key: None,
redacts: Some(body.event_id.into()), redacts: Some((&*body.event_id).into()),
}, },
sender_user, sender_user,
&body.room_id, &body.room_id,

View file

@ -23,7 +23,7 @@ use ruma::{
}, },
int, int,
serde::{CanonicalJsonObject, JsonObject}, serde::{CanonicalJsonObject, JsonObject},
RoomAliasId, RoomId, OwnedRoomAliasId, RoomAliasId, RoomId,
}; };
use serde_json::{json, value::to_raw_value}; use serde_json::{json, value::to_raw_value};
use std::{cmp::max, collections::BTreeMap, sync::Arc}; use std::{cmp::max, collections::BTreeMap, sync::Arc};
@ -77,7 +77,7 @@ pub async fn create_room_route(
)); ));
} }
let alias: Option<Box<RoomAliasId>> = let alias: Option<OwnedRoomAliasId> =
body.room_alias_name body.room_alias_name
.as_ref() .as_ref()
.map_or(Ok(None), |localpart| { .map_or(Ok(None), |localpart| {

View file

@ -56,8 +56,7 @@ pub async fn login_route(
} else { } else {
return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type.")); return Err(Error::BadRequest(ErrorKind::Forbidden, "Bad login type."));
}; };
let user_id = let user_id = UserId::parse_with_server_name(username, db.globals.server_name())
UserId::parse_with_server_name(username.to_owned(), db.globals.server_name())
.map_err(|_| { .map_err(|_| {
Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.") Error::BadRequest(ErrorKind::InvalidUsername, "Username is invalid.")
})?; })?;

View file

@ -73,7 +73,7 @@ pub async fn send_state_event_for_empty_key_route(
&db, &db,
sender_user, sender_user,
&body.room_id, &body.room_id,
&body.event_type.to_string().into(), &body.event_type,
&body.body.body, &body.body.body,
body.state_key.to_owned(), body.state_key.to_owned(),
) )

View file

@ -10,7 +10,7 @@ use ruma::{
RoomEventType, StateEventType, RoomEventType, StateEventType,
}, },
serde::Raw, serde::Raw,
DeviceId, RoomId, UserId, OwnedDeviceId, OwnedUserId, RoomId, UserId,
}; };
use std::{ use std::{
collections::{hash_map::Entry, BTreeMap, HashMap, HashSet}, collections::{hash_map::Entry, BTreeMap, HashMap, HashSet},
@ -128,8 +128,8 @@ pub async fn sync_events_route(
async fn sync_helper_wrapper( async fn sync_helper_wrapper(
db: Arc<DatabaseGuard>, db: Arc<DatabaseGuard>,
sender_user: Box<UserId>, sender_user: OwnedUserId,
sender_device: Box<DeviceId>, sender_device: OwnedDeviceId,
body: sync_events::v3::IncomingRequest, body: sync_events::v3::IncomingRequest,
tx: Sender<Option<Result<sync_events::v3::Response>>>, tx: Sender<Option<Result<sync_events::v3::Response>>>,
) { ) {
@ -170,8 +170,8 @@ async fn sync_helper_wrapper(
async fn sync_helper( async fn sync_helper(
db: Arc<DatabaseGuard>, db: Arc<DatabaseGuard>,
sender_user: Box<UserId>, sender_user: OwnedUserId,
sender_device: Box<DeviceId>, sender_device: OwnedDeviceId,
body: sync_events::v3::IncomingRequest, body: sync_events::v3::IncomingRequest,
// bool = caching allowed // bool = caching allowed
) -> Result<(sync_events::v3::Response, bool), Error> { ) -> Result<(sync_events::v3::Response, bool), Error> {
@ -222,7 +222,7 @@ async fn sync_helper(
// Look for device list updates of this account // Look for device list updates of this account
device_list_updates.extend( device_list_updates.extend(
db.users db.users
.keys_changed(&sender_user.to_string(), since, None) .keys_changed(sender_user.as_str(), since, None)
.filter_map(|r| r.ok()), .filter_map(|r| r.ok()),
); );
@ -407,7 +407,7 @@ async fn sync_helper(
}; };
// This check is in case a bad user ID made it into the database // This check is in case a bad user ID made it into the database
if let Ok(uid) = UserId::parse(state_key.as_ref()) { if let Ok(uid) = UserId::parse(state_key) {
lazy_loaded.insert(uid); lazy_loaded.insert(uid);
} }
state_events.push(pdu); state_events.push(pdu);
@ -614,7 +614,7 @@ async fn sync_helper(
// Look for device list updates in this room // Look for device list updates in this room
device_list_updates.extend( device_list_updates.extend(
db.users db.users
.keys_changed(&room_id.to_string(), since, None) .keys_changed(room_id.as_str(), since, None)
.filter_map(|r| r.ok()), .filter_map(|r| r.ok()),
); );

View file

@ -61,7 +61,7 @@ pub async fn send_event_to_device_route(
DeviceIdOrAllDevices::DeviceId(target_device_id) => db.users.add_to_device_event( DeviceIdOrAllDevices::DeviceId(target_device_id) => db.users.add_to_device_event(
sender_user, sender_user,
target_user_id, target_user_id,
&target_device_id, target_device_id,
&body.event_type, &body.event_type,
event.deserialize_as().map_err(|_| { event.deserialize_as().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid") Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")

View file

@ -4,7 +4,7 @@ use std::{
net::{IpAddr, Ipv4Addr}, net::{IpAddr, Ipv4Addr},
}; };
use ruma::{RoomVersionId, ServerName}; use ruma::{OwnedServerName, RoomVersionId};
use serde::{de::IgnoredAny, Deserialize}; use serde::{de::IgnoredAny, Deserialize};
use tracing::warn; use tracing::warn;
@ -20,7 +20,7 @@ pub struct Config {
pub port: u16, pub port: u16,
pub tls: Option<TlsConfig>, pub tls: Option<TlsConfig>,
pub server_name: Box<ServerName>, pub server_name: OwnedServerName,
#[serde(default = "default_database_backend")] #[serde(default = "default_database_backend")]
pub database_backend: String, pub database_backend: String,
pub database_path: String, pub database_path: String,
@ -58,7 +58,7 @@ pub struct Config {
pub proxy: ProxyConfig, pub proxy: ProxyConfig,
pub jwt_secret: Option<String>, pub jwt_secret: Option<String>,
#[serde(default = "Vec::new")] #[serde(default = "Vec::new")]
pub trusted_servers: Vec<Box<ServerName>>, pub trusted_servers: Vec<OwnedServerName>,
#[serde(default = "default_log")] #[serde(default = "default_log")]
pub log: String, pub log: String,
#[serde(default)] #[serde(default)]
@ -177,7 +177,7 @@ impl fmt::Display for Config {
("Turn TTL", &self.turn_ttl.to_string()), ("Turn TTL", &self.turn_ttl.to_string()),
("Turn URIs", { ("Turn URIs", {
let mut lst = vec![]; let mut lst = vec![];
for item in self.turn_uris.to_vec().into_iter().enumerate() { for item in self.turn_uris.iter().cloned().enumerate() {
let (_, uri): (usize, String) = item; let (_, uri): (usize, String) = item;
lst.push(uri); lst.push(uri);
} }
@ -185,7 +185,7 @@ impl fmt::Display for Config {
}), }),
]; ];
let mut msg: String = "Active config values:\n\n".to_string(); let mut msg: String = "Active config values:\n\n".to_owned();
for line in lines.into_iter().enumerate() { for line in lines.into_iter().enumerate() {
msg += &format!("{}: {}\n", line.1 .0, line.1 .1); msg += &format!("{}: {}\n", line.1 .0, line.1 .1);

View file

@ -25,7 +25,7 @@ use ruma::{
GlobalAccountDataEvent, GlobalAccountDataEventType, GlobalAccountDataEvent, GlobalAccountDataEventType,
}, },
push::Ruleset, push::Ruleset,
DeviceId, EventId, RoomId, UserId, DeviceId, EventId, OwnedRoomId, RoomId, UserId,
}; };
use std::{ use std::{
collections::{BTreeMap, HashMap, HashSet}, collections::{BTreeMap, HashMap, HashSet},
@ -443,7 +443,7 @@ impl Database {
for (roomid, _) in db.rooms.roomid_shortstatehash.iter() { for (roomid, _) in db.rooms.roomid_shortstatehash.iter() {
let string = utils::string_from_bytes(&roomid).unwrap(); let string = utils::string_from_bytes(&roomid).unwrap();
let room_id = <&RoomId>::try_from(string.as_str()).unwrap(); let room_id = <&RoomId>::try_from(string.as_str()).unwrap();
db.rooms.update_joined_count(room_id, &db)?; db.rooms.update_joined_count(room_id, db)?;
} }
db.globals.bump_database_version(6)?; db.globals.bump_database_version(6)?;
@ -453,7 +453,7 @@ impl Database {
if db.globals.database_version()? < 7 { if db.globals.database_version()? < 7 {
// Upgrade state store // Upgrade state store
let mut last_roomstates: HashMap<Box<RoomId>, u64> = HashMap::new(); let mut last_roomstates: HashMap<OwnedRoomId, u64> = HashMap::new();
let mut current_sstatehash: Option<u64> = None; let mut current_sstatehash: Option<u64> = None;
let mut current_room = None; let mut current_room = None;
let mut current_state = HashSet::new(); let mut current_state = HashSet::new();

View file

@ -30,7 +30,7 @@ use ruma::{
}, },
RoomEventType, RoomEventType,
}, },
EventId, RoomAliasId, RoomId, RoomName, RoomVersionId, ServerName, UserId, EventId, OwnedEventId, OwnedRoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use tokio::sync::{mpsc, MutexGuard, RwLock, RwLockReadGuard}; use tokio::sync::{mpsc, MutexGuard, RwLock, RwLockReadGuard};
@ -147,13 +147,11 @@ fn process_admin_message(db: &Database, room_message: String) -> RoomMessageEven
let command_line = lines.next().expect("each string has at least one line"); let command_line = lines.next().expect("each string has at least one line");
let body: Vec<_> = lines.collect(); let body: Vec<_> = lines.collect();
let admin_command = match parse_admin_command(&command_line) { let admin_command = match parse_admin_command(command_line) {
Ok(command) => command, Ok(command) => command,
Err(error) => { Err(error) => {
let server_name = db.globals.server_name(); let server_name = db.globals.server_name();
let message = error let message = error.replace("server.name", server_name.as_str());
.to_string()
.replace("server.name", server_name.as_str());
let html_message = usage_to_html(&message, server_name); let html_message = usage_to_html(&message, server_name);
return RoomMessageEventContent::text_html(message, html_message); return RoomMessageEventContent::text_html(message, html_message);
@ -193,8 +191,8 @@ fn parse_admin_command(command_line: &str) -> std::result::Result<AdminCommand,
// Backwards compatibility with `register_appservice`-style commands // Backwards compatibility with `register_appservice`-style commands
let command_with_dashes; let command_with_dashes;
if argv.len() > 1 && argv[1].contains("_") { if argv.len() > 1 && argv[1].contains('_') {
command_with_dashes = argv[1].replace("_", "-"); command_with_dashes = argv[1].replace('_', "-");
argv[1] = &command_with_dashes; argv[1] = &command_with_dashes;
} }
@ -236,7 +234,7 @@ enum AdminCommand {
/// Get the auth_chain of a PDU /// Get the auth_chain of a PDU
GetAuthChain { GetAuthChain {
/// An event ID (the $ character followed by the base64 reference hash) /// An event ID (the $ character followed by the base64 reference hash)
event_id: Box<EventId>, event_id: OwnedEventId,
}, },
#[clap(verbatim_doc_comment)] #[clap(verbatim_doc_comment)]
@ -254,7 +252,7 @@ enum AdminCommand {
/// Retrieve and print a PDU by ID from the Conduit database /// Retrieve and print a PDU by ID from the Conduit database
GetPdu { GetPdu {
/// An event ID (a $ followed by the base64 reference hash) /// An event ID (a $ followed by the base64 reference hash)
event_id: Box<EventId>, event_id: OwnedEventId,
}, },
/// Print database memory usage statistics /// Print database memory usage statistics
@ -337,7 +335,7 @@ fn process_admin_command(
Err(e) => RoomMessageEventContent::text_plain(e.to_string()), Err(e) => RoomMessageEventContent::text_plain(e.to_string()),
}, },
AdminCommand::GetAuthChain { event_id } => { AdminCommand::GetAuthChain { event_id } => {
let event_id = Arc::<EventId>::from(event_id); let event_id = Arc::from(&*event_id);
if let Some(event) = db.rooms.get_pdu_json(&event_id)? { if let Some(event) = db.rooms.get_pdu_json(&event_id)? {
let room_id_str = event let room_id_str = event
.get("room_id") .get("room_id")
@ -498,7 +496,7 @@ fn usage_to_html(text: &str, server_name: &ServerName) -> String {
let text = text.replace("subcommand", "command"); let text = text.replace("subcommand", "command");
// Escape option names (e.g. `<element-id>`) since they look like HTML tags // Escape option names (e.g. `<element-id>`) since they look like HTML tags
let text = text.replace("<", "&lt;").replace(">", "&gt;"); let text = text.replace('<', "&lt;").replace('>', "&gt;");
// Italicize the first line (command name and version text) // Italicize the first line (command name and version text)
let re = Regex::new("^(.*?)\n").expect("Regex compilation should not fail"); let re = Regex::new("^(.*?)\n").expect("Regex compilation should not fail");
@ -526,7 +524,7 @@ fn usage_to_html(text: &str, server_name: &ServerName) -> String {
while text_lines while text_lines
.get(line_index) .get(line_index)
.map(|line| line.starts_with("#")) .map(|line| line.starts_with('#'))
.unwrap_or(false) .unwrap_or(false)
{ {
command_body += if text_lines[line_index].starts_with("# ") { command_body += if text_lines[line_index].starts_with("# ") {
@ -557,12 +555,10 @@ fn usage_to_html(text: &str, server_name: &ServerName) -> String {
}; };
// Add HTML line-breaks // Add HTML line-breaks
let text = text
.replace("\n\n\n", "\n\n")
.replace("\n", "<br>\n")
.replace("[nobr]<br>", "");
text text.replace("\n\n\n", "\n\n")
.replace('\n', "<br>\n")
.replace("[nobr]<br>", "")
} }
/// Create the admin room. /// Create the admin room.
@ -606,7 +602,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
@ -631,7 +627,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
@ -653,7 +649,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
@ -669,7 +665,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
@ -687,7 +683,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
@ -703,13 +699,12 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
// 5. Events implied by name and topic // 5. Events implied by name and topic
let room_name = RoomName::parse(format!("{} Admin Room", db.globals.server_name())) let room_name = format!("{} Admin Room", db.globals.server_name());
.expect("Room name is valid");
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomName, event_type: RoomEventType::RoomName,
@ -721,7 +716,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
@ -738,12 +733,12 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
// 6. Room alias // 6. Room alias
let alias: Box<RoomAliasId> = format!("#admins:{}", db.globals.server_name()) let alias: OwnedRoomAliasId = format!("#admins:{}", db.globals.server_name())
.try_into() .try_into()
.expect("#admins:server_name is a valid alias name"); .expect("#admins:server_name is a valid alias name");
@ -761,7 +756,7 @@ pub(crate) async fn create_admin_room(db: &Database) -> Result<()> {
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
@ -778,7 +773,7 @@ pub(crate) async fn make_user_admin(
user_id: &UserId, user_id: &UserId,
displayname: String, displayname: String,
) -> Result<()> { ) -> Result<()> {
let admin_room_alias: Box<RoomAliasId> = format!("#admins:{}", db.globals.server_name()) let admin_room_alias: OwnedRoomAliasId = format!("#admins:{}", db.globals.server_name())
.try_into() .try_into()
.expect("#admins:server_name is a valid alias name"); .expect("#admins:server_name is a valid alias name");
let room_id = db let room_id = db
@ -821,7 +816,7 @@ pub(crate) async fn make_user_admin(
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
db.rooms.build_and_append_pdu( db.rooms.build_and_append_pdu(
@ -842,9 +837,9 @@ pub(crate) async fn make_user_admin(
state_key: Some(user_id.to_string()), state_key: Some(user_id.to_string()),
redacts: None, redacts: None,
}, },
&user_id, user_id,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
@ -867,7 +862,7 @@ pub(crate) async fn make_user_admin(
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;
@ -876,8 +871,8 @@ pub(crate) async fn make_user_admin(
PduBuilder { PduBuilder {
event_type: RoomEventType::RoomMessage, event_type: RoomEventType::RoomMessage,
content: to_raw_value(&RoomMessageEventContent::text_html( content: to_raw_value(&RoomMessageEventContent::text_html(
format!("## Thank you for trying out Conduit!\n\nConduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.\n\nHelpful links:\n> Website: https://conduit.rs\n> Git and Documentation: https://gitlab.com/famedly/conduit\n> Report issues: https://gitlab.com/famedly/conduit/-/issues\n\nFor a list of available commands, send the following message in this room: `@conduit:{}: --help`\n\nHere are some rooms you can join (by typing the command):\n\nConduit room (Ask questions and get notified on updates):\n`/join #conduit:fachschaften.org`\n\nConduit lounge (Off-topic, only Conduit users are allowed to join)\n`/join #conduit-lounge:conduit.rs`", db.globals.server_name()).to_owned(), format!("## Thank you for trying out Conduit!\n\nConduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.\n\nHelpful links:\n> Website: https://conduit.rs\n> Git and Documentation: https://gitlab.com/famedly/conduit\n> Report issues: https://gitlab.com/famedly/conduit/-/issues\n\nFor a list of available commands, send the following message in this room: `@conduit:{}: --help`\n\nHere are some rooms you can join (by typing the command):\n\nConduit room (Ask questions and get notified on updates):\n`/join #conduit:fachschaften.org`\n\nConduit lounge (Off-topic, only Conduit users are allowed to join)\n`/join #conduit-lounge:conduit.rs`", db.globals.server_name()),
format!("<h2>Thank you for trying out Conduit!</h2>\n<p>Conduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.</p>\n<p>Helpful links:</p>\n<blockquote>\n<p>Website: https://conduit.rs<br>Git and Documentation: https://gitlab.com/famedly/conduit<br>Report issues: https://gitlab.com/famedly/conduit/-/issues</p>\n</blockquote>\n<p>For a list of available commands, send the following message in this room: <code>@conduit:{}: --help</code></p>\n<p>Here are some rooms you can join (by typing the command):</p>\n<p>Conduit room (Ask questions and get notified on updates):<br><code>/join #conduit:fachschaften.org</code></p>\n<p>Conduit lounge (Off-topic, only Conduit users are allowed to join)<br><code>/join #conduit-lounge:conduit.rs</code></p>\n", db.globals.server_name()).to_owned(), format!("<h2>Thank you for trying out Conduit!</h2>\n<p>Conduit is currently in Beta. This means you can join and participate in most Matrix rooms, but not all features are supported and you might run into bugs from time to time.</p>\n<p>Helpful links:</p>\n<blockquote>\n<p>Website: https://conduit.rs<br>Git and Documentation: https://gitlab.com/famedly/conduit<br>Report issues: https://gitlab.com/famedly/conduit/-/issues</p>\n</blockquote>\n<p>For a list of available commands, send the following message in this room: <code>@conduit:{}: --help</code></p>\n<p>Here are some rooms you can join (by typing the command):</p>\n<p>Conduit room (Ask questions and get notified on updates):<br><code>/join #conduit:fachschaften.org</code></p>\n<p>Conduit lounge (Off-topic, only Conduit users are allowed to join)<br><code>/join #conduit-lounge:conduit.rs</code></p>\n", db.globals.server_name()),
)) ))
.expect("event is valid, we just created it"), .expect("event is valid, we just created it"),
unsigned: None, unsigned: None,
@ -886,7 +881,7 @@ pub(crate) async fn make_user_admin(
}, },
&conduit_user, &conduit_user,
&room_id, &room_id,
&db, db,
&state_lock, &state_lock,
)?; )?;

View file

@ -4,8 +4,8 @@ use ruma::{
client::sync::sync_events, client::sync::sync_events,
federation::discovery::{ServerSigningKeys, VerifyKey}, federation::discovery::{ServerSigningKeys, VerifyKey},
}, },
DeviceId, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, ServerName, MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedEventId, OwnedRoomId, OwnedServerName,
ServerSigningKeyId, UserId, OwnedServerSigningKeyId, OwnedUserId, RoomVersionId, ServerName,
}; };
use std::{ use std::{
collections::{BTreeMap, HashMap}, collections::{BTreeMap, HashMap},
@ -24,7 +24,7 @@ use super::abstraction::Tree;
pub const COUNTER: &[u8] = b"c"; pub const COUNTER: &[u8] = b"c";
type WellKnownMap = HashMap<Box<ServerName>, (FedDest, String)>; type WellKnownMap = HashMap<OwnedServerName, (FedDest, String)>;
type TlsNameMap = HashMap<String, (Vec<IpAddr>, u16)>; type TlsNameMap = HashMap<String, (Vec<IpAddr>, u16)>;
type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries
type SyncHandle = ( type SyncHandle = (
@ -45,13 +45,13 @@ pub struct Globals {
pub stable_room_versions: Vec<RoomVersionId>, pub stable_room_versions: Vec<RoomVersionId>,
pub unstable_room_versions: Vec<RoomVersionId>, pub unstable_room_versions: Vec<RoomVersionId>,
pub(super) server_signingkeys: Arc<dyn Tree>, pub(super) server_signingkeys: Arc<dyn Tree>,
pub bad_event_ratelimiter: Arc<RwLock<HashMap<Box<EventId>, RateLimitState>>>, pub bad_event_ratelimiter: Arc<RwLock<HashMap<OwnedEventId, RateLimitState>>>,
pub bad_signature_ratelimiter: Arc<RwLock<HashMap<Vec<String>, RateLimitState>>>, pub bad_signature_ratelimiter: Arc<RwLock<HashMap<Vec<String>, RateLimitState>>>,
pub servername_ratelimiter: Arc<RwLock<HashMap<Box<ServerName>, Arc<Semaphore>>>>, pub servername_ratelimiter: Arc<RwLock<HashMap<OwnedServerName, Arc<Semaphore>>>>,
pub sync_receivers: RwLock<HashMap<(Box<UserId>, Box<DeviceId>), SyncHandle>>, pub sync_receivers: RwLock<HashMap<(OwnedUserId, OwnedDeviceId), SyncHandle>>,
pub roomid_mutex_insert: RwLock<HashMap<Box<RoomId>, Arc<Mutex<()>>>>, pub roomid_mutex_insert: RwLock<HashMap<OwnedRoomId, Arc<Mutex<()>>>>,
pub roomid_mutex_state: RwLock<HashMap<Box<RoomId>, Arc<TokioMutex<()>>>>, pub roomid_mutex_state: RwLock<HashMap<OwnedRoomId, Arc<TokioMutex<()>>>>,
pub roomid_mutex_federation: RwLock<HashMap<Box<RoomId>, Arc<TokioMutex<()>>>>, // this lock will be held longer pub roomid_mutex_federation: RwLock<HashMap<OwnedRoomId, Arc<TokioMutex<()>>>>, // this lock will be held longer
pub rotate: RotationHandler, pub rotate: RotationHandler,
} }
@ -263,7 +263,7 @@ impl Globals {
self.config.default_room_version.clone() self.config.default_room_version.clone()
} }
pub fn trusted_servers(&self) -> &[Box<ServerName>] { pub fn trusted_servers(&self) -> &[OwnedServerName] {
&self.config.trusted_servers &self.config.trusted_servers
} }
@ -316,7 +316,7 @@ impl Globals {
&self, &self,
origin: &ServerName, origin: &ServerName,
new_keys: ServerSigningKeys, new_keys: ServerSigningKeys,
) -> Result<BTreeMap<Box<ServerSigningKeyId>, VerifyKey>> { ) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
// Not atomic, but this is not critical // Not atomic, but this is not critical
let signingkeys = self.server_signingkeys.get(origin.as_bytes())?; let signingkeys = self.server_signingkeys.get(origin.as_bytes())?;
@ -355,7 +355,7 @@ impl Globals {
pub fn signing_keys_for( pub fn signing_keys_for(
&self, &self,
origin: &ServerName, origin: &ServerName,
) -> Result<BTreeMap<Box<ServerSigningKeyId>, VerifyKey>> { ) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
let signingkeys = self let signingkeys = self
.server_signingkeys .server_signingkeys
.get(origin.as_bytes())? .get(origin.as_bytes())?

View file

@ -5,7 +5,7 @@ use ruma::{
error::ErrorKind, error::ErrorKind,
}, },
serde::Raw, serde::Raw,
RoomId, UserId, OwnedRoomId, RoomId, UserId,
}; };
use std::{collections::BTreeMap, sync::Arc}; use std::{collections::BTreeMap, sync::Arc};
@ -211,13 +211,13 @@ impl KeyBackups {
&self, &self,
user_id: &UserId, user_id: &UserId,
version: &str, version: &str,
) -> Result<BTreeMap<Box<RoomId>, RoomKeyBackup>> { ) -> Result<BTreeMap<OwnedRoomId, RoomKeyBackup>> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
prefix.extend_from_slice(version.as_bytes()); prefix.extend_from_slice(version.as_bytes());
prefix.push(0xff); prefix.push(0xff);
let mut rooms = BTreeMap::<Box<RoomId>, RoomKeyBackup>::new(); let mut rooms = BTreeMap::<OwnedRoomId, RoomKeyBackup>::new();
for result in self for result in self
.backupkeyid_backup .backupkeyid_backup

View file

@ -234,6 +234,7 @@ pub fn get_actions<'a>(
db: &Database, db: &Database,
) -> Result<&'a [Action]> { ) -> Result<&'a [Action]> {
let ctx = PushConditionRoomCtx { let ctx = PushConditionRoomCtx {
user_id: user.to_owned(),
room_id: room_id.to_owned(), room_id: room_id.to_owned(),
member_count: 10_u32.into(), // TODO: get member count efficiently member_count: 10_u32.into(), // TODO: get member count efficiently
user_display_name: db user_display_name: db
@ -274,10 +275,7 @@ async fn send_notice(
}; };
let mut device = Device::new(pusher.app_id.clone(), pusher.pushkey.clone()); let mut device = Device::new(pusher.app_id.clone(), pusher.pushkey.clone());
let mut data_minus_url = pusher.data.clone(); device.data = pusher.data.clone().into();
// The url must be stripped off according to spec
data_minus_url.url = None;
device.data = data_minus_url;
// Tweaks are only added if the format is NOT event_id_only // Tweaks are only added if the format is NOT event_id_only
if !event_id_only { if !event_id_only {

View file

@ -27,7 +27,8 @@ use ruma::{
push::{Action, Ruleset, Tweak}, push::{Action, Ruleset, Tweak},
serde::{CanonicalJsonObject, CanonicalJsonValue, Raw}, serde::{CanonicalJsonObject, CanonicalJsonValue, Raw},
state_res::{self, RoomVersion, StateMap}, state_res::{self, RoomVersion, StateMap},
uint, DeviceId, EventId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId, uint, DeviceId, EventId, OwnedDeviceId, OwnedEventId, OwnedRoomAliasId, OwnedRoomId,
OwnedServerName, OwnedUserId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
}; };
use serde::Deserialize; use serde::Deserialize;
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
@ -108,16 +109,16 @@ pub struct Rooms {
/// RoomId + EventId -> Parent PDU EventId. /// RoomId + EventId -> Parent PDU EventId.
pub(super) referencedevents: Arc<dyn Tree>, pub(super) referencedevents: Arc<dyn Tree>,
pub(super) pdu_cache: Mutex<LruCache<Box<EventId>, Arc<PduEvent>>>, pub(super) pdu_cache: Mutex<LruCache<OwnedEventId, Arc<PduEvent>>>,
pub(super) shorteventid_cache: Mutex<LruCache<u64, Arc<EventId>>>, pub(super) shorteventid_cache: Mutex<LruCache<u64, Arc<EventId>>>,
pub(super) auth_chain_cache: Mutex<LruCache<Vec<u64>, Arc<HashSet<u64>>>>, pub(super) auth_chain_cache: Mutex<LruCache<Vec<u64>, Arc<HashSet<u64>>>>,
pub(super) eventidshort_cache: Mutex<LruCache<Box<EventId>, u64>>, pub(super) eventidshort_cache: Mutex<LruCache<OwnedEventId, u64>>,
pub(super) statekeyshort_cache: Mutex<LruCache<(StateEventType, String), u64>>, pub(super) statekeyshort_cache: Mutex<LruCache<(StateEventType, String), u64>>,
pub(super) shortstatekey_cache: Mutex<LruCache<u64, (StateEventType, String)>>, pub(super) shortstatekey_cache: Mutex<LruCache<u64, (StateEventType, String)>>,
pub(super) our_real_users_cache: RwLock<HashMap<Box<RoomId>, Arc<HashSet<Box<UserId>>>>>, pub(super) our_real_users_cache: RwLock<HashMap<OwnedRoomId, Arc<HashSet<OwnedUserId>>>>,
pub(super) appservice_in_room_cache: RwLock<HashMap<Box<RoomId>, HashMap<String, bool>>>, pub(super) appservice_in_room_cache: RwLock<HashMap<OwnedRoomId, HashMap<String, bool>>>,
pub(super) lazy_load_waiting: pub(super) lazy_load_waiting:
Mutex<HashMap<(Box<UserId>, Box<DeviceId>, Box<RoomId>, u64), HashSet<Box<UserId>>>>, Mutex<HashMap<(OwnedUserId, OwnedDeviceId, OwnedRoomId, u64), HashSet<OwnedUserId>>>,
pub(super) stateinfo_cache: Mutex< pub(super) stateinfo_cache: Mutex<
LruCache< LruCache<
u64, u64,
@ -129,7 +130,7 @@ pub struct Rooms {
)>, )>,
>, >,
>, >,
pub(super) lasttimelinecount_cache: Mutex<HashMap<Box<RoomId>, u64>>, pub(super) lasttimelinecount_cache: Mutex<HashMap<OwnedRoomId, u64>>,
} }
impl Rooms { impl Rooms {
@ -279,7 +280,7 @@ impl Rooms {
let mut sauthevents = auth_events let mut sauthevents = auth_events
.into_iter() .into_iter()
.filter_map(|(event_type, state_key)| { .filter_map(|(event_type, state_key)| {
self.get_shortstatekey(&event_type.to_string().into(), &state_key) self.get_shortstatekey(&event_type, &state_key)
.ok() .ok()
.flatten() .flatten()
.map(|s| (s, (event_type, state_key))) .map(|s| (s, (event_type, state_key)))
@ -1529,7 +1530,7 @@ impl Rooms {
{ {
hash_map::Entry::Vacant(v) => { hash_map::Entry::Vacant(v) => {
if let Some(last_count) = self if let Some(last_count) = self
.pdus_until(&sender_user, &room_id, u64::MAX)? .pdus_until(sender_user, room_id, u64::MAX)?
.filter_map(|r| { .filter_map(|r| {
// Filter out buggy events // Filter out buggy events
if r.is_err() { if r.is_err() {
@ -1992,7 +1993,7 @@ impl Rooms {
// where events in the current room state do not exist // where events in the current room state do not exist
self.set_room_state(room_id, statehashid)?; self.set_room_state(room_id, statehashid)?;
let mut servers: HashSet<Box<ServerName>> = let mut servers: HashSet<OwnedServerName> =
self.room_servers(room_id).filter_map(|r| r.ok()).collect(); self.room_servers(room_id).filter_map(|r| r.ok()).collect();
// In case we are kicking or banning a user, we need to inform their server of the change // In case we are kicking or banning a user, we need to inform their server of the change
@ -2002,7 +2003,7 @@ impl Rooms {
.as_ref() .as_ref()
.and_then(|state_key| UserId::parse(state_key.as_str()).ok()) .and_then(|state_key| UserId::parse(state_key.as_str()).ok())
{ {
servers.insert(Box::from(state_key_uid.server_name())); servers.insert(state_key_uid.server_name().to_owned());
} }
} }
@ -2498,7 +2499,7 @@ impl Rooms {
&self, &self,
room_id: &RoomId, room_id: &RoomId,
db: &Database, db: &Database,
) -> Result<Arc<HashSet<Box<UserId>>>> { ) -> Result<Arc<HashSet<OwnedUserId>>> {
let maybe = self let maybe = self
.our_real_users_cache .our_real_users_cache
.read() .read()
@ -2694,7 +2695,7 @@ impl Rooms {
let (make_leave_response, remote_server) = make_leave_response_and_server?; let (make_leave_response, remote_server) = make_leave_response_and_server?;
let room_version_id = match make_leave_response.room_version { let room_version_id = match make_leave_response.room_version {
Some(version) if self.is_supported_version(&db, &version) => version, Some(version) if self.is_supported_version(db, &version) => version,
_ => return Err(Error::BadServerResponse("Room version is not supported")), _ => return Err(Error::BadServerResponse("Room version is not supported")),
}; };
@ -2814,7 +2815,7 @@ impl Rooms {
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn id_from_alias(&self, alias: &RoomAliasId) -> Result<Option<Box<RoomId>>> { pub fn id_from_alias(&self, alias: &RoomAliasId) -> Result<Option<OwnedRoomId>> {
self.alias_roomid self.alias_roomid
.get(alias.alias().as_bytes())? .get(alias.alias().as_bytes())?
.map(|bytes| { .map(|bytes| {
@ -2830,7 +2831,7 @@ impl Rooms {
pub fn room_aliases<'a>( pub fn room_aliases<'a>(
&'a self, &'a self,
room_id: &RoomId, room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<RoomAliasId>>> + 'a { ) -> impl Iterator<Item = Result<OwnedRoomAliasId>> + 'a {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
@ -2859,7 +2860,7 @@ impl Rooms {
} }
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn public_rooms(&self) -> impl Iterator<Item = Result<Box<RoomId>>> + '_ { pub fn public_rooms(&self) -> impl Iterator<Item = Result<OwnedRoomId>> + '_ {
self.publicroomids.iter().map(|(bytes, _)| { self.publicroomids.iter().map(|(bytes, _)| {
RoomId::parse( RoomId::parse(
utils::string_from_bytes(&bytes).map_err(|_| { utils::string_from_bytes(&bytes).map_err(|_| {
@ -2922,8 +2923,8 @@ impl Rooms {
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn get_shared_rooms<'a>( pub fn get_shared_rooms<'a>(
&'a self, &'a self,
users: Vec<Box<UserId>>, users: Vec<OwnedUserId>,
) -> Result<impl Iterator<Item = Result<Box<RoomId>>> + 'a> { ) -> Result<impl Iterator<Item = Result<OwnedRoomId>> + 'a> {
let iterators = users.into_iter().map(move |user_id| { let iterators = users.into_iter().map(move |user_id| {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
@ -2962,7 +2963,7 @@ impl Rooms {
pub fn room_servers<'a>( pub fn room_servers<'a>(
&'a self, &'a self,
room_id: &RoomId, room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<ServerName>>> + 'a { ) -> impl Iterator<Item = Result<OwnedServerName>> + 'a {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
@ -2995,7 +2996,7 @@ impl Rooms {
pub fn server_rooms<'a>( pub fn server_rooms<'a>(
&'a self, &'a self,
server: &ServerName, server: &ServerName,
) -> impl Iterator<Item = Result<Box<RoomId>>> + 'a { ) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
let mut prefix = server.as_bytes().to_vec(); let mut prefix = server.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
@ -3017,7 +3018,7 @@ impl Rooms {
pub fn room_members<'a>( pub fn room_members<'a>(
&'a self, &'a self,
room_id: &RoomId, room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<UserId>>> + 'a { ) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
@ -3063,7 +3064,7 @@ impl Rooms {
pub fn room_useroncejoined<'a>( pub fn room_useroncejoined<'a>(
&'a self, &'a self,
room_id: &RoomId, room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<UserId>>> + 'a { ) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
@ -3089,7 +3090,7 @@ impl Rooms {
pub fn room_members_invited<'a>( pub fn room_members_invited<'a>(
&'a self, &'a self,
room_id: &RoomId, room_id: &RoomId,
) -> impl Iterator<Item = Result<Box<UserId>>> + 'a { ) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
@ -3145,7 +3146,7 @@ impl Rooms {
pub fn rooms_joined<'a>( pub fn rooms_joined<'a>(
&'a self, &'a self,
user_id: &UserId, user_id: &UserId,
) -> impl Iterator<Item = Result<Box<RoomId>>> + 'a { ) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
self.userroomid_joined self.userroomid_joined
.scan_prefix(user_id.as_bytes().to_vec()) .scan_prefix(user_id.as_bytes().to_vec())
.map(|(key, _)| { .map(|(key, _)| {
@ -3168,7 +3169,7 @@ impl Rooms {
pub fn rooms_invited<'a>( pub fn rooms_invited<'a>(
&'a self, &'a self,
user_id: &UserId, user_id: &UserId,
) -> impl Iterator<Item = Result<(Box<RoomId>, Vec<Raw<AnyStrippedStateEvent>>)>> + 'a { ) -> impl Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnyStrippedStateEvent>>)>> + 'a {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
@ -3241,7 +3242,7 @@ impl Rooms {
pub fn rooms_left<'a>( pub fn rooms_left<'a>(
&'a self, &'a self,
user_id: &UserId, user_id: &UserId,
) -> impl Iterator<Item = Result<(Box<RoomId>, Vec<Raw<AnySyncStateEvent>>)>> + 'a { ) -> impl Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnySyncStateEvent>>)>> + 'a {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
@ -3385,7 +3386,7 @@ impl Rooms {
user_id: &UserId, user_id: &UserId,
device_id: &DeviceId, device_id: &DeviceId,
room_id: &RoomId, room_id: &RoomId,
lazy_load: HashSet<Box<UserId>>, lazy_load: HashSet<OwnedUserId>,
count: u64, count: u64,
) { ) {
self.lazy_load_waiting.lock().unwrap().insert( self.lazy_load_waiting.lock().unwrap().insert(
@ -3467,7 +3468,7 @@ impl Rooms {
.transpose()?; .transpose()?;
let room_version = create_event_content let room_version = create_event_content
.map(|create_event| create_event.room_version) .map(|create_event| create_event.room_version)
.ok_or_else(|| Error::BadDatabase("Invalid room version"))?; .ok_or(Error::BadDatabase("Invalid room version"))?;
Ok(room_version) Ok(room_version)
} }
} }

View file

@ -8,7 +8,7 @@ use ruma::{
presence::PresenceState, presence::PresenceState,
serde::Raw, serde::Raw,
signatures::CanonicalJsonObject, signatures::CanonicalJsonObject,
RoomId, UInt, UserId, OwnedUserId, RoomId, UInt, UserId,
}; };
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
@ -78,7 +78,7 @@ impl RoomEdus {
since: u64, since: u64,
) -> impl Iterator< ) -> impl Iterator<
Item = Result<( Item = Result<(
Box<UserId>, OwnedUserId,
u64, u64,
Raw<ruma::events::AnySyncEphemeralRoomEvent>, Raw<ruma::events::AnySyncEphemeralRoomEvent>,
)>, )>,
@ -450,7 +450,7 @@ impl RoomEdus {
{ {
// Send new presence events to set the user offline // Send new presence events to set the user offline
let count = globals.next_count()?.to_be_bytes(); let count = globals.next_count()?.to_be_bytes();
let user_id: Box<_> = utils::string_from_bytes(&user_id_bytes) let user_id: OwnedUserId = utils::string_from_bytes(&user_id_bytes)
.map_err(|_| { .map_err(|_| {
Error::bad_database("Invalid UserId bytes in userid_lastpresenceupdate.") Error::bad_database("Invalid UserId bytes in userid_lastpresenceupdate.")
})? })?
@ -499,7 +499,7 @@ impl RoomEdus {
since: u64, since: u64,
_rooms: &super::Rooms, _rooms: &super::Rooms,
_globals: &super::super::globals::Globals, _globals: &super::super::globals::Globals,
) -> Result<HashMap<Box<UserId>, PresenceEvent>> { ) -> Result<HashMap<OwnedUserId, PresenceEvent>> {
//self.presence_maintain(rooms, globals)?; //self.presence_maintain(rooms, globals)?;
let mut prefix = room_id.as_bytes().to_vec(); let mut prefix = room_id.as_bytes().to_vec();

View file

@ -26,7 +26,7 @@ use ruma::{
events::{push_rules::PushRulesEvent, AnySyncEphemeralRoomEvent, GlobalAccountDataEventType}, events::{push_rules::PushRulesEvent, AnySyncEphemeralRoomEvent, GlobalAccountDataEventType},
push, push,
receipt::ReceiptType, receipt::ReceiptType,
uint, MilliSecondsSinceUnixEpoch, ServerName, UInt, UserId, uint, MilliSecondsSinceUnixEpoch, OwnedServerName, ServerName, UInt, UserId,
}; };
use tokio::{ use tokio::{
select, select,
@ -40,7 +40,7 @@ use super::abstraction::Tree;
pub enum OutgoingKind { pub enum OutgoingKind {
Appservice(String), Appservice(String),
Push(Vec<u8>, Vec<u8>), // user and pushkey Push(Vec<u8>, Vec<u8>), // user and pushkey
Normal(Box<ServerName>), Normal(OwnedServerName),
} }
impl OutgoingKind { impl OutgoingKind {
@ -323,7 +323,7 @@ impl Sending {
// Look for device list updates in this room // Look for device list updates in this room
device_list_changes.extend( device_list_changes.extend(
db.users db.users
.keys_changed(&room_id.to_string(), since, None) .keys_changed(room_id.as_str(), since, None)
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.filter(|user_id| user_id.server_name() == db.globals.server_name()), .filter(|user_id| user_id.server_name() == db.globals.server_name()),
); );
@ -420,7 +420,7 @@ impl Sending {
} }
#[tracing::instrument(skip(self, servers, pdu_id))] #[tracing::instrument(skip(self, servers, pdu_id))]
pub fn send_pdu<I: Iterator<Item = Box<ServerName>>>( pub fn send_pdu<I: Iterator<Item = OwnedServerName>>(
&self, &self,
servers: I, servers: I,
pdu_id: &[u8], pdu_id: &[u8],
@ -535,7 +535,7 @@ impl Sending {
let response = appservice_server::send_request( let response = appservice_server::send_request(
&db.globals, &db.globals,
db.appservice db.appservice
.get_registration(&id) .get_registration(id)
.map_err(|e| (kind.clone(), e))? .map_err(|e| (kind.clone(), e))?
.ok_or_else(|| { .ok_or_else(|| {
( (

View file

@ -13,7 +13,7 @@ use ruma::{
}, },
}, },
signatures::CanonicalJsonValue, signatures::CanonicalJsonValue,
DeviceId, UserId, DeviceId, OwnedDeviceId, OwnedUserId, UserId,
}; };
use tracing::error; use tracing::error;
@ -22,7 +22,7 @@ use super::abstraction::Tree;
pub struct Uiaa { pub struct Uiaa {
pub(super) userdevicesessionid_uiaainfo: Arc<dyn Tree>, // User-interactive authentication pub(super) userdevicesessionid_uiaainfo: Arc<dyn Tree>, // User-interactive authentication
pub(super) userdevicesessionid_uiaarequest: pub(super) userdevicesessionid_uiaarequest:
RwLock<BTreeMap<(Box<UserId>, Box<DeviceId>, String), CanonicalJsonValue>>, RwLock<BTreeMap<(OwnedUserId, OwnedDeviceId, String), CanonicalJsonValue>>,
} }
impl Uiaa { impl Uiaa {

View file

@ -4,8 +4,8 @@ use ruma::{
encryption::{CrossSigningKey, DeviceKeys, OneTimeKey}, encryption::{CrossSigningKey, DeviceKeys, OneTimeKey},
events::{AnyToDeviceEvent, StateEventType}, events::{AnyToDeviceEvent, StateEventType},
serde::Raw, serde::Raw,
DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, MxcUri, RoomAliasId, DeviceId, DeviceKeyAlgorithm, DeviceKeyId, MilliSecondsSinceUnixEpoch, OwnedDeviceId,
UInt, UserId, OwnedDeviceKeyId, OwnedMxcUri, OwnedUserId, RoomAliasId, UInt, UserId,
}; };
use std::{collections::BTreeMap, mem, sync::Arc}; use std::{collections::BTreeMap, mem, sync::Arc};
use tracing::warn; use tracing::warn;
@ -85,7 +85,7 @@ impl Users {
/// Find out which user an access token belongs to. /// Find out which user an access token belongs to.
#[tracing::instrument(skip(self, token))] #[tracing::instrument(skip(self, token))]
pub fn find_from_token(&self, token: &str) -> Result<Option<(Box<UserId>, String)>> { pub fn find_from_token(&self, token: &str) -> Result<Option<(OwnedUserId, String)>> {
self.token_userdeviceid self.token_userdeviceid
.get(token.as_bytes())? .get(token.as_bytes())?
.map_or(Ok(None), |bytes| { .map_or(Ok(None), |bytes| {
@ -113,7 +113,7 @@ impl Users {
/// Returns an iterator over all users on this homeserver. /// Returns an iterator over all users on this homeserver.
#[tracing::instrument(skip(self))] #[tracing::instrument(skip(self))]
pub fn iter(&self) -> impl Iterator<Item = Result<Box<UserId>>> + '_ { pub fn iter(&self) -> impl Iterator<Item = Result<OwnedUserId>> + '_ {
self.userid_password.iter().map(|(bytes, _)| { self.userid_password.iter().map(|(bytes, _)| {
UserId::parse(utils::string_from_bytes(&bytes).map_err(|_| { UserId::parse(utils::string_from_bytes(&bytes).map_err(|_| {
Error::bad_database("User ID in userid_password is invalid unicode.") Error::bad_database("User ID in userid_password is invalid unicode.")
@ -217,7 +217,7 @@ impl Users {
/// Get the avatar_url of a user. /// Get the avatar_url of a user.
#[tracing::instrument(skip(self, user_id))] #[tracing::instrument(skip(self, user_id))]
pub fn avatar_url(&self, user_id: &UserId) -> Result<Option<Box<MxcUri>>> { pub fn avatar_url(&self, user_id: &UserId) -> Result<Option<OwnedMxcUri>> {
self.userid_avatarurl self.userid_avatarurl
.get(user_id.as_bytes())? .get(user_id.as_bytes())?
.map(|bytes| { .map(|bytes| {
@ -231,7 +231,7 @@ impl Users {
/// Sets a new avatar_url or removes it if avatar_url is None. /// Sets a new avatar_url or removes it if avatar_url is None.
#[tracing::instrument(skip(self, user_id, avatar_url))] #[tracing::instrument(skip(self, user_id, avatar_url))]
pub fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<Box<MxcUri>>) -> Result<()> { pub fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<OwnedMxcUri>) -> Result<()> {
if let Some(avatar_url) = avatar_url { if let Some(avatar_url) = avatar_url {
self.userid_avatarurl self.userid_avatarurl
.insert(user_id.as_bytes(), avatar_url.to_string().as_bytes())?; .insert(user_id.as_bytes(), avatar_url.to_string().as_bytes())?;
@ -340,7 +340,7 @@ impl Users {
pub fn all_device_ids<'a>( pub fn all_device_ids<'a>(
&'a self, &'a self,
user_id: &UserId, user_id: &UserId,
) -> impl Iterator<Item = Result<Box<DeviceId>>> + 'a { ) -> impl Iterator<Item = Result<OwnedDeviceId>> + 'a {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
// All devices have metadata // All devices have metadata
@ -446,7 +446,7 @@ impl Users {
device_id: &DeviceId, device_id: &DeviceId,
key_algorithm: &DeviceKeyAlgorithm, key_algorithm: &DeviceKeyAlgorithm,
globals: &super::globals::Globals, globals: &super::globals::Globals,
) -> Result<Option<(Box<DeviceKeyId>, Raw<OneTimeKey>)>> { ) -> Result<Option<(OwnedDeviceKeyId, Raw<OneTimeKey>)>> {
let mut prefix = user_id.as_bytes().to_vec(); let mut prefix = user_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);
prefix.extend_from_slice(device_id.as_bytes()); prefix.extend_from_slice(device_id.as_bytes());
@ -496,7 +496,7 @@ impl Users {
.scan_prefix(userdeviceid) .scan_prefix(userdeviceid)
.map(|(bytes, _)| { .map(|(bytes, _)| {
Ok::<_, Error>( Ok::<_, Error>(
serde_json::from_slice::<Box<DeviceKeyId>>( serde_json::from_slice::<OwnedDeviceKeyId>(
&*bytes.rsplit(|&b| b == 0xff).next().ok_or_else(|| { &*bytes.rsplit(|&b| b == 0xff).next().ok_or_else(|| {
Error::bad_database("OneTimeKey ID in db is invalid.") Error::bad_database("OneTimeKey ID in db is invalid.")
})?, })?,
@ -684,7 +684,7 @@ impl Users {
.ok_or_else(|| Error::bad_database("key in keyid_key has no signatures field."))? .ok_or_else(|| Error::bad_database("key in keyid_key has no signatures field."))?
.as_object_mut() .as_object_mut()
.ok_or_else(|| Error::bad_database("key in keyid_key has invalid signatures field."))? .ok_or_else(|| Error::bad_database("key in keyid_key has invalid signatures field."))?
.entry(sender_id.to_owned()) .entry(sender_id.to_string())
.or_insert_with(|| serde_json::Map::new().into()); .or_insert_with(|| serde_json::Map::new().into());
signatures signatures
@ -709,7 +709,7 @@ impl Users {
user_or_room_id: &str, user_or_room_id: &str,
from: u64, from: u64,
to: Option<u64>, to: Option<u64>,
) -> impl Iterator<Item = Result<Box<UserId>>> + 'a { ) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
let mut prefix = user_or_room_id.as_bytes().to_vec(); let mut prefix = user_or_room_id.as_bytes().to_vec();
prefix.push(0xff); prefix.push(0xff);

View file

@ -6,7 +6,7 @@ use ruma::{
error::{Error as RumaError, ErrorKind}, error::{Error as RumaError, ErrorKind},
uiaa::{UiaaInfo, UiaaResponse}, uiaa::{UiaaInfo, UiaaResponse},
}, },
ServerName, OwnedServerName,
}; };
use thiserror::Error; use thiserror::Error;
use tracing::{error, warn}; use tracing::{error, warn};
@ -55,7 +55,7 @@ pub enum Error {
source: reqwest::Error, source: reqwest::Error,
}, },
#[error("{0}")] #[error("{0}")]
FederationError(Box<ServerName>, RumaError), FederationError(OwnedServerName, RumaError),
#[error("Could not do this io: {source}")] #[error("Could not do this io: {source}")]
IoError { IoError {
#[from] #[from]

View file

@ -5,7 +5,8 @@ use ruma::{
AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, RoomEventType, StateEvent, AnyStrippedStateEvent, AnySyncRoomEvent, AnySyncStateEvent, RoomEventType, StateEvent,
}, },
serde::{CanonicalJsonObject, CanonicalJsonValue, Raw}, serde::{CanonicalJsonObject, CanonicalJsonValue, Raw},
state_res, EventId, MilliSecondsSinceUnixEpoch, RoomId, UInt, UserId, state_res, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId, RoomId,
UInt, UserId,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::{ use serde_json::{
@ -25,8 +26,8 @@ pub struct EventHash {
#[derive(Clone, Deserialize, Serialize, Debug)] #[derive(Clone, Deserialize, Serialize, Debug)]
pub struct PduEvent { pub struct PduEvent {
pub event_id: Arc<EventId>, pub event_id: Arc<EventId>,
pub room_id: Box<RoomId>, pub room_id: OwnedRoomId,
pub sender: Box<UserId>, pub sender: OwnedUserId,
pub origin_server_ts: UInt, pub origin_server_ts: UInt,
#[serde(rename = "type")] #[serde(rename = "type")]
pub kind: RoomEventType, pub kind: RoomEventType,
@ -42,7 +43,7 @@ pub struct PduEvent {
pub unsigned: Option<Box<RawJsonValue>>, pub unsigned: Option<Box<RawJsonValue>>,
pub hashes: EventHash, pub hashes: EventHash,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub signatures: Option<Box<RawJsonValue>>, // BTreeMap<Box<ServerName>, BTreeMap<ServerSigningKeyId, String>> pub signatures: Option<Box<RawJsonValue>>, // BTreeMap<OwnedServerName, BTreeMap<ServerSigningKeyId, String>>
} }
impl PduEvent { impl PduEvent {
@ -333,7 +334,7 @@ impl Ord for PduEvent {
pub(crate) fn gen_event_id_canonical_json( pub(crate) fn gen_event_id_canonical_json(
pdu: &RawJsonValue, pdu: &RawJsonValue,
db: &Database, db: &Database,
) -> crate::Result<(Box<EventId>, CanonicalJsonObject)> { ) -> crate::Result<(OwnedEventId, CanonicalJsonObject)> {
let value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| { let value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| {
warn!("Error parsing incoming event {:?}: {:?}", pdu, e); warn!("Error parsing incoming event {:?}: {:?}", pdu, e);
Error::BadServerResponse("Invalid PDU in server response") Error::BadServerResponse("Invalid PDU in server response")

View file

@ -1,6 +1,7 @@
use crate::Error; use crate::Error;
use ruma::{ use ruma::{
api::client::uiaa::UiaaResponse, signatures::CanonicalJsonValue, DeviceId, ServerName, UserId, api::client::uiaa::UiaaResponse, signatures::CanonicalJsonValue, OwnedDeviceId,
OwnedServerName, OwnedUserId,
}; };
use std::ops::Deref; use std::ops::Deref;
@ -10,9 +11,9 @@ mod axum;
/// Extractor for Ruma request structs /// Extractor for Ruma request structs
pub struct Ruma<T> { pub struct Ruma<T> {
pub body: T, pub body: T,
pub sender_user: Option<Box<UserId>>, pub sender_user: Option<OwnedUserId>,
pub sender_device: Option<Box<DeviceId>>, pub sender_device: Option<OwnedDeviceId>,
pub sender_servername: Option<Box<ServerName>>, pub sender_servername: Option<OwnedServerName>,
// This is None when body is not a valid string // This is None when body is not a valid string
pub json_body: Option<CanonicalJsonValue>, pub json_body: Option<CanonicalJsonValue>,
pub from_appservice: bool, pub from_appservice: bool,

View file

@ -18,7 +18,7 @@ use http::StatusCode;
use ruma::{ use ruma::{
api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse}, api::{client::error::ErrorKind, AuthScheme, IncomingRequest, OutgoingResponse},
signatures::CanonicalJsonValue, signatures::CanonicalJsonValue,
DeviceId, ServerName, UserId, OwnedDeviceId, OwnedServerName, UserId,
}; };
use serde::Deserialize; use serde::Deserialize;
use tracing::{debug, error, warn}; use tracing::{debug, error, warn};
@ -133,7 +133,7 @@ where
} }
Some((user_id, device_id)) => ( Some((user_id, device_id)) => (
Some(user_id), Some(user_id),
Some(Box::<DeviceId>::from(device_id)), Some(OwnedDeviceId::from(device_id)),
None, None,
false, false,
), ),
@ -300,7 +300,7 @@ where
} }
struct XMatrix { struct XMatrix {
origin: Box<ServerName>, origin: OwnedServerName,
key: String, // KeyName? key: String, // KeyName?
sig: String, sig: String,
} }

View file

@ -54,8 +54,8 @@ use ruma::{
signatures::{CanonicalJsonObject, CanonicalJsonValue}, signatures::{CanonicalJsonObject, CanonicalJsonValue},
state_res::{self, RoomVersion, StateMap}, state_res::{self, RoomVersion, StateMap},
to_device::DeviceIdOrAllDevices, to_device::DeviceIdOrAllDevices,
uint, EventId, MilliSecondsSinceUnixEpoch, RoomId, RoomVersionId, ServerName, uint, EventId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedServerName,
ServerSigningKeyId, OwnedServerSigningKeyId, OwnedUserId, RoomId, RoomVersionId, ServerName,
}; };
use serde_json::value::{to_raw_value, RawValue as RawJsonValue}; use serde_json::value::{to_raw_value, RawValue as RawJsonValue};
use std::{ use std::{
@ -282,7 +282,7 @@ where
let response = T::IncomingResponse::try_from_http_response(http_response); let response = T::IncomingResponse::try_from_http_response(http_response);
if response.is_ok() && write_destination_to_cache { if response.is_ok() && write_destination_to_cache {
globals.actual_destination_cache.write().unwrap().insert( globals.actual_destination_cache.write().unwrap().insert(
Box::<ServerName>::from(destination), OwnedServerName::from(destination),
(actual_destination, host), (actual_destination, host),
); );
} }
@ -526,7 +526,7 @@ pub async fn get_server_keys_route(db: DatabaseGuard) -> Result<impl IntoRespons
return Err(Error::bad_config("Federation is disabled.")); return Err(Error::bad_config("Federation is disabled."));
} }
let mut verify_keys: BTreeMap<Box<ServerSigningKeyId>, VerifyKey> = BTreeMap::new(); let mut verify_keys: BTreeMap<OwnedServerSigningKeyId, VerifyKey> = BTreeMap::new();
verify_keys.insert( verify_keys.insert(
format!("ed25519:{}", db.globals.keypair().version()) format!("ed25519:{}", db.globals.keypair().version())
.try_into() .try_into()
@ -684,14 +684,14 @@ pub async fn send_transaction_message_route(
} }
}; };
acl_check(&sender_servername, &room_id, &db)?; acl_check(sender_servername, &room_id, &db)?;
let mutex = Arc::clone( let mutex = Arc::clone(
db.globals db.globals
.roomid_mutex_federation .roomid_mutex_federation
.write() .write()
.unwrap() .unwrap()
.entry(room_id.clone()) .entry(room_id.to_owned())
.or_default(), .or_default(),
); );
let mutex_lock = mutex.lock().await; let mutex_lock = mutex.lock().await;
@ -699,7 +699,7 @@ pub async fn send_transaction_message_route(
resolved_map.insert( resolved_map.insert(
event_id.clone(), event_id.clone(),
handle_incoming_pdu( handle_incoming_pdu(
&sender_servername, sender_servername,
&event_id, &event_id,
&room_id, &room_id,
value, value,
@ -1214,7 +1214,7 @@ fn handle_outlier_pdu<'a>(
&room_version, &room_version,
&incoming_pdu, &incoming_pdu,
None::<PduEvent>, // TODO: third party invite None::<PduEvent>, // TODO: third party invite
|k, s| auth_events.get(&(k.to_string().into(), s.to_owned())), |k, s| auth_events.get(&(k.to_owned(), s.to_owned())),
) )
.map_err(|_e| "Auth check failed".to_owned())? .map_err(|_e| "Auth check failed".to_owned())?
{ {
@ -1357,9 +1357,7 @@ async fn upgrade_outlier_to_timeline_pdu(
for (k, id) in leaf_state { for (k, id) in leaf_state {
if let Ok((ty, st_key)) = db.rooms.get_statekey_from_short(k) { if let Ok((ty, st_key)) = db.rooms.get_statekey_from_short(k) {
// FIXME: Undo .to_string().into() when StateMap state.insert((ty, st_key), id.clone());
// is updated to use StateEventType
state.insert((ty.to_string().into(), st_key), id.clone());
} else { } else {
warn!("Failed to get_statekey_from_short."); warn!("Failed to get_statekey_from_short.");
} }
@ -1501,7 +1499,7 @@ async fn upgrade_outlier_to_timeline_pdu(
None::<PduEvent>, // TODO: third party invite None::<PduEvent>, // TODO: third party invite
|k, s| { |k, s| {
db.rooms db.rooms
.get_shortstatekey(&k.to_string().into(), s) .get_shortstatekey(k, s)
.ok() .ok()
.flatten() .flatten()
.and_then(|shortstatekey| state_at_incoming_event.get(&shortstatekey)) .and_then(|shortstatekey| state_at_incoming_event.get(&shortstatekey))
@ -1705,9 +1703,7 @@ async fn upgrade_outlier_to_timeline_pdu(
.filter_map(|(k, id)| { .filter_map(|(k, id)| {
db.rooms db.rooms
.get_statekey_from_short(k) .get_statekey_from_short(k)
// FIXME: Undo .to_string().into() when StateMap .map(|(ty, st_key)| ((ty, st_key), id))
// is updated to use StateEventType
.map(|(ty, st_key)| ((ty.to_string().into(), st_key), id))
.map_err(|e| warn!("Failed to get_statekey_from_short: {}", e)) .map_err(|e| warn!("Failed to get_statekey_from_short: {}", e))
.ok() .ok()
}) })
@ -1867,7 +1863,7 @@ pub(crate) fn fetch_and_handle_outliers<'a>(
Ok(res) => { Ok(res) => {
warn!("Got {} over federation", next_id); warn!("Got {} over federation", next_id);
let (calculated_event_id, value) = let (calculated_event_id, value) =
match crate::pdu::gen_event_id_canonical_json(&res.pdu, &db) { match crate::pdu::gen_event_id_canonical_json(&res.pdu, db) {
Ok(t) => t, Ok(t) => t,
Err(_) => { Err(_) => {
back_off((*next_id).to_owned()); back_off((*next_id).to_owned());
@ -2401,7 +2397,7 @@ pub async fn get_missing_events_route(
continue; continue;
} }
queued_events.extend_from_slice( queued_events.extend_from_slice(
&serde_json::from_value::<Vec<Box<EventId>>>( &serde_json::from_value::<Vec<OwnedEventId>>(
serde_json::to_value(pdu.get("prev_events").cloned().ok_or_else(|| { serde_json::to_value(pdu.get("prev_events").cloned().ok_or_else(|| {
Error::bad_database("Event in db has no prev_events field.") Error::bad_database("Event in db has no prev_events field.")
})?) })?)
@ -2828,7 +2824,7 @@ async fn create_join_event(
// let mut auth_cache = EventMap::new(); // let mut auth_cache = EventMap::new();
// We do not add the event_id field to the pdu here because of signature and hashes checks // We do not add the event_id field to the pdu here because of signature and hashes checks
let (event_id, value) = match crate::pdu::gen_event_id_canonical_json(pdu, &db) { let (event_id, value) = match crate::pdu::gen_event_id_canonical_json(pdu, db) {
Ok(t) => t, Ok(t) => t,
Err(_) => { Err(_) => {
// Event could not be converted to canonical json // Event could not be converted to canonical json
@ -2839,7 +2835,7 @@ async fn create_join_event(
} }
}; };
let origin: Box<ServerName> = serde_json::from_value( let origin: OwnedServerName = serde_json::from_value(
serde_json::to_value(value.get("origin").ok_or(Error::BadRequest( serde_json::to_value(value.get("origin").ok_or(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Event needs an origin field.", "Event needs an origin field.",
@ -2985,10 +2981,10 @@ pub async fn create_invite_route(
// Add event_id back // Add event_id back
signed_event.insert( signed_event.insert(
"event_id".to_owned(), "event_id".to_owned(),
CanonicalJsonValue::String(event_id.into()), CanonicalJsonValue::String(event_id.to_string()),
); );
let sender: Box<_> = serde_json::from_value( let sender: OwnedUserId = serde_json::from_value(
signed_event signed_event
.get("sender") .get("sender")
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
@ -3000,7 +2996,7 @@ pub async fn create_invite_route(
) )
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "sender is not a user id."))?; .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "sender is not a user id."))?;
let invited_user: Box<_> = serde_json::from_value( let invited_user: OwnedUserId = serde_json::from_value(
signed_event signed_event
.get("state_key") .get("state_key")
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
@ -3259,7 +3255,7 @@ pub(crate) async fn fetch_required_signing_keys(
// the PDUs and either cache the key or add it to the list that needs to be retrieved. // the PDUs and either cache the key or add it to the list that needs to be retrieved.
fn get_server_keys_from_cache( fn get_server_keys_from_cache(
pdu: &RawJsonValue, pdu: &RawJsonValue,
servers: &mut BTreeMap<Box<ServerName>, BTreeMap<Box<ServerSigningKeyId>, QueryCriteria>>, servers: &mut BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>>,
room_version: &RoomVersionId, room_version: &RoomVersionId,
pub_key_map: &mut RwLockWriteGuard<'_, BTreeMap<String, BTreeMap<String, Base64>>>, pub_key_map: &mut RwLockWriteGuard<'_, BTreeMap<String, BTreeMap<String, Base64>>>,
db: &Database, db: &Database,
@ -3350,7 +3346,7 @@ pub(crate) async fn fetch_join_signing_keys(
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>, pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
db: &Database, db: &Database,
) -> Result<()> { ) -> Result<()> {
let mut servers: BTreeMap<Box<ServerName>, BTreeMap<Box<ServerSigningKeyId>, QueryCriteria>> = let mut servers: BTreeMap<OwnedServerName, BTreeMap<OwnedServerSigningKeyId, QueryCriteria>> =
BTreeMap::new(); BTreeMap::new();
{ {