Compare commits

...
Author SHA1 Message Date
timedout 6e06b8ae11 style: Remove stray unused import 2026-11-02 05:23:31 +00:00
timedout 5773914c9d feat: Move resolve-true-destination to federation 2026-11-02 05:05:36 +00:00
timedout 4ac23d8649 feat: Remove unused test commands 2026-11-01 05:15:17 +00:00
timedout 0e5c7cc640 feat: Move change-log-level to server 2026-11-01 05:09:14 +00:00
timedout 7577c9f001 feat: Remove force-device-list-updates
This command has not been useful since conduwuit 0.4.6 or so
2026-11-01 04:54:39 +00:00
timedout bdc06d8135 feat: Remove useless debug PDU commands 2026-11-01 04:54:07 +00:00
timedout 9bc58d34bf feat: Remove force-join-list-of-local-users
Nobody uses this
2026-11-01 04:47:10 +00:00
timedout 06a2e73e8a feat: Move & rename join-all-local-users 2026-11-01 02:47:05 +00:00
timedout 693f80eeb2 feat: Move & merge some membership-related commands into rooms membership 2026-11-01 02:00:53 +00:00
timedout 1666993187 feat: Move force-set-room-state-from-server into room state subcommand 2026-11-01 01:31:07 +00:00
timedout dbcc0e0d31 feat: Move show-auth-chain to graph command 2026-11-01 00:43:51 +00:00
timedout a535604a27 feat: Remove get-auth-chain command
It's not really useful to just know how long loading an auth chain took
2026-10-31 23:12:43 +00:00
timedout 2f82475811 feat: Move get-remote-pdu to graph command, simplify 2026-10-31 23:09:37 +00:00
timedout b651fbd088 feat: Move some PDU commands to !admin rooms graph 2026-10-31 22:56:13 +00:00
timedout 5de3d74436 feat: Move list-extremities to graph room subcommand 2026-10-31 22:30:23 +00:00
timedout 4f128af921 feat: Move & destructure servers-in-back command to federation group 2026-10-31 22:17:11 +00:00
timedout a748115ab5 feat: Move ping command to federation group 2026-10-31 21:16:07 +00:00
timedout 84d4c1c19e feat: Reorganise federation commands 2026-10-31 21:10:30 +00:00
timedout 7871ce9190 feat: Move room state commands to the room group 2026-10-31 20:57:49 +00:00
18 changed files with 1213 additions and 1785 deletions

No files matched your search

File diff suppressed because it is too large. Load diff
-202
View File
@@ -1,12 +1,8 @@
mod commands;
pub(crate) mod tester;
use clap::Subcommand;
use conduwuit::Result;
use ruma::{OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName};
use service::rooms::short::{ShortEventId, ShortRoomId};
use self::tester::TesterCommand;
use crate::admin_command_dispatch;
#[admin_command_dispatch]
@@ -17,177 +13,6 @@ pub enum DebugCommand {
message: Vec<String>,
},
/// Loads the auth_chain of a PDU, reporting how long it took.
GetAuthChain {
/// An event ID (the $ character followed by the base64 reference hash)
event_id: OwnedEventId,
},
/// Walks & displays the auth_chain of a PDU in a mermaid graph format.
///
/// This is useless to basically anyone but developers, and is also probably
/// slow and memory hungry.
ShowAuthChain {
/// The root event ID to start walking back from.
event_id: OwnedEventId,
},
/// Parse and print a PDU from a JSON
///
/// The PDU event is only checked for validity and is not added to the
/// database.
///
/// This command needs a JSON blob provided in a Markdown code block below
/// the command.
ParsePdu,
/// Retrieve and print a PDU by EventID from the Continuwuity database
GetPdu {
/// An event ID (a $ followed by the base64 reference hash)
event_id: OwnedEventId,
},
/// Retrieve and print a PDU by PduId from the Continuwuity database
GetShortPdu {
/// Shortroomid integer
shortroomid: ShortRoomId,
/// Shorteventid integer
shorteventid: ShortEventId,
},
/// Attempts to retrieve a PDU from a remote server. **Does not** insert
/// it into the database
/// or persist it anywhere.
GetRemotePdu {
/// An event ID (a $ followed by the base64 reference hash)
event_id: OwnedEventId,
/// Argument for us to attempt to fetch the event from the
/// specified remote server.
server: OwnedServerName,
},
/// Same as `get-remote-pdu` but accepts a codeblock newline delimited
/// list of PDUs and a single server to fetch from
GetRemotePduList {
/// Argument for us to attempt to fetch all the events from the
/// specified remote server.
server: OwnedServerName,
/// If set, ignores errors, else stops at the first error/failure.
#[arg(short, long)]
force: bool,
},
/// Gets all the room state events for the specified room.
///
/// This is functionally equivalent to `GET
/// /_matrix/client/v3/rooms/{roomid}/state`, except the admin command does
/// *not* check if the sender user is allowed to see state events. This is
/// done because it's implied that server admins here have database access
/// and can see/get room info themselves anyways if they were malicious
/// admins.
///
/// Of course the check is still done on the actual client API.
GetRoomState {
/// Room ID
room_id: OwnedRoomOrAliasId,
},
/// Gets all the room state events at the specified event.
///
/// State at event might not be available for some PDUs, such as rejected
/// ones.
GetStateAt {
event_id: OwnedEventId,
},
/// Sends a federation request to the remote server's
/// `/_matrix/federation/v1/version` endpoint and measures the latency it
/// took for the server to respond
Ping {
server: OwnedServerName,
},
/// Forces device lists for all local and remote users to be updated (as
/// having new keys available)
ForceDeviceListUpdates,
/// Change tracing log level/filter on the fly
///
/// This accepts the same format as the `log` config option.
ChangeLogLevel {
/// Log level/filter
filter: Option<String>,
/// Resets the log level/filter to the one in your config
#[arg(short, long)]
reset: bool,
},
/// Verify JSON signatures
///
/// This command needs a JSON blob provided in a Markdown code block below
/// the command.
VerifyJson,
/// Verify PDU
///
/// This re-verifies a PDU existing in the database found by ID.
VerifyPdu {
event_id: OwnedEventId,
},
/// Prints the very first PDU in the specified room (typically
/// m.room.create)
FirstPduInRoom {
/// The room ID
room_id: OwnedRoomId,
},
/// Prints the latest ("last") PDU in the specified room (typically a
/// message)
LatestPduInRoom {
/// The room ID
room_id: OwnedRoomId,
},
/// Forcefully replaces the room state of our local copy of the specified
/// room, with the copy (auth chain and room state events) the specified
/// remote server says.
///
/// A common desire for room deletion is to simply "reset" our copy of the
/// room. While this admin command is not a replacement for that, if you
/// know you have split/broken room state and you know another server in the
/// room that has the best/working room state, this command can let you use
/// their room state. Such example is your server saying users are in a
/// room, but other servers are saying they're not in the room in question.
///
/// This command will get the latest PDU in the room we know about, and
/// request the room state at that point in time via
/// `/_matrix/federation/v1/state/{roomId}`.
ForceSetRoomStateFromServer {
/// The impacted room ID
room_id: OwnedRoomId,
/// The server we will use to query the room state for
server_name: OwnedServerName,
/// The event ID of the latest known PDU in the room. Will be found
/// automatically if not provided.
event_id: Option<OwnedEventId>,
},
/// Runs a server name through Continuwuity's true destination resolution
/// process
///
/// Useful for debugging well-known issues
ResolveTrueDestination {
server_name: OwnedServerName,
#[arg(short, long)]
no_cache: bool,
},
/// Print extended memory usage
///
/// Optional argument is a character mask (a sequence of characters in any
@@ -204,9 +29,6 @@ pub enum DebugCommand {
/// invocation.
RuntimeInterval,
/// Print the current time
Time,
/// Get database statistics
DatabaseStats {
property: Option<String>,
@@ -233,28 +55,4 @@ pub enum DebugCommand {
RoomsByExtremityCount {
page: Option<usize>,
},
RoomExtremities {
room_id: OwnedRoomId,
},
/// Lists remote servers that are currently in a "backoff" state.
///
/// Servers in this list will not be contacted until the retry time elapses,
/// or they make contact first.
///
/// "Stale" indicates that routing information may be out of date, and the
/// remote will be re-resolved immediately before the next contact attempt.
ServersInBackoff {
#[arg(short, long, alias = "room")]
room_id: Option<OwnedRoomId>,
#[arg(short, long)]
name: Option<OwnedServerName>,
},
/// Developer test stubs
#[command(subcommand)]
#[allow(non_snake_case)]
#[clap(hide(true))]
Tester(TesterCommand),
}
-48
View File
@@ -1,48 +0,0 @@
use conduwuit::{Err, Result};
use crate::admin_command_dispatch;
#[admin_command_dispatch]
#[derive(Debug, clap::Subcommand)]
pub enum TesterCommand {
Panic,
Failure,
Tester,
Timer,
}
#[allow(clippy::unused_async_trait_impl)]
impl crate::Context<'_> {
#[rustfmt::skip]
async fn panic(&self) -> Result {
panic!("panicked")
}
#[rustfmt::skip]
async fn failure(&self) -> Result {
Err!("failed")
}
#[inline(never)]
#[rustfmt::skip]
async fn tester(&self) -> Result {
self.write_str("Ok").await
}
#[inline(never)]
#[rustfmt::skip]
async fn timer(&self) -> Result {
let started = std::time::Instant::now();
timed(self.body);
let elapsed = started.elapsed();
self.write_str(&format!("completed in {elapsed:#?}")).await
}
}
#[inline(never)]
#[rustfmt::skip]
#[allow(unused_variables)]
fn timed(body: &[&str]) {
}
+77 -46
View File
@@ -1,20 +1,23 @@
use std::fmt::Write;
use conduwuit::{Err, Result, utils::response::LimitReadExt};
use futures::StreamExt;
use ruma::{MilliSecondsSinceUnixEpoch, OwnedRoomId, OwnedServerName, OwnedUserId};
use crate::get_room_info;
use resolvematrix::{
resolution::ResolvedDestination,
server::{MatrixResolver, MatrixResolverBuilder},
};
use ruma::{MilliSecondsSinceUnixEpoch, OwnedRoomOrAliasId, OwnedServerName};
impl crate::Context<'_> {
pub(super) async fn disable_room(&self, room_id: OwnedRoomId) -> Result {
pub(super) async fn disable_room(&self, room: OwnedRoomOrAliasId) -> Result {
self.bail_restricted()?;
let room_id = self.services.rooms.alias.resolve(&room).await?;
self.services.rooms.metadata.disable_room(&room_id, true);
self.write_str("Room disabled.").await
}
pub(super) async fn enable_room(&self, room_id: OwnedRoomId) -> Result {
pub(super) async fn enable_room(&self, room: OwnedRoomOrAliasId) -> Result {
self.bail_restricted()?;
let room_id = self.services.rooms.alias.resolve(&room).await?;
self.services.rooms.metadata.disable_room(&room_id, false);
self.write_str("Room enabled.").await
}
@@ -33,13 +36,13 @@ impl crate::Context<'_> {
map.len(),
self.services.transactions.txn_active_handle_count()
);
for (r, (e, i)) in map.iter() {
let elapsed = i.elapsed();
for (room_id, (event_id, started_at)) in map.iter() {
let elapsed = started_at.elapsed();
writeln!(
msg,
"{} {}: {}m{}s",
r,
e,
room_id,
event_id,
elapsed.as_secs() / 60,
elapsed.as_secs() % 60
)?;
@@ -50,7 +53,7 @@ impl crate::Context<'_> {
self.write_str(&msg).await
}
pub(super) async fn fetch_support_well_known(&self, server_name: OwnedServerName) -> Result {
pub(super) async fn fetch_support(&self, server_name: OwnedServerName) -> Result {
let response = self
.services
.client
@@ -97,41 +100,6 @@ impl crate::Context<'_> {
.await
}
pub(super) async fn remote_user_in_rooms(&self, user_id: OwnedUserId) -> Result {
if user_id.server_name() == self.services.server.name {
return Err!(
"User belongs to our server, please use `list-joined-rooms` user admin command \
instead.",
);
}
let mut rooms: Vec<(OwnedRoomId, u64, String)> = self
.services
.rooms
.state_cache
.rooms_joined(&user_id)
.then(async |room_id| get_room_info(self.services, &room_id).await)
.collect()
.await;
if rooms.is_empty() {
return Err!("User is not in any rooms.");
}
rooms.sort_by_key(|r| r.1);
rooms.reverse();
let num = rooms.len();
let body = rooms
.iter()
.map(|(id, members, name)| format!("{id} | Members: {members} | Name: {name}"))
.collect::<Vec<_>>()
.join("\n");
self.write_str(&format!("Rooms {user_id} shares with us ({num}):\n```\n{body}\n```"))
.await
}
pub(super) async fn get_signing_keys(&self, server_name: OwnedServerName) -> Result {
let response = self
.services
@@ -157,4 +125,67 @@ impl crate::Context<'_> {
Ok(())
}
pub(super) async fn ping(&self, server: OwnedServerName) -> Result {
let timer = tokio::time::Instant::now();
match self
.services
.sending
.send_unauthenticated_request(
&server,
ruma::api::federation::discovery::get_server_version::v1::Request::new(),
)
.await
{
| Err(e) => {
return Err!("Failed sending federation request to specified server:\n\n{e}");
},
| Ok(response) => {
let ping_time = timer.elapsed();
let json_text_res = serde_json::to_string_pretty(&response.server);
let out = if let Ok(json) = json_text_res {
format!("Got response which took {ping_time:?} time:\n```json\n{json}\n```")
} else {
format!("Got non-JSON response which took {ping_time:?} time:\n{response:?}")
};
write!(self, "{out}")
},
}
.await
}
pub(super) async fn resolve_true_destination(
&self,
server_name: OwnedServerName,
no_cache: bool,
) -> Result {
if !self.services.server.config.allow_federation {
return Err!("Federation is disabled on this homeserver.",);
}
let resolver: &MatrixResolver = if no_cache {
&MatrixResolverBuilder::new()
.dangerous_tls_accept_invalid_certs(self.services.server.config.allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure)
.http_client(self.services.client.dns.clone())
.build()?
} else {
&self.services.client.matrix_resolver
};
let actual = resolver.resolve_server(server_name.as_str()).await?;
let destination = match actual.destination {
| ResolvedDestination::Literal(addr) => addr.to_string(),
| ResolvedDestination::Named(host, port) => format!("{host}:{port}"),
};
let msg = format!(
"Destination: {}\nHostname URI (SNI): {}\nIs override?: {}\nResolution step: {}",
destination, actual.host, actual.is_override, actual.resolution_step
);
self.write_str(&msg).await
}
}
+161
View File
@@ -0,0 +1,161 @@
use std::time::Duration;
use clap::Subcommand;
use conduwuit::Result;
use conduwuit_macros::admin_command_dispatch;
use futures::StreamExt;
use ruma::{OwnedRoomOrAliasId, OwnedServerName};
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum HealthCommand {
/// Lists all servers that are currently marked as unhealthy (i.e. we
/// previously failed to establish direct federation and have not succeeded
/// since).
#[clap(name = "list")]
ListUnhealthyServers {
/// An optional filter to only check servers that are in a specific room
/// (ID or alias).
room: Option<OwnedRoomOrAliasId>,
},
/// Displays the current health status of the given remote server.
#[clap(name = "status")]
ServerHealthStatus {
server_name: OwnedServerName,
},
/// Forces the server to consider the remote server healthy.
///
/// This is generally unnecessary as this already happens when the remote
/// server makes contact with this server, or if this server successfully
/// makes a request to the remote server after the backoff window.
ForceHealthy {
server_name: OwnedServerName,
},
/// Forces the server to consider the remote server unhealthy.
///
/// This is generally unnecessary as this already happens when the remote
/// server fails to resolve or connect, or returns unusual errors.
/// If you are looking to stop contacting a specific server, take a look at
/// the `forbidden_remote_server_names` configuration option.
ForceUnhealthy {
server_name: OwnedServerName,
/// If set, the server will also be marked as having stale routing
/// information. This means the address will be re-resolved on the next
/// connection attempt.
#[arg(long)]
stale: bool,
},
}
impl crate::Context<'_> {
pub(super) async fn list_unhealthy_servers(
&self,
room: Option<OwnedRoomOrAliasId>,
) -> Result {
let unhealthy = self.services.federation.remote_health();
if unhealthy.is_empty() {
return self
.write_str("No servers are currently tracked as unhealthy.")
.await;
}
let stale_destinations = self.services.federation.stale_destinations();
let mut candidates: Vec<_> = if let Some(room) = room {
let room_id = self.services.rooms.alias.resolve(&room).await?;
self.services
.rooms
.state_cache
.room_servers(&room_id)
.collect()
.await
} else {
unhealthy
.keys()
.chain(stale_destinations.iter())
.cloned()
.collect()
};
candidates.retain(|name| unhealthy.contains_key(name));
candidates.sort();
candidates.dedup();
if candidates.is_empty() {
return self
.write_str("No servers are currently unhealthy meeting the given criteria.")
.await;
}
for server_name in candidates {
let Some((retries, retry_at)) = unhealthy.get(&server_name) else { continue };
let is_stale = if stale_destinations.contains(&server_name) {
"Yes"
} else {
"No"
};
self.write_str(&format!("| {server_name} | {retries} | {retry_at} | {is_stale} |\n"))
.await?;
}
Ok(())
}
pub(super) async fn server_health_status(&self, server_name: OwnedServerName) -> Result {
let stale = self
.services
.federation
.stale_destinations()
.contains(&server_name);
let Some((retries, retry_at_ts)) = self
.services
.federation
.remote_health()
.get(&server_name)
.copied()
else {
return self
.write_str(&if stale {
format!(
"{server_name} is currently healthy, but may have stale routing \
information."
)
} else {
format!("{server_name} is currently healthy.")
})
.await;
};
let state = if stale {
"unhealthy with potentially stale routing information"
} else {
"unhealthy"
};
self.write_str(&format!(
"{server_name} is currently {state}: {retries} consecutive connections have \
failed,and no new connection will be attempted for another {}.",
conduwuit::utils::time::pretty(Duration::from_millis(retry_at_ts)),
))
.await
}
pub(super) async fn force_healthy(&self, server_name: OwnedServerName) -> Result {
self.services.federation.mark_healthy(&server_name);
self.write_str("Done.").await
}
pub(super) async fn force_unhealthy(
&self,
server_name: OwnedServerName,
stale: bool,
) -> Result {
if stale {
self.services
.federation
.mark_destination_stale(&server_name);
}
self.services.federation.hit_unhealthy(server_name);
self.write_str("Done.").await
}
}
+35 -16
View File
@@ -1,47 +1,66 @@
mod commands;
mod health;
use clap::Subcommand;
use conduwuit::Result;
use ruma::{OwnedRoomId, OwnedServerName, OwnedUserId};
use ruma::{OwnedRoomOrAliasId, OwnedServerName};
use crate::admin_command_dispatch;
use crate::{admin_command_dispatch, federation::health::HealthCommand};
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum FederationCommand {
/// List all rooms we are currently handling an incoming pdu from
#[clap(name = "incoming", alias = "inbound")]
IncomingFederation,
/// Disables incoming federation handling for a room.
///
/// The room can still be used locally, but events from other servers will
/// stop being received.
DisableRoom {
room_id: OwnedRoomId,
room: OwnedRoomOrAliasId,
},
/// Enables incoming federation handling for a room again.
///
/// This does not unban the room if it was banned, it only re-enables
/// incoming events.
EnableRoom {
room_id: OwnedRoomId,
room: OwnedRoomOrAliasId,
},
/// Fetch `/.well-known/matrix/support` from the specified server
/// Fetch support details from the given server.
///
/// Despite the name, this is not a federation endpoint and does not go
/// through the federation / server resolution process as per-spec this is
/// supposed to be served at the server_name.
///
/// Respecting homeservers put this file here for listing administration,
/// moderation, and security inquiries. This command provides a way to
/// easily fetch that information.
FetchSupportWellKnown {
/// This makes a request to `https://<server_name>/.well-known/matrix/support`. Many servers do not advertise support information, but those that do usually provide a way to contact homeserver administrators.
FetchSupport {
server_name: OwnedServerName,
},
/// Lists all the rooms we share/track with the specified *remote* user
RemoteUserInRooms {
user_id: OwnedUserId,
/// Runs a server name through Continuwuity's server-to-server address
/// resolution process.
#[clap(name = "resolve")]
ResolveTrueDestination {
server_name: OwnedServerName,
#[arg(short, long)]
skip_cache: bool,
},
/// Queries the remote server for their current signing keys.
GetSigningKeys {
server_name: OwnedServerName,
},
/// Makes a federation request to the remote server, to test connectivity.
///
/// The request is made to the federation version endpoint, which if
/// successful, will also reveal how long the request took and what the
/// remote server's software is.
Ping {
server_name: OwnedServerName,
},
#[command(subcommand)]
Health(HealthCommand),
}
+401
View File
@@ -0,0 +1,401 @@
use std::{
collections::{HashMap, HashSet},
fmt::Write,
};
use clap::Subcommand;
use conduwuit::{Err, Event, PduEvent, Result, err, utils::stream::BroadbandExt};
use conduwuit_macros::admin_command_dispatch;
use futures::StreamExt;
use ruma::{EventId, OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, UInt};
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum GraphCommand {
/// Lists all forward extremities in a room.
ListExtremities {
room: OwnedRoomOrAliasId,
},
/// Fetches a PDU (event) by its event ID, as stored in the database. Also
/// includes details about the PDU state.
GetPDU {
event_id: OwnedEventId,
},
/// Fetches a PDU over federation. Does not store the result.
FetchPDU {
event_id: OwnedEventId,
server_name: OwnedServerName,
},
/// Yields the first PDU we became aware of in a room.
/// This is always the room's create event for local rooms, or the first
/// membership event that introduced us to the remote room.
#[clap(name = "first-pdu")]
FirstPduInRoom {
room_id: OwnedRoomId,
},
/// Yields the most recent PDU in a room.
#[clap(name = "latest-pdu")]
LatestPduInRoom {
room_id: OwnedRoomId,
},
/// Draws a mermaid graph of the auth chain for an event.
ShowAuthChain {
event_id: OwnedEventId,
},
}
impl crate::Context<'_> {
pub(super) async fn list_extremities(&self, room: OwnedRoomOrAliasId) -> Result {
let room_id = self.services.rooms.alias.resolve(&room).await?;
let mut extremities = self
.services
.rooms
.state
.get_forward_extremities(&room_id)
.broad_filter_map(|event_id| async move {
self.services.rooms.timeline.get_pdu(&event_id).await.ok()
})
.collect::<Vec<_>>()
.await;
extremities.sort_by_key(|pdu| (pdu.depth, pdu.origin_server_ts));
if extremities.is_empty() {
return Err!("No room extremities.");
}
self.write_str("| Event ID | Type | Sender | Timestamp | Depth |\n")
.await?;
self.write_str("| -------- | ---- | ------ | --------- | ----- |\n")
.await?;
for pdu in extremities {
let url = format!(
"https://matrix.to/#/{}/{}?via={}",
room_id,
pdu.event_id(),
self.services.server.name
);
self.write_str(&format!(
"| [`{}`]({url}) | `{}` | `{}` | `{}` | `{}` |\n",
pdu.event_id(),
pdu.kind(),
pdu.sender(),
pdu.origin_server_ts,
pdu.depth
))
.await?;
}
Ok(())
}
pub(super) async fn get_pdu(&self, event_id: OwnedEventId) -> Result {
let mut outlier = false;
let mut pdu_json = self
.services
.rooms
.timeline
.get_non_outlier_pdu_json(&event_id)
.await;
if pdu_json.is_err() {
outlier = true;
pdu_json = self.services.rooms.timeline.get_pdu_json(&event_id).await;
}
let rejected = self
.services
.rooms
.pdu_metadata
.is_event_rejected(&event_id)
.await;
let soft_failed = self
.services
.rooms
.pdu_metadata
.is_event_soft_failed(&event_id)
.await;
match pdu_json {
| Err(_) => return Err!("PDU not found locally."),
| Ok(json) => {
let text = serde_json::to_string_pretty(&json)?;
let msg = if rejected {
"Rejected PDU:"
} else if soft_failed {
"Soft-failed PDU:"
} else if outlier {
"Outlier PDU:"
} else {
"Timeline PDU:"
};
write!(self, "{msg}\n```json\n{text}\n```")
},
}
.await
}
pub(super) async fn fetch_pdu(
&self,
event_id: OwnedEventId,
server: OwnedServerName,
) -> Result {
let response = self
.services
.sending
.send_federation_request(
&server,
ruma::api::federation::event::get_event::v1::Request::new(event_id.clone()),
)
.await?;
let (real_event_id, room_id, pdu_json) = self
.services
.rooms
.event_handler
.parse_incoming_pdu(&response.pdu, None)
.await?;
self.write_str(&format!(
"Event ID: {real_event_id}\nRoom ID: {room_id}\nPDU:\n```json\n{}\n```",
serde_json::to_string_pretty(&pdu_json)?
))
.await
}
pub(super) async fn first_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
let first_pdu = self
.services
.rooms
.timeline
.first_pdu_in_room(&room_id)
.await
.map(Event::into_canonical_object)
.and_then(|v| serde_json::to_string_pretty(&v).map_err(Into::into))
.map_err(|e| err!(Database("Failed to find the first PDU in database: {e:?}")))?;
let out = format!("```json\n{first_pdu}\n```");
self.write_str(&out).await
}
pub(super) async fn latest_pdu_in_room(&self, room_id: OwnedRoomId) -> Result {
self.bail_restricted()?;
let latest_pdu = self
.services
.rooms
.timeline
.latest_pdu_in_room(&room_id)
.await
.map(Event::into_canonical_object)
.and_then(|v| serde_json::to_string_pretty(&v).map_err(Into::into))
.map_err(|e| err!(Database("Failed to find the latest PDU in database: {e:?}")))?;
let out = format!("```json\n{latest_pdu}\n```");
self.write_str(&out).await
}
pub(super) async fn show_auth_chain(&self, event_id: OwnedEventId) -> Result {
// TODO: This command sucks and really needs to elide redundant auth
// edges.
let node_status = async |event_id: &EventId, missing: bool| -> NodeStatus {
if self
.services
.rooms
.pdu_metadata
.is_event_rejected(event_id)
.await
{
NodeStatus::Rejected(missing)
} else if self
.services
.rooms
.pdu_metadata
.is_event_soft_failed(event_id)
.await
{
NodeStatus::SoftFailed(missing)
} else {
NodeStatus::Normal(missing)
}
};
let Ok(root) = self.services.rooms.timeline.get_pdu(&event_id).await else {
return Err!("Event not found.");
};
let mut graph = String::from(
"```mermaid\n%% This is a mermaid graph. You can plug this output into\n\
%% https://mermaid.live/edit to visualise it on-the-fly.\nflowchart TD\n\
classDef rejected fill:#ffe5e5,stroke:#cc0000,stroke-width:2px,color:#000;\n\
classDef soft_failed fill:#fff6cc,stroke:#c9a400,stroke-width:2px,color:#000;\n"
);
let mut node_ids: HashMap<OwnedEventId, String> = HashMap::new();
let mut cached_events: HashMap<OwnedEventId, PduEvent> =
HashMap::from([(event_id.clone(), root.clone())]);
let mut scheduled: HashSet<OwnedEventId> = HashSet::from([event_id.clone()]);
let mut visited: HashSet<OwnedEventId> = HashSet::new();
let mut stack = vec![root];
let mut next_node_id = 0_usize;
let node_id_for = |event_id: &OwnedEventId,
node_ids: &mut HashMap<OwnedEventId, String>,
next_node_id: &mut usize| {
node_ids
.entry(event_id.clone())
.or_insert_with(|| {
let id = format!("n{}", *next_node_id);
*next_node_id = next_node_id.saturating_add(1);
id
})
.clone()
};
let node_name = |e: &PduEvent| {
if let Some(state_key) = e.state_key() {
format!("{},'{}'", e.event_type(), state_key)
} else {
format!("{}", e.event_type())
}
};
while let Some(event) = stack.pop() {
let current_event_id = event.event_id().to_owned();
if !visited.insert(current_event_id.clone()) {
continue;
}
let current_node_id =
node_id_for(&current_event_id, &mut node_ids, &mut next_node_id);
let current_status = node_status(&current_event_id, false).await;
render_node(
&mut graph,
&current_node_id,
&current_event_id,
&node_name(&event),
current_status,
)?;
let mut children = Vec::with_capacity(event.auth_events.len());
for auth_event_id in event.auth_events().rev() {
let auth_event_id = auth_event_id.to_owned();
let auth_node_id = node_id_for(&auth_event_id, &mut node_ids, &mut next_node_id);
writeln!(graph, "{current_node_id} --> {auth_node_id}")?;
let first_seen = scheduled.insert(auth_event_id.clone());
let auth_pdu = if let Some(auth_pdu) = cached_events.get(&auth_event_id) {
// NOTE: events might be referenced multiple times (like the
// create event) so this saves some cheeky db lookup
// time
Some(auth_pdu.clone())
} else if first_seen {
match self.services.rooms.timeline.get_pdu(&auth_event_id).await {
| Ok(auth_event) => {
cached_events.insert(auth_event_id.clone(), auth_event.clone());
Some(auth_event)
},
| Err(_) => None,
}
} else {
None
};
// NOTE: Depth is used as the primary sorting key here, even
// though it has no bearing on state resolution or anything.
// Timestamp is used as a tiebreaker, failing back to
// lexicographical comparison.
let (depth, ts) = auth_pdu
.as_ref()
.map_or((UInt::MAX, UInt::MAX), |pdu| (pdu.depth, pdu.origin_server_ts));
children.push(AuthChild {
node_id: auth_node_id,
event_id: auth_event_id,
depth,
ts,
first_seen,
pdu: auth_pdu,
});
}
children.sort_by(|a, b| {
a.depth
.cmp(&b.depth)
.then(a.ts.cmp(&b.ts))
.then(a.event_id.as_str().cmp(b.event_id.as_str()))
});
for child in children.into_iter().rev() {
if !child.first_seen {
continue;
}
if let Some(child_pdu) = child.pdu {
// We have this PDU so will want to traverse it.
stack.push(child_pdu);
} else {
// We don't have this PDU locally so we can't traverse its
// auth events, but we can still render it as a node.
render_node(
&mut graph,
&child.node_id,
&child.event_id,
"",
node_status(&child.event_id, true).await,
)?;
}
}
}
graph.push_str("```\n");
self.write_str(&graph).await
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum NodeStatus {
Normal(bool),
SoftFailed(bool),
Rejected(bool),
}
struct AuthChild {
node_id: String,
event_id: OwnedEventId,
depth: UInt,
ts: UInt,
first_seen: bool,
pdu: Option<PduEvent>,
}
fn render_node(
graph: &mut String,
node_id: &str,
event_id: &EventId,
name: &str,
status: NodeStatus,
) -> Result {
let evt_str = event_id.to_string();
let status_label = match status {
| NodeStatus::Normal(false) => format!("{evt_str}: {name}"),
| NodeStatus::Normal(true) => format!("{evt_str}: {name} (missing locally)"),
| NodeStatus::SoftFailed(false) => format!("{evt_str}: {name} (soft-failed)"),
| NodeStatus::SoftFailed(true) =>
format!("{evt_str}: {name} (soft-failed & missing locally)"),
| NodeStatus::Rejected(false) => format!("{evt_str}: {name} (rejected)"),
| NodeStatus::Rejected(true) => format!("{evt_str}: {name} (rejected & missing locally)"),
};
writeln!(graph, "{node_id}[\"{}\"]", status_label.as_str())?;
match status {
| NodeStatus::Rejected(_) => writeln!(graph, "class {node_id} rejected;")?,
| NodeStatus::SoftFailed(_) => writeln!(graph, "class {node_id} soft_failed;")?,
| NodeStatus::Normal(_) => {},
}
Ok(())
}
+167
View File
@@ -0,0 +1,167 @@
use std::hash::RandomState;
use clap::Subcommand;
use conduwuit::{Err, Result, info};
use conduwuit_macros::admin_command_dispatch;
use futures::StreamExt;
use ruma::{OwnedRoomOrAliasId, OwnedServerName, OwnedUserId};
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum RoomMembershipCommands {
/// Make a local user join a room.
#[clap(name = "join")]
JoinRoom {
/// The user to make join the room. Must be a local user.
user_id: OwnedUserId,
/// The room (ID or alias) to join.
room: OwnedRoomOrAliasId,
/// The server to join through, if a remote room.
///
/// Residents returned after resolving an alias override this option.
#[arg(long)]
via: Option<OwnedServerName>,
},
/// Makes all local users join the designated room.
JoinAllLocalUsers {
/// The room (ID or alias) to join.
room: OwnedRoomOrAliasId,
},
/// Make a local user leave a room or reject an invite.
#[clap(name = "leave", alias = "reject-invite")]
LeaveRoom {
/// The user to make leave the room. Must be a local user.
user_id: OwnedUserId,
/// The room (ID or alias) to leave.
room: OwnedRoomOrAliasId,
/// The server to leave through, if a room we are not a member of (e.g.
/// an invite).
///
/// Residents returned after resolving an alias override this option.
#[arg(long)]
via: Option<OwnedServerName>,
},
}
impl crate::Context<'_> {
pub(super) async fn join_room(
&self,
user_id: OwnedUserId,
room: OwnedRoomOrAliasId,
via: Option<OwnedServerName>,
) -> Result {
self.bail_restricted()?;
if !self.services.globals.user_is_local(&user_id) {
return Err!("User {user_id:?} does not belong to our server.");
}
let (room_id, residents) = self
.services
.rooms
.alias
.resolve_with_servers(&room, via.map(|v| vec![v]))
.await?;
self.services
.rooms
.membership
.join_room(&user_id, &room_id, None, &residents)
.await?;
self.write_str(&format!("Successfully joined {room_id} as {user_id}."))
.await
}
pub(super) async fn join_all_local_users(&self, room: OwnedRoomOrAliasId) -> Result {
self.bail_restricted()?;
let (room_id, residents) = self
.services
.rooms
.alias
.resolve_with_servers(&room, None)
.await?;
if !self
.services
.rooms
.state_cache
.is_joined(
self.sender
.expect("This command must be executed by a user"),
&room_id,
)
.await
{
return Err!("You must be a member of the room you want to join everyone to.");
}
let mut success = 0_usize;
let mut failed = 0_usize;
let mut local_users = self.services.users.stream_local_users();
while let Some(user_id) = local_users.next().await {
if self
.services
.rooms
.membership
.join_room(&user_id, &room_id, None, &residents)
.await
.is_ok()
{
success = success.saturating_add(1);
} else {
failed = failed.saturating_add(1);
}
}
self.write_str(&format!("Done: {success} successful joins, {failed} failed."))
.await
}
pub(super) async fn leave_room(
&self,
user_id: OwnedUserId,
room: OwnedRoomOrAliasId,
via: Option<OwnedServerName>,
) -> Result {
self.bail_restricted()?;
if !self.services.globals.user_is_local(&user_id) {
return Err!("User {user_id:?} does not belong to our server.");
}
let no_explicit_via = via.is_none();
let (room_id, residents) = self
.services
.rooms
.alias
.resolve_with_servers(&room, via.map(|v| vec![v]))
.await?;
if no_explicit_via
|| self
.services
.rooms
.state_cache
.server_in_room(self.services.globals.server_name(), &room_id)
.await
{
if !self
.services
.rooms
.state_cache
.is_joined(&user_id, &room_id)
.await
{
return Err!("User {user_id:?} is not a member of room {room_id:?}.");
}
info!("Leaving room locally...");
conduwuit_api::client::leave_room(self.services, &user_id, &room_id, None).await?;
} else {
info!("Leaving room remotely...");
conduwuit_api::client::remote_leave_room::<RandomState>(
self.services,
&user_id,
&room_id,
None,
residents.into_iter().collect(),
)
.await?;
}
self.write_str(&format!("Successfully made {user_id} leave {room_id}."))
.await
}
}
+22 -6
View File
@@ -1,16 +1,20 @@
mod alias;
mod commands;
mod directory;
mod graph;
mod info;
mod membership;
mod moderation;
mod state;
use clap::Subcommand;
use conduwuit::Result;
use ruma::OwnedRoomId;
use self::{
alias::RoomAliasCommand, directory::RoomDirectoryCommand, info::RoomInfoCommand,
moderation::RoomModerationCommand,
alias::RoomAliasCommand, directory::RoomDirectoryCommand, graph::GraphCommand,
info::RoomInfoCommand, membership::RoomMembershipCommands, moderation::RoomModerationCommand,
state::RoomStateCommand,
};
use crate::admin_command_dispatch;
@@ -40,22 +44,34 @@ pub enum RoomCommand {
no_details: bool,
},
#[command(subcommand)]
/// View information about a room we know about
#[command(subcommand)]
Info(RoomInfoCommand),
#[command(subcommand)]
/// Manage moderation of remote or local rooms
#[command(subcommand)]
Moderation(RoomModerationCommand),
#[command(subcommand)]
/// Manage rooms' aliases
#[command(subcommand)]
Alias(RoomAliasCommand),
#[command(subcommand)]
/// Manage the room directory
#[command(subcommand)]
Directory(RoomDirectoryCommand),
/// Manage room memberships (join, leave, invite, etc.) for local users.
#[command(subcommand)]
Membership(RoomMembershipCommands),
/// Interface with room graphs directly (advanced).
#[command(subcommand)]
Graph(GraphCommand),
/// Interface with room state directly (advanced).
#[command(subcommand)]
State(RoomStateCommand),
/// Check if we know about a room
Exists {
room_id: OwnedRoomId,
+286
View File
@@ -0,0 +1,286 @@
use std::collections::HashMap;
use clap::Subcommand;
use conduwuit::{Err, Event, PduEvent, Result, debug_error, err, info, warn};
use conduwuit_macros::admin_command_dispatch;
use futures::StreamExt;
#[allow(unused_imports)]
// necessary to stop RustRover from importing this trait for some reason
use ruma::state_res::Event as _;
use ruma::{
OwnedEventId, OwnedRoomOrAliasId, OwnedServerName, api::federation::event::get_room_state,
};
use service::rooms::state_compressor::HashSetCompressStateEvent;
#[admin_command_dispatch]
#[derive(Debug, Subcommand)]
pub enum RoomStateCommand {
/// Exports the room's current state as a JSON file.
/// If an event ID is supplied, the state at that event (the state preceding
/// it, plus any change made by the named event) is returned instead, if it
/// is known.
#[clap(name = "export")]
ExportState {
/// The room ID or alias to get the state for.
room: OwnedRoomOrAliasId,
/// The event ID to get the state at, if any.
event_id: Option<OwnedEventId>,
},
/// Downloads the current state of a room from a remote server, and replaces
/// the local copy of the room's state with it.
///
/// If you're reading this, this command does not do what you think it does.
Transplant {
/// The room ID or alias to replace the current state of.
room: OwnedRoomOrAliasId,
/// The server name to fetch the state from. Make sure this is a trusted
/// server, as the result will be implicitly trusted.
server_name: OwnedServerName,
/// The latest event ID in the room to use as the "latest event".
/// Calculated by default.
at_event: Option<OwnedEventId>,
/// Try to force the state even if the server thinks it isn't in the
/// target room.
///
/// Using this on rooms the server has never joined may break
/// everything.
#[arg(long)]
force: bool,
// (the "may break everything" part isn't necessarily true, but it is highly likely that
// things will actually break in an unrecoverable way, so being dramatic gets the main
// point across)
},
}
impl crate::Context<'_> {
pub(super) async fn export_state(
&self,
room: OwnedRoomOrAliasId,
event_id: Option<OwnedEventId>,
) -> Result {
self.bail_restricted()?;
let room_id = self.services.rooms.alias.resolve(&room).await?;
let shortstatehash = match &event_id {
| Some(event_id) =>
self.services
.rooms
.state_accessor
.pdu_shortstatehash(event_id)
.await?,
| None =>
self.services
.rooms
.state
.get_room_shortstatehash(&room_id)
.await?,
};
let mut state_at: Vec<_> = self
.services
.rooms
.state_accessor
.state_full_pdus(shortstatehash)
.map(Event::into_pdu)
.collect()
.await;
if let Some(event_id) = event_id {
let pdu = self.services.rooms.timeline.get_pdu(&event_id).await?;
if let Some(state_key) = pdu.state_key() {
state_at.retain(|p| p.kind() != pdu.kind() || p.state_key() != Some(state_key));
state_at.push(pdu);
}
}
if state_at.is_empty() {
return Err!(Request(NotFound("No state found.")));
}
let json = serde_json::to_string_pretty(&state_at).map_err(|e| {
err!(Database(
"Failed to convert room state events to pretty JSON, possible invalid room \
state events in the database: {e:?}",
))
})?;
self.write_str(&format!("```json\n{json}\n```")).await
}
pub(super) async fn transplant(
&self,
room: OwnedRoomOrAliasId,
server_name: OwnedServerName,
latest_event: Option<OwnedEventId>,
force: bool,
) -> Result {
self.bail_restricted()?;
let room_id = self.services.rooms.alias.resolve(&room).await?;
if !force
&& !self
.services
.rooms
.state_cache
.server_in_room(&self.services.server.name, &room_id)
.await
{
return Err!(
"We are not participating in the room / we don't know about the room ID."
);
}
let at_event_id = match latest_event {
| Some(event_id) => event_id,
| None => self
.services
.rooms
.timeline
.latest_pdu_in_room(&room_id)
.await
.map_err(|_| err!(Database("Failed to find the latest PDU in database")))?
.event_id()
.to_owned(),
};
let room_version = self.services.rooms.state.get_room_version(&room_id).await?;
let room_version_rules = room_version.rules().unwrap();
let mut state: HashMap<u64, OwnedEventId> = HashMap::new();
let state_lock = self.services.rooms.state.mutex.lock(&*room_id).await;
// TODO: Use /state_ids and fetch events we're missing atomically,
// instead of /state, which is very large and frequently times out.
let remote_state_response = self
.services
.sending
.send_federation_request(
&server_name,
get_room_state::v1::Request::new(at_event_id.clone(), room_id.clone()),
)
.await?;
for pdu in remote_state_response.pdus.clone() {
match self
.services
.rooms
.event_handler
.parse_incoming_pdu(&pdu, Some(&room_version_rules))
.await
{
| Ok(t) => t,
| Err(e) => {
warn!("Could not parse PDU, ignoring: {e}");
continue;
},
};
}
info!("Going through room_state response PDUs");
for result in remote_state_response.pdus.iter().map(|pdu| {
self.services
.server_keys
.verify_event_json_no_fetch_add_event_id(pdu, &room_version_rules)
}) {
let Ok((event_id, value)) = result.await else {
continue;
};
let pdu = PduEvent::from_id_val(&event_id, value.clone()).map_err(|e| {
debug_error!(
"Invalid PDU in fetching remote room state PDUs response: {value:#?}"
);
err!(BadServerResponse(debug_error!("Invalid PDU in send_join response: {e:?}")))
})?;
self.services
.rooms
.outlier
.add_pdu_outlier(&event_id, &value);
if let Some(state_key) = &pdu.state_key {
let shortstatekey = self
.services
.rooms
.short
.get_or_create_shortstatekey(&pdu.kind.to_string().into(), state_key)
.await;
state.insert(shortstatekey, pdu.event_id.clone());
self.services
.rooms
.pdu_metadata
.clear_pdu_markers(pdu.event_id());
}
}
info!("Going through auth_chain response");
for result in remote_state_response.auth_chain.iter().map(|pdu| {
self.services
.server_keys
.verify_event_json_no_fetch_add_event_id(pdu, &room_version_rules)
}) {
let Ok((event_id, value)) = result.await else {
continue;
};
self.services
.rooms
.outlier
.add_pdu_outlier(&event_id, &value);
self.services
.rooms
.pdu_metadata
.clear_pdu_markers(&event_id);
}
info!("Resolving new room state");
let new_room_state = self
.services
.rooms
.event_handler
.resolve_state(&room_id, &room_version_rules, state)
.await?;
info!("Compressing new room state");
let HashSetCompressStateEvent {
shortstatehash: short_state_hash,
added,
removed,
} = self
.services
.rooms
.state_compressor
.save_state(room_id.clone().as_ref(), new_room_state)
.await?;
info!("Forcing new room state");
self.services
.rooms
.state
.force_state(room_id.clone().as_ref(), short_state_hash, added, removed, &state_lock)
.await?;
info!("Replacing forward extremities");
self.services
.rooms
.state
.replace_forward_extremities(
&room_id,
std::iter::once(at_event_id.as_ref()),
&state_lock,
)
.await;
info!("Updating joined counts for room");
self.services
.rooms
.state_cache
.update_joined_count(&room_id)
.await;
self.write_str("Successfully forced the room state from the requested remote server.")
.await
}
}
+35 -1
View File
@@ -1,11 +1,12 @@
use std::{fmt::Write, path::PathBuf, sync::Arc};
use conduwuit::{
Err, Result,
Err, Result, err,
utils::{stream::IterStream, time},
warn,
};
use futures::TryStreamExt;
use tracing_subscriber::EnvFilter;
impl crate::Context<'_> {
pub(super) async fn uptime(&self) -> Result {
@@ -234,4 +235,37 @@ impl crate::Context<'_> {
self.write_str(&info).await
}
pub(super) async fn change_log_level(&self, filter: Option<String>, reset: bool) -> Result {
let handles = &["console"];
if reset {
let old_filter_layer = EnvFilter::try_new(&self.services.server.config.log)
.map_err(|e| err!("Log level from config appears to be invalid now: {e}"))?;
self.services
.server
.log
.reload
.reload(&old_filter_layer, Some(handles))
.map_err(|e| {
err!("Failed to modify and reload the global tracing log level: {e}")
})?;
self.write_str("Successfully changed log level back to config value")
.await
} else {
let filter = filter.ok_or_else(|| err!("No log level was specified."))?;
let new_filter_layer = EnvFilter::try_new(filter)
.map_err(|e| err!("Invalid log level filter specified: {e}"))?;
self.services
.server
.log
.reload
.reload(&new_filter_layer, Some(handles))
.map_err(|e| {
err!("Failed to modify and reload the global tracing log level: {e}")
})?;
self.write_str("Successfully changed log level back to config value")
.await
}
}
}
+12
View File
@@ -58,4 +58,16 @@ pub enum ServerCommand {
/// Build information
BuildInfo,
/// Change tracing log level/filter on the fly
///
/// This accepts the same format as the `log` config option.
ChangeLogLevel {
/// Log level/filter
filter: Option<String>,
/// Resets the log level/filter to the one in your config
#[arg(short, long)]
reset: bool,
},
}
+5 -315
View File
@@ -1,19 +1,16 @@
use std::collections::{BTreeMap, HashSet};
use std::collections::BTreeMap;
use api::client::{
full_user_deactivate, leave_room, recreate_push_rules_and_return, remote_leave_room,
};
use api::client::{full_user_deactivate, leave_room, recreate_push_rules_and_return};
use conduwuit::{
Err, Result, debug_warn, info,
Err, Result, info,
matrix::{Event, pdu::PartialPdu},
utils::{self, ReadyExt},
utils::{self},
warn,
};
use futures::{FutureExt, StreamExt};
use lettre::Address;
use ruma::{
OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedServerName, OwnedUserId, ServerName,
UserId, assign,
OwnedEventId, OwnedRoomId, OwnedRoomOrAliasId, OwnedUserId, UserId, assign,
events::{
RoomAccountDataEventType,
room::{power_levels::RoomPowerLevelsEventContent, redaction::RoomRedactionEventContent},
@@ -28,7 +25,6 @@ use crate::{
};
const AUTO_GEN_PASSWORD_LENGTH: usize = 25;
const BULK_JOIN_REASON: &str = "Bulk force joining this room as initiated by the server admin.";
impl crate::Context<'_> {
pub(super) async fn list_users(
@@ -464,272 +460,6 @@ impl crate::Context<'_> {
.await
}
pub(super) async fn force_join_list_of_local_users(
&self,
room_id: OwnedRoomOrAliasId,
yes_i_want_to_do_this: bool,
) -> Result {
if self.body.len() < 2
|| !self.body[0].trim().starts_with("```")
|| self.body.last().unwrap_or(&"").trim() != "```"
{
return Err!("Expected code block in command body. Add --help for details.",);
}
if !yes_i_want_to_do_this {
return Err!(
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to \
force bulk join all specified local users.",
);
}
let server_admins = self.services.admin.get_admins().await;
if server_admins.is_empty() {
return Err!("There are no admins set for this server.");
}
let (room_id, servers) = self
.services
.rooms
.alias
.resolve_with_servers(&room_id, None)
.await?;
if !self
.services
.rooms
.state_cache
.server_in_room(self.services.globals.server_name(), &room_id)
.await
{
return Err!("We are not joined in this room.");
}
if !self
.services
.rooms
.state_cache
.room_members(&room_id)
.ready_any(|user_id| server_admins.contains(&user_id))
.await
{
return Err!("There is not a single server admin in the room.",);
}
let usernames = self
.body
.to_vec()
.drain(1..self.body.len().saturating_sub(1))
.collect::<Vec<_>>();
let mut user_ids: Vec<OwnedUserId> = Vec::with_capacity(usernames.len());
for username in usernames {
match parse_active_local_user_id(self.services, username).await {
| Ok(user_id) => {
// don't make the server service account join
if user_id == self.services.globals.server_user {
self.services
.admin
.send_text(&format!(
"{username} is the server service account, skipping over"
))
.await;
continue;
}
user_ids.push(user_id);
},
| Err(e) => {
self.services
.admin
.send_text(&format!(
"{username} is not a valid username, skipping over: {e}"
))
.await;
continue;
},
}
}
let mut failed_joins: usize = 0;
let mut successful_joins: usize = 0;
for user_id in user_ids {
match self
.services
.rooms
.membership
.join_room(&user_id, &room_id, Some(String::from(BULK_JOIN_REASON)), &servers)
.await
{
| Ok(_res) => {
successful_joins = successful_joins.saturating_add(1);
},
| Err(e) => {
debug_warn!(
"Failed force joining {user_id} to {room_id} during bulk join: {e}"
);
failed_joins = failed_joins.saturating_add(1);
},
}
}
self.write_str(&format!(
"{successful_joins} local users have been joined to {room_id}. {failed_joins} joins \
failed.",
))
.await
}
pub(super) async fn force_join_all_local_users(
&self,
room_id: OwnedRoomOrAliasId,
yes_i_want_to_do_this: bool,
) -> Result {
if !yes_i_want_to_do_this {
return Err!(
"You must pass the --yes-i-want-to-do-this-flag to ensure you really want to \
force bulk join all local users.",
);
}
let server_admins = self.services.admin.get_admins().await;
if server_admins.is_empty() {
return Err!("There are no admins set for this server.");
}
let (room_id, servers) = self
.services
.rooms
.alias
.resolve_with_servers(&room_id, None)
.await?;
if !self
.services
.rooms
.state_cache
.server_in_room(self.services.globals.server_name(), &room_id)
.await
{
return Err!("We are not joined in this room.");
}
if !self
.services
.rooms
.state_cache
.room_members(&room_id)
.ready_any(|user_id| server_admins.contains(&user_id))
.await
{
return Err!("There is not a single server admin in the room.",);
}
let mut failed_joins: usize = 0;
let mut successful_joins: usize = 0;
for user_id in &self
.services
.users
.stream_local_users()
.collect::<Vec<_>>()
.await
{
match self
.services
.rooms
.membership
.join_room(user_id, &room_id, Some(String::from(BULK_JOIN_REASON)), &servers)
.await
{
| Ok(_res) => {
successful_joins = successful_joins.saturating_add(1);
},
| Err(e) => {
debug_warn!(
"Failed force joining {user_id} to {room_id} during bulk join: {e}"
);
failed_joins = failed_joins.saturating_add(1);
},
}
}
self.write_str(&format!(
"{successful_joins} local users have been joined to {room_id}. {failed_joins} joins \
failed.",
))
.await
}
pub(super) async fn force_join_room(
&self,
user_id: String,
room_id: OwnedRoomOrAliasId,
via: Option<String>,
) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?;
let (room_id, mut servers) = self
.services
.rooms
.alias
.resolve_with_servers(&room_id, None)
.await?;
if let Some(via) = via.map(ServerName::parse).transpose()? {
servers.retain(|n| *n != via);
servers.insert(0, via);
}
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
self.services
.rooms
.membership
.join_room(&user_id, &room_id, None, &servers)
.await?;
self.write_str(&format!("{user_id} has been joined to {room_id}."))
.await
}
pub(super) async fn force_leave_room(
&self,
user_id: String,
room_id: OwnedRoomOrAliasId,
) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?;
let room_id = self.services.rooms.alias.resolve(&room_id).await?;
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
if !self
.services
.rooms
.state_cache
.is_joined(&user_id, &room_id)
.await
{
return Err!("{user_id} is not joined in the room");
}
leave_room(self.services, &user_id, &room_id, None)
.boxed()
.await?;
self.write_str(&format!("{user_id} has left {room_id}."))
.await
}
pub(super) async fn force_demote(
&self,
user_id: String,
@@ -943,46 +673,6 @@ impl crate::Context<'_> {
.await
}
pub(super) async fn force_leave_remote_room(
&self,
user_id: String,
room_id: OwnedRoomOrAliasId,
via: Option<String>,
) -> Result {
let user_id = parse_local_user_id(self.services, &user_id)?;
let (room_id, vias_raw) = self
.services
.rooms
.alias
.resolve_with_servers(
&room_id,
if let Some(v) = via.clone() {
Some(vec![ServerName::parse(v)?])
} else {
None
},
)
.await?;
assert!(
self.services.globals.user_is_local(&user_id),
"Parsed user_id must be a local user"
);
let mut vias: HashSet<OwnedServerName> = HashSet::new();
if let Some(via) = via {
vias.insert(ServerName::parse(via)?);
}
for server in vias_raw {
vias.insert(server);
}
remote_leave_room(self.services, &user_id, &room_id, None, vias)
.boxed()
.await?;
self.write_str(&format!("{user_id} successfully left {room_id} via remote server."))
.await
}
pub(super) async fn lock(&self, user_id: String) -> Result {
let user_id = parse_active_local_user_id(self.services, &user_id).await?;
-53
View File
@@ -193,32 +193,6 @@ pub enum UserCommand {
user_id: String,
},
/// Manually join a local user to a room.
ForceJoinRoom {
/// The user to join
user_id: String,
/// The room to join
room_id: OwnedRoomOrAliasId,
/// The server name to join via.
///
/// This server will always be tried first, however if more are
/// available, they may be tried after.
via: Option<String>,
},
/// Manually leave a local user from a room.
ForceLeaveRoom {
user_id: String,
room_id: OwnedRoomOrAliasId,
},
/// Manually leave a remote room for a local user.
ForceLeaveRemoteRoom {
user_id: String,
room_id: OwnedRoomOrAliasId,
via: Option<String>,
},
/// Forces the specified user to drop their power levels to the room
/// default, if their permissions allow and the auth check permits
ForceDemote {
@@ -265,33 +239,6 @@ pub enum UserCommand {
event_id: OwnedEventId,
},
/// Force joins a specified list of local users to join the specified
/// room.
///
/// Specify a codeblock of usernames.
///
/// At least 1 server admin must be in the room to reduce abuse.
///
/// Requires the `--yes-i-want-to-do-this` flag.
ForceJoinListOfLocalUsers {
room_id: OwnedRoomOrAliasId,
#[arg(long)]
yes_i_want_to_do_this: bool,
},
/// Force joins all local users to the specified room.
///
/// At least 1 server admin must be in the room to reduce abuse.
///
/// Requires the `--yes-i-want-to-do-this` flag.
ForceJoinAllLocalUsers {
room_id: OwnedRoomOrAliasId,
#[arg(long)]
yes_i_want_to_do_this: bool,
},
/// Resets the push-rules (notification settings) of the target user to the
/// server defaults.
ResetPushRules {
+1 -1
View File
@@ -214,7 +214,7 @@ pub async fn leave_room(
Ok(())
}
pub async fn remote_leave_room<S: ::std::hash::BuildHasher>(
pub async fn remote_leave_room<S: std::hash::BuildHasher>(
services: &Services,
user_id: &UserId,
room_id: &RoomId,
+4 -3
View File
@@ -167,10 +167,11 @@ migration!(stringify!($name) => $name)
// names, preventing users from signing in.
VersionBump(22),
migration!(fix_oauth_scope_names),
// Removes any extremities in roomid_pduleaves that we do not know about (and
// consequently should not reference).
// Removes any extremities in roomid_pduleaves that we do not know about
// (and consequently should not reference).
migration!(remove_unknown_extremities),
// Re-calculates extremities for any rooms that actually lack any extremities at all.
// Re-calculates extremities for any rooms that actually lack any
// extremities at all.
migration!(consistency_check_extremity_tracker),
]
};
@@ -382,7 +382,7 @@ impl super::Service {
/// returned the correct event.
/// Allows `fetch_and_handle_missing_events` to atomically fetch events from
/// multiple remotes in parallel.
async fn fetch_event_via(
pub async fn fetch_event_via(
&self,
remote: OwnedServerName,
event_id: OwnedEventId,
@@ -93,7 +93,7 @@ impl super::Service {
room_version_rules: Option<&RoomVersionRules>,
) -> Result<Parsed> {
let value = serde_json::from_str::<CanonicalJsonObject>(pdu.get()).map_err(|e| {
err!(BadServerResponse(debug_warn!("Error parsing incoming event {e:?}")))
err!(BadServerResponse(debug_warn!("Error parsing incoming event as JSON {e:?}")))
})?;
let event_type = value
.get("type")