1mod attach;
2pub mod console;
3pub mod context;
4pub mod create;
5mod execute;
6mod grant;
7mod notices;
8mod processor;
9mod register;
10mod respond;
11#[cfg(test)]
12mod tests;
13
14use std::{
15 collections::BTreeMap,
16 sync::{Arc, Mutex as StdMutex, RwLock as StdRwLock},
17 time::Instant,
18};
19
20use async_trait::async_trait;
21pub use context::Context;
22pub use create::create_admin_room;
23use futures::TryFutureExt;
24use ruma::{
25 OwnedEventId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, RoomId, RoomOrAliasId, UserId,
26};
27use tokio::sync::mpsc::{Receiver, Sender, channel};
28use tuwunel_core::{
29 Err, Result, debug, err, error::default_log, implement, utils::ReadyExt, warn,
30};
31use tuwunel_matrix::{Event, event::MsgType};
32
33use crate::rooms::state::RoomMutexGuard;
34
35pub struct Service {
36 services: Arc<crate::services::OnceServices>,
37 queue: StdRwLock<Queue>,
38 pub command: StdRwLock<Option<Arc<dyn Command>>>,
39 pub admin_alias: OwnedRoomAliasId,
40 register_nonces: StdMutex<BTreeMap<String, Instant>>,
41 #[cfg(feature = "console")]
42 pub console: Arc<console::Console>,
43}
44
45enum Queue {
51 Pending,
53
54 Open(Sender<CommandInput>),
56
57 Closed,
59}
60
61#[derive(Clone, Debug, Default)]
68pub struct CommandInput {
69 pub command: String,
71
72 pub reply_id: Option<OwnedEventId>,
74
75 pub sender: Option<OwnedUserId>,
77}
78
79#[async_trait]
81pub trait Command: Send + Sync + 'static {
82 fn clap(&self) -> clap::Command;
85
86 async fn dispatch(&self, matches: clap::ArgMatches, context: &Context<'_>) -> Result;
88}
89
90pub type ProcessorResult = Result<Option<CommandOutput>, CommandOutput>;
95
96pub enum CommandOutput {
99 Markdown(String),
100 Plain(String),
101}
102
103impl From<String> for CommandInput {
104 fn from(command: String) -> Self { Self { command, ..Default::default() } }
105}
106
107impl From<&str> for CommandInput {
108 fn from(command: &str) -> Self { command.to_owned().into() }
109}
110
111impl CommandOutput {
112 #[inline]
113 #[must_use]
114 pub fn as_str(&self) -> &str {
115 match self {
116 | Self::Markdown(text) | Self::Plain(text) => text,
117 }
118 }
119}
120
121const COMMAND_QUEUE_LIMIT: usize = 512;
123
124#[async_trait]
125impl crate::Service for Service {
126 fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
127 Ok(Arc::new(Self {
128 services: args.services.clone(),
129 queue: StdRwLock::new(Queue::Pending),
130 command: StdRwLock::new(None),
131 admin_alias: OwnedRoomAliasId::try_from(format!("#admins:{}", args.server.name))
132 .expect("#admins:server_name is valid alias name"),
133 register_nonces: StdMutex::new(BTreeMap::new()),
134 #[cfg(feature = "console")]
135 console: console::Console::new(args),
136 }))
137 }
138
139 async fn worker(self: Arc<Self>) -> Result {
140 let mut signals = self.services.server.signal.subscribe();
141 let Some(mut receiver) = self
142 .queue
143 .write()
144 .expect("locked for writing")
145 .open()
146 else {
147 return Ok(());
148 };
149
150 self.console_auto_start().await;
151
152 loop {
153 tokio::select! {
154 command = receiver.recv() => match command {
155 Some(command) => self.handle_command(command).await,
156 None => break,
157 },
158 sig = signals.recv() => if let Ok(sig) = sig {
159 self.handle_signal(sig).await;
160 },
161 }
162 }
163
164 self.interrupt().await;
166 self.console_auto_stop().await;
167
168 Ok(())
169 }
170
171 async fn interrupt(&self) {
172 #[cfg(feature = "console")]
173 self.console.interrupt();
174
175 *self.queue.write().expect("locked for writing") = Queue::Closed;
176 }
177
178 fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
179}
180
181#[implement(Queue)]
186fn open(&mut self) -> Option<Receiver<CommandInput>> {
187 match self {
188 | Self::Closed => None,
189 | Self::Pending | Self::Open(_) => {
190 let (sender, receiver) = channel(COMMAND_QUEUE_LIMIT);
191
192 *self = Self::Open(sender);
193 Some(receiver)
194 },
195 }
196}
197
198impl Service {
199 pub async fn command(&self, input: CommandInput) -> Result {
205 let Some(queue) = self
206 .queue
207 .read()
208 .expect("locked for reading")
209 .sender()
210 else {
211 return Err!("Admin command queue unavailable.");
212 };
213
214 queue
215 .send(input)
216 .map_err(|e| err!("Failed to enqueue admin command: {e:?}"))
217 .await
218 }
219
220 pub async fn command_in_place(&self, input: CommandInput) -> ProcessorResult {
226 self.process_command(&input).await
227 }
228
229 pub fn complete_command(&self, command: &str) -> Option<String> {
232 self.command
233 .read()
234 .expect("locked for reading")
235 .as_ref()
236 .map(|root| processor::complete(root.clap(), command))
237 }
238
239 async fn handle_signal(&self, sig: &'static str) {
240 if sig == execute::SIGNAL {
241 self.signal_execute().await.ok();
242 }
243
244 #[cfg(feature = "console")]
245 self.console.handle_signal(sig);
246 }
247
248 async fn handle_command(&self, command: CommandInput) {
249 match self.process_command(&command).await {
250 | Ok(None) => debug!("Command successful with no response"),
251 | Err(output) | Ok(Some(output)) => self
252 .handle_response(output, command.reply_id.as_deref())
253 .await
254 .unwrap_or_else(default_log),
255 }
256 }
257
258 async fn process_command(&self, command: &CommandInput) -> ProcessorResult {
259 let root = self
260 .command
261 .read()
262 .expect("locked for reading")
263 .clone()
264 .expect("Admin module is not loaded");
265
266 processor::handle_command(root, Arc::clone(self.services.get()), command).await
267 }
268
269 pub async fn user_is_admin(&self, user_id: &UserId) -> bool {
271 if user_id == self.services.globals.server_user {
272 return true;
273 }
274
275 let Ok(admin_room) = self.get_admin_room().await else {
276 return false;
277 };
278
279 self.services
280 .state_cache
281 .is_joined(user_id, &admin_room)
282 .await
283 }
284
285 pub async fn user_is_last_admin(&self, user_id: &UserId) -> bool {
293 let server_user: &UserId = &self.services.globals.server_user;
294 if user_id == server_user {
295 return false;
296 }
297
298 let Ok(admin_room) = self.get_admin_room().await else {
299 return false;
300 };
301
302 if !self
303 .services
304 .state_cache
305 .is_joined(user_id, &admin_room)
306 .await
307 {
308 return false;
309 }
310
311 !self
312 .services
313 .state_cache
314 .active_local_users_in_room(&admin_room)
315 .ready_any(|member| member != user_id && member != server_user)
316 .await
317 }
318
319 pub async fn get_admin_room(&self) -> Result<OwnedRoomId> {
324 let room_id = self
325 .services
326 .alias
327 .resolve_local_alias(&self.admin_alias)
328 .await?;
329
330 self.services
331 .state_cache
332 .is_joined(&self.services.globals.server_user, &room_id)
333 .await
334 .then_some(room_id)
335 .ok_or_else(|| err!(Request(NotFound("Admin user not joined to admin room"))))
336 }
337
338 pub async fn get_report_room(&self) -> Result<OwnedRoomId> {
342 let Some(report_room) = self
343 .services
344 .server
345 .config
346 .admin
347 .report_room
348 .as_ref()
349 else {
350 return self.get_admin_room().await;
351 };
352
353 match self.resolve_report_room(report_room).await {
354 | Ok(room_id) => Ok(room_id),
355 | Err(e) => {
356 warn!(%report_room, error = %e, "Falling back to the admin room for reports");
357 self.get_admin_room().await
358 },
359 }
360 }
361
362 async fn resolve_report_room(&self, report_room: &RoomOrAliasId) -> Result<OwnedRoomId> {
363 let room_id = self
364 .services
365 .alias
366 .maybe_resolve(report_room)
367 .await?;
368
369 self.services
370 .state_cache
371 .is_joined(&self.services.globals.server_user, &room_id)
372 .await
373 .then_some(room_id)
374 .ok_or_else(|| err!("server user is not joined to the configured report room"))
375 }
376
377 pub async fn is_admin_command<Pdu>(&self, event: &Pdu, body: &str) -> bool
385 where
386 Pdu: Event,
387 {
388 let body = body.trim_start();
389
390 let is_escape = body.starts_with('\\');
392 let is_public_escape = is_escape
393 && body
394 .trim_start_matches('\\')
395 .starts_with("!admin");
396
397 let server_user = &self.services.globals.server_user;
399 let is_public_prefix =
400 body.starts_with("!admin") || body.starts_with(server_user.as_str());
401
402 if !is_public_escape && !is_public_prefix {
404 return false;
405 }
406
407 let user_is_local = self
408 .services
409 .globals
410 .user_is_local(event.sender());
411
412 if is_public_escape && !user_is_local {
414 return false;
415 }
416
417 if is_public_escape && !self.services.server.config.admin.escape_commands {
419 return false;
420 }
421
422 if event.msgtype() != Some(MsgType::Text) {
425 return false;
426 }
427
428 if is_public_prefix && !self.is_admin_room(event.room_id()).await {
430 return false;
431 }
432
433 if !self.user_is_admin(event.sender()).await {
435 return false;
436 }
437
438 let emergency_password_set = self
441 .services
442 .server
443 .config
444 .authentication
445 .emergency_password
446 .is_some();
447
448 let from_server = event.sender() == server_user && !emergency_password_set;
449 if from_server && self.is_admin_room(event.room_id()).await {
450 return false;
451 }
452
453 true
455 }
456
457 #[must_use]
458 pub async fn is_admin_room(&self, room_id_: &RoomId) -> bool {
459 self.get_admin_room()
460 .map_ok(|room_id| room_id == room_id_)
461 .await
462 .unwrap_or(false)
463 }
464}
465
466#[implement(Queue)]
467#[inline]
468fn sender(&self) -> Option<Sender<CommandInput>> {
469 match self {
470 | Self::Open(sender) => Some(sender.clone()),
471 | Self::Pending | Self::Closed => None,
472 }
473}
474
475#[implement(Service)]
482pub async fn lock_admin_room(&self) -> Option<RoomMutexGuard> {
483 let admin_room = self.get_admin_room().await.ok()?;
484
485 self.services
486 .state
487 .mutex
488 .lock(&admin_room)
489 .await
490 .into()
491}