mc-minder 0.5.4

A smart management suite for Minecraft servers(fabric) on Linux/Termux/Android
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use anyhow::{Context, Result};
use log::{debug, warn, info};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::process::ChildStdin;
use tokio::sync::Mutex;
use tokio::time::{timeout, Duration};

// ============================================================
// CommandSenderMode - Enum for different transport modes
// ============================================================

#[derive(Clone)]
#[allow(dead_code)]
pub enum CommandSenderMode {
    Rcon { host: String, port: u16, password: String },
    PooledRcon { host: String, port: u16, password: String },
    Stdin { stdin: std::sync::Arc<Mutex<ChildStdin>> },
}

pub struct CommandSender {
    mode: CommandSenderMode,
}

#[allow(dead_code)]
impl CommandSender {
    pub fn new(mode: CommandSenderMode) -> Self {
        Self { mode }
    }

    pub fn rcon(host: String, port: u16, password: String) -> Self {
        Self { mode: CommandSenderMode::Rcon { host, port, password } }
    }

    /// Create a pooled RCON sender that maintains a persistent connection.
    /// This is more efficient than creating a new connection per command.
    pub fn pooled_rcon(host: String, port: u16, password: String) -> Self {
        Self { mode: CommandSenderMode::PooledRcon { host, port, password } }
    }

    pub fn stdin(stdin: ChildStdin) -> Self {
        Self { mode: CommandSenderMode::Stdin { stdin: std::sync::Arc::new(Mutex::new(stdin)) } }
    }

    /// Send a command and return the response text (if available).
    /// For RCON, this returns the server's response to the command.
    /// For Stdin, this returns a confirmation string.
    pub async fn send_command(&mut self, command: &str) -> Result<String> {
        match &mut self.mode {
            CommandSenderMode::Rcon { host, port, password } => {
                RconCommandSender::new(host.clone(), *port, password.clone())
                    .send_command(command)
                    .await
            }
            CommandSenderMode::PooledRcon { host, port, password } => {
                PooledRconSender::new(host.clone(), *port, password.clone())
                    .send_command(command)
                    .await
            }
            CommandSenderMode::Stdin { stdin } => {
                StdinCommandSender::new(stdin.clone()).send_command(command).await
            }
        }
    }

    /// Send a command without caring about the response.
    /// Useful for fire-and-forget commands like `say` and `tellraw`.
    #[allow(dead_code)]
    pub async fn send_command_ignore_response(&mut self, command: &str) -> Result<()> {
        match self.send_command(command).await {
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    #[allow(dead_code)]
    pub fn name(&self) -> &'static str {
        match &self.mode {
            CommandSenderMode::Rcon { .. } => "RCON",
            CommandSenderMode::PooledRcon { .. } => "PooledRCON",
            CommandSenderMode::Stdin { .. } => "Stdin",
        }
    }
}

// ============================================================
// RconCommandSender - Single-shot RCON connection per command
// ============================================================

pub struct RconCommandSender {
    host: String,
    port: u16,
    password: String,
}

impl RconCommandSender {
    pub fn new(host: String, port: u16, password: String) -> Self {
        Self { host, port, password }
    }

    pub async fn send_command(&mut self, command: &str) -> Result<String> {
        const MAX_RETRIES: u32 = 3;

        for attempt in 1..=MAX_RETRIES {
            match self.execute_with_response(command).await {
                Ok(response) => {
                    debug!("[RconSender] Command sent successfully: {}", command);
                    return Ok(response);
                }
                Err(e) => {
                    warn!("[RconSender] Attempt {}/{} failed: {}", attempt, MAX_RETRIES, e);
                    if attempt < MAX_RETRIES {
                        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                    }
                }
            }
        }

        Err(anyhow::anyhow!(
            "[RconSender] Failed to send command after {} attempts: {}",
            MAX_RETRIES, command
        ))
    }

    async fn execute_with_response(&mut self, command: &str) -> Result<String> {
        use tokio::net::TcpStream;

        const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);

        let addr = format!("{}:{}", self.host, self.port);
        debug!("[RconSender] Connecting to RCON at {}", addr);

        let mut stream = timeout(CONNECT_TIMEOUT, TcpStream::connect(&addr))
            .await
            .context("RCON connection timeout")?
            .context(format!(
                "[RconSender] Failed to connect to RCON at {}. Please check:\n\
                 - enable-rcon=true\n\
                 - rcon.port={}\n\
                 - rcon.password=<password>",
                addr, self.port
            ))?;

        self.authenticate(&mut stream).await?;
        let response = self.send_packet(&mut stream, 1, 2, command).await?;

        Ok(response)
    }

    async fn authenticate(&self, stream: &mut tokio::net::TcpStream) -> Result<()> {
        const PACKET_TYPE_AUTH: i32 = 3;

        let payload_bytes = self.password.as_bytes();
        let length = 4 + 4 + payload_bytes.len() as i32 + 1;

        let mut buf = Vec::with_capacity(4 + length as usize);
        buf.extend_from_slice(&length.to_le_bytes());
        buf.extend_from_slice(&1_i32.to_le_bytes());
        buf.extend_from_slice(&PACKET_TYPE_AUTH.to_le_bytes());
        buf.extend_from_slice(payload_bytes);
        buf.push(0);

        stream.write_all(&buf).await.context("[RconSender] Auth write failed")?;
        stream.flush().await.context("[RconSender] Auth flush failed")?;

        let mut len_buf = [0u8; 4];
        stream.read_exact(&mut len_buf).await.context("[RconSender] Auth read length failed")?;
        let resp_len = i32::from_le_bytes(len_buf);

        if resp_len < 10 {
            return Err(anyhow::anyhow!("[RconSender] Invalid auth response length: {}", resp_len));
        }

        let mut data = vec![0u8; resp_len as usize];
        stream.read_exact(&mut data).await.context("[RconSender] Auth read data failed")?;

        let id = i32::from_le_bytes([data[0], data[1], data[2], data[3]]);
        if id == -1 {
            return Err(anyhow::anyhow!("[RconSender] RCON authentication rejected"));
        }

        debug!("[RconSender] Authenticated successfully");
        Ok(())
    }

    async fn send_packet(&self, stream: &mut tokio::net::TcpStream, packet_id: i32, packet_type: i32, payload: &str) -> Result<String> {
        const READ_TIMEOUT: Duration = Duration::from_secs(10);

        let payload_bytes = payload.as_bytes();
        let length = 4 + 4 + payload_bytes.len() as i32 + 1;

        let mut buf = Vec::with_capacity(4 + length as usize);
        buf.extend_from_slice(&length.to_le_bytes());
        buf.extend_from_slice(&packet_id.to_le_bytes());
        buf.extend_from_slice(&packet_type.to_le_bytes());
        buf.extend_from_slice(payload_bytes);
        buf.push(0);

        let write_result = timeout(Duration::from_secs(10), stream.write_all(&buf))
            .await
            .context("[RconSender] Write timeout")?;
        write_result.context("[RconSender] Write failed")?;

        stream.flush().await.context("[RconSender] Flush failed")?;

        let mut len_buf = [0u8; 4];
        let read_result = timeout(READ_TIMEOUT, stream.read_exact(&mut len_buf))
            .await
            .context("[RconSender] Read timeout")?;
        read_result.context("[RconSender] Read length failed")?;

        let resp_len = i32::from_le_bytes(len_buf);
        let mut response = String::new();

        if resp_len >= 10 {
            let mut data = vec![0u8; resp_len as usize];
            let read_result = timeout(READ_TIMEOUT, stream.read_exact(&mut data))
                .await
                .context("[RconSender] Read timeout")?;
            read_result.context("[RconSender] Read data failed")?;

            // Extract response text (skip 8 bytes: request_id + packet_type, remove trailing null)
            if data.len() > 9 {
                response = String::from_utf8_lossy(&data[8..data.len().saturating_sub(1)]).into_owned();
            }
        }

        debug!("[RconSender] Packet sent: id={}, type={}, cmd={}", packet_id, packet_type, payload);
        Ok(response)
    }
}

// ============================================================
// PooledRconSender - Persistent RCON connection with auto-reconnect
// ============================================================

pub struct PooledRconSender {
    host: String,
    port: u16,
    password: String,
    stream: Option<tokio::net::TcpStream>,
}

impl PooledRconSender {
    pub fn new(host: String, port: u16, password: String) -> Self {
        Self {
            host,
            port,
            password,
            stream: None,
        }
    }

    pub async fn send_command(&mut self, command: &str) -> Result<String> {
        const MAX_RETRIES: u32 = 3;

        for attempt in 1..=MAX_RETRIES {
            // Try existing connection first
            if self.stream.is_some() {
                match self.execute_command(command).await {
                    Ok(response) => return Ok(response),
                    Err(e) => {
                        // Connection lost, reconnect
                        self.stream = None;
                        warn!("[PooledRconSender] Connection lost, reconnect attempt {}/{}: {}", attempt, MAX_RETRIES, e);
                        // Fall through to reconnect attempt
                    }
                }
            }

            // No connection or lost connection, establish new one
            if let Err(e) = self.connect().await {
                warn!("[PooledRconSender] Connect attempt {}/{} failed: {}", attempt, MAX_RETRIES, e);
                if attempt < MAX_RETRIES {
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
                continue;
            }

            // Send command on fresh connection
            match self.execute_command(command).await {
                Ok(response) => return Ok(response),
                Err(e) => {
                    warn!("[PooledRconSender] Command failed on attempt {}: {}", attempt, e);
                    self.stream = None;
                }
            }
        }

        Err(anyhow::anyhow!(
            "[PooledRconSender] Failed after {} attempts: {}",
            MAX_RETRIES, command
        ))
    }

    async fn connect(&mut self) -> Result<()> {
        use tokio::net::TcpStream;

        const PACKET_TYPE_AUTH: i32 = 3;
        const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);

        let addr = format!("{}:{}", self.host, self.port);
        debug!("[PooledRconSender] Connecting to {}", addr);

        let mut stream = timeout(CONNECT_TIMEOUT, TcpStream::connect(&addr))
            .await
            .context(format!("[PooledRconSender] Connection timeout to {}", addr))?
            .context(format!("[PooledRconSender] Failed to connect to RCON at {}", addr))?;

        // Authenticate
        let payload_bytes = self.password.as_bytes();
        let length = 4 + 4 + payload_bytes.len() as i32 + 1;

        let mut buf = Vec::with_capacity(4 + length as usize);
        buf.extend_from_slice(&length.to_le_bytes());
        buf.extend_from_slice(&1_i32.to_le_bytes());
        buf.extend_from_slice(&PACKET_TYPE_AUTH.to_le_bytes());
        buf.extend_from_slice(payload_bytes);
        buf.push(0);

        stream.write_all(&buf).await.context("[PooledRconSender] Auth write failed")?;
        stream.flush().await.context("[PooledRconSender] Auth flush failed")?;

        // Read auth response
        let mut len_buf = [0u8; 4];
        stream.read_exact(&mut len_buf).await.context("[PooledRconSender] Auth read length failed")?;
        let resp_len = i32::from_le_bytes(len_buf);

        if resp_len < 10 {
            return Err(anyhow::anyhow!("[PooledRconSender] Invalid auth response length: {}", resp_len));
        }

        let mut data = vec![0u8; resp_len as usize];
        stream.read_exact(&mut data).await.context("[PooledRconSender] Auth read data failed")?;

        let id = i32::from_le_bytes([data[0], data[1], data[2], data[3]]);
        if id == -1 {
            return Err(anyhow::anyhow!("[PooledRconSender] RCON authentication rejected"));
        }

        debug!("[PooledRconSender] Authenticated successfully to {}", addr);
        self.stream = Some(stream);
        Ok(())
    }

    async fn execute_command(&mut self, command: &str) -> Result<String> {
        const PACKET_TYPE_COMMAND: i32 = 2;

        let stream = self.stream.as_mut()
            .ok_or_else(|| anyhow::anyhow!("[PooledRconSender] No connection"))?;

        // Send command packet
        let payload_bytes = command.as_bytes();
        let length = 4 + 4 + payload_bytes.len() as i32 + 1;

        let mut buf = Vec::with_capacity(4 + length as usize);
        buf.extend_from_slice(&length.to_le_bytes());
        buf.extend_from_slice(&1_i32.to_le_bytes());
        buf.extend_from_slice(&PACKET_TYPE_COMMAND.to_le_bytes());
        buf.extend_from_slice(payload_bytes);
        buf.push(0);

        let write_result = timeout(Duration::from_secs(10), stream.write_all(&buf)).await
            .context("[PooledRconSender] Write timeout")?;
        write_result.context("[PooledRconSender] Write failed")?;
        stream.flush().await.context("[PooledRconSender] Flush failed")?;

        // Read response
        let mut len_buf = [0u8; 4];
        let read_result = timeout(Duration::from_secs(10), stream.read_exact(&mut len_buf)).await
            .context("[PooledRconSender] Read timeout")?;
        read_result.context("[PooledRconSender] Read length failed")?;

        let resp_len = i32::from_le_bytes(len_buf);
        let mut response = String::new();

        if resp_len >= 10 {
            let mut data = vec![0u8; resp_len as usize];
            let read_result = timeout(Duration::from_secs(10), stream.read_exact(&mut data)).await
                .context("[PooledRconSender] Read timeout")?;
            read_result.context("[PooledRconSender] Read data failed")?;

            // Extract response text (skip 8 bytes: request_id + packet_type)
            if data.len() > 9 {
                response = String::from_utf8_lossy(&data[8..data.len().saturating_sub(1)]).into_owned();
            }
        }

        debug!("[PooledRconSender] Command sent: {}", command);
        Ok(response)
    }
}

// ============================================================
// StdinCommandSender - Sends commands via process stdin
// ============================================================

pub struct StdinCommandSender {
    stdin: std::sync::Arc<Mutex<ChildStdin>>,
}

impl StdinCommandSender {
    pub fn new(stdin: std::sync::Arc<Mutex<ChildStdin>>) -> Self {
        Self { stdin }
    }

    pub async fn send_command(&mut self, command: &str) -> Result<String> {
        let mut stdin = self.stdin.lock().await;
        stdin.write_all(command.as_bytes()).await.context("[StdinSender] Write failed")?;
        stdin.write_all(b"\n").await.context("[StdinSender] Newline failed")?;
        stdin.flush().await.context("[StdinSender] Flush failed")?;
        debug!("[StdinSender] Command sent: {}", command);
        Ok(format!("Command sent: {}", command))
    }
}

// ============================================================
// MultiCommandSender - Tries multiple senders in order
// ============================================================

pub struct MultiCommandSender {
    senders: Vec<CommandSender>,
}

impl MultiCommandSender {
    pub fn new() -> Self {
        Self { senders: Vec::new() }
    }

    pub fn add_sender(&mut self, sender: CommandSender) {
        self.senders.push(sender);
    }

    /// Send a command through the first available sender.
    /// Returns the response text from the first successful sender.
    pub async fn send_command(&mut self, command: &str) -> Result<String> {
        if self.senders.is_empty() {
            return Err(anyhow::anyhow!("[MultiSender] No command senders available"));
        }

        let mut last_error = None;
        for sender in &mut self.senders {
            match sender.send_command(command).await {
                Ok(response) => {
                    info!("[MultiSender] Command sent via {}: {}", sender.name(), command);
                    return Ok(response);
                }
                Err(e) => {
                    warn!("[MultiSender] {} failed: {}", sender.name(), e);
                    last_error = Some(e);
                }
            }
        }

        Err(last_error.unwrap_or_else(|| anyhow::anyhow!("[MultiSender] All senders failed")))
    }

    /// Send a command without caring about the response text.
    pub async fn send_command_ignore_response(&mut self, command: &str) -> Result<()> {
        self.send_command(command).await.map(|_| ())
    }

    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.senders.is_empty()
    }
}

impl Default for MultiCommandSender {
    fn default() -> Self {
        Self::new()
    }
}