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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Ts3 query library  
//! Small, bare-metal ts query lib without any callback support currently.
//!
//! # Examples
//! Simple auth + clients of a server group
//! ```rust,no_run
//! use ts3_query::*;
//!
//! # fn main() -> Result<(),Ts3Error> {
//! let mut client = QueryClient::new("localhost:10011")?;
//!
//! client.login("serveradmin", "password")?;
//! client.select_server_by_port(9987)?;
//!
//! let group_clients = client.get_servergroup_client_list(7)?;
//! println!("Got clients in group 7: {:?}",group_clients);
//!
//! client.logout()?;
//! # Ok(())
//! # }
//!
//! ```
//!
//! Using the raw interface for setting client descriptions.
//! ```rust,no_run
//! use ts3_query::*;
//!
//! # fn main() -> Result<(),Ts3Error> {
//! let mut client = QueryClient::new("localhost:10011")?;
//!
//! client.login("serveradmin", "password")?;
//! client.select_server_by_port(9987)?;
//!
//! // escape things like string args, not required for clid
//! // as it's not user input/special chars in this case
//! let cmd = format!("clientedit clid={} client_description={}",
//!  7, raw::escape_arg("Some Description!")
//! );
//! // we don't expect any value returned
//! let _ = client.raw_command(&cmd)?;
//!
//! client.logout()?;
//! # Ok(())
//! # }
//! ```
//!
//! Raw interface example retrieving online client names
//! ```rust,no_run
//! use ts3_query::*;
//! use std::collections::HashSet;
//! 
//! # fn main() -> Result<(),Ts3Error> {
//! let mut client = QueryClient::new("localhost:10011")?;
//! 
//! client.login("serveradmin", "password")?;
//! client.select_server_by_port(9987)?;
//! 
//! let res = raw::parse_multi_hashmap(client.raw_command("clientlist")?, false);
//! let names = res
//!     .into_iter()
//!     .map(|e| e.get("client_nickname").map(raw::unescape_val)
//!      // may want to catch this in a real application
//!         .unwrap())
//!     .collect::<HashSet<String>>();
//! println!("{:?}",names);
//! client.logout()?;
//! # Ok(())
//! # }
//! ```
use snafu::{Backtrace, OptionExt, ResultExt, Snafu};
use std::collections::HashMap;
use std::fmt::{Debug, Write as FmtWrite};
use std::io::{self, BufRead, BufReader, Write};
use std::net::{Shutdown, TcpStream, ToSocketAddrs};
use std::string::FromUtf8Error;
use std::time::Duration;

pub mod raw;
use io::Read;
use raw::*;

#[derive(Snafu, Debug)]
pub enum Ts3Error {
    /// Error on response conversion with invalid utf8 data
    #[snafu(display("Input was invalid UTF-8: {}", source))]
    Utf8Error { source: FromUtf8Error },
    /// Catch-all IO error, contains optional context
    #[snafu(display("IO Error: {}{}, kind: {:?}", context, source,source.kind()))]
    Io {
        /// Context of action, empty per default.
        ///
        /// Please use a format like `"reading connection: "`
        context: &'static str,
        source: io::Error,
    },
    /// Reached EOF reading response, server closed connection / timeout.
    #[snafu(display("IO Error: Connection closed"))]
    ConnectionClosed { backtrace: Backtrace },
    #[snafu(display("No valid socket address provided."))]
    InvalidSocketAddress { backtrace: Backtrace },
    /// Invalid response error. Server returned unexpected data.
    #[snafu(display("Received invalid response, {}{:?}", context, data))]
    InvalidResponse {
        /// Context of action, empty per default.
        ///
        /// Please use a format like `"expected XY, got: "`
        context: &'static str,
        data: String,
    },
    /// TS3-Server error response
    #[snafu(display("Server responded with error: {}", response))]
    ServerError {
        response: ErrorResponse,
        backtrace: Backtrace,
    },
    /// Maximum amount of response bytes/lines reached, DDOS limit prevented further data read.
    ///
    /// This will probably cause the current connection to become invalid due to remaining data in the connection.
    #[snafu(display("Invalid response, DDOS limit reached: {:?}", response))]
    ResponseLimit {
        response: Vec<String>,
        backtrace: Backtrace,
    },
}

impl Ts3Error {
    /// Returns true if the error is of kind ServerError
    pub fn is_error_response(&self) -> bool {
        match self {
            Ts3Error::ServerError { .. } => true,
            _ => false,
        }
    }
    /// Returns the [`ErrorResponse`](ErrorResponse) if existing.
    pub fn error_response(&self) -> Option<&ErrorResponse> {
        match self {
            Ts3Error::ServerError { response, .. } => Some(response),
            _ => None,
        }
    }
}

impl From<io::Error> for Ts3Error {
    fn from(error: io::Error) -> Self {
        Ts3Error::Io {
            context: "",
            source: error,
        }
    }
}

/// Server error response
#[derive(Debug)]
pub struct ErrorResponse {
    /// Error ID
    pub id: usize,
    /// Error message
    pub msg: String,
}

impl std::fmt::Display for ErrorResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Error code {}, msg: {}", self.id, self.msg)
    }
}

/// Ts3 Query client with active connection
pub struct QueryClient {
    rx: BufReader<TcpStream>,
    tx: TcpStream,
    limit_lines: usize,
    limit_lines_bytes: u64,
}

const LIMIT_READ_LINES: usize = 100;
const LIMIT_LINE_BYTES: u64 = 64_000;

type Result<T> = ::std::result::Result<T, Ts3Error>;

impl Drop for QueryClient {
    fn drop(&mut self) {
        self.quit();
        let _ = self.tx.shutdown(Shutdown::Both);
    }
}

impl QueryClient {
    /// Create new query connection
    pub fn new<A: ToSocketAddrs>(addr: A) -> Result<Self> {
        let (rx, tx) = Self::new_inner(addr, None, None)?;

        Ok(Self {
            rx,
            tx,
            limit_lines: LIMIT_READ_LINES,
            limit_lines_bytes: LIMIT_LINE_BYTES,
        })
    }

    /// Create new query connection with timeouts
    ///
    /// `t_connect` is used for connection, `timeout` for read/write operations
    pub fn with_timeout<A: ToSocketAddrs>(
        addr: A,
        t_connect: Option<Duration>,
        timeout: Option<Duration>,
    ) -> Result<Self> {
        let (rx, tx) = Self::new_inner(addr, timeout, t_connect)?;

        Ok(Self {
            rx,
            tx,
            limit_lines: LIMIT_READ_LINES,
            limit_lines_bytes: LIMIT_LINE_BYTES,
        })
    }

    /// Set new maximum amount of lines to read per response, until DoS protection triggers.
    pub fn limit_lines(&mut self, limit: usize) {
        self.limit_lines = limit;
    }

    /// Set new maximum amount of bytes per line to read until DoS protection triggers.
    pub fn limit_line_bytes(&mut self, limit: u64) {
        self.limit_lines_bytes = limit;
    }

    /// Rename this client, performs `clientupdate client_nickname` escaping the name
    pub fn rename(&mut self, name: &str) -> Result<()> {
        writeln!(
            &mut self.tx,
            "clientupdate client_nickname={}",
            escape_arg(name)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Update this clients description
    pub fn update_description(&mut self, descr: &str) -> Result<()> {
        write!(
            &mut self.tx,
            "clientupdate CLIENT_DESCRIPTION={}",
            escape_arg(descr)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Send quit command, does not close the socket, not to be exposed
    fn quit(&mut self) {
        let _ = writeln!(&mut self.tx, "quit");
    }

    /// Inner new-function that handles greeting etc
    fn new_inner<A: ToSocketAddrs>(
        addr: A,
        timeout: Option<Duration>,
        conn_timeout: Option<Duration>,
    ) -> Result<(BufReader<TcpStream>, TcpStream)> {
        let addr = addr
            .to_socket_addrs()
            .context(Io {
                context: "invalid socket address",
            })?
            .next()
            .context(InvalidSocketAddress {})?;
        let stream = if let Some(dur) = conn_timeout {
            TcpStream::connect_timeout(&addr, dur).context(Io {
                context: "while connecting: ",
            })?
        } else {
            TcpStream::connect(addr).context(Io {
                context: "while connecting: ",
            })?
        };

        stream.set_write_timeout(timeout).context(Io {
            context: "setting write timeout: ",
        })?;
        stream.set_read_timeout(timeout).context(Io {
            context: "setting read timeout: ",
        })?;

        stream.set_nodelay(true).context(Io {
            context: "setting nodelay: ",
        })?;

        let mut reader = BufReader::new(stream.try_clone().context(Io {
            context: "splitting connection: ",
        })?);

        // read server type token
        let mut buffer = Vec::new();
        reader.read_until(b'\r', &mut buffer).context(Io {
            context: "reading response: ",
        })?;

        buffer.clear();
        if let Err(e) = reader.read_until(b'\r', &mut buffer) {
            use std::io::ErrorKind::*;
            match e.kind() {
                TimedOut | WouldBlock => (), // ignore no greeting
                _ => return Err(e.into()),
            }
        }

        Ok((reader, stream))
    }

    /// Perform a raw command, returns its response as raw value. (No unescaping is performed.)
    ///
    /// You need to escape the command properly.
    pub fn raw_command(&mut self, command: &str) -> Result<Vec<String>> {
        writeln!(&mut self.tx, "{}", command)?;
        let v = self.read_response()?;
        Ok(v)
    }

    /// Performs whoami
    ///
    /// Returns a hashmap of entries. Values are unescaped if set.
    pub fn whoami(&mut self, unescape: bool) -> Result<HashMap<String, String>> {
        writeln!(&mut self.tx, "whoami")?;
        let v = self.read_response()?;
        Ok(parse_hashmap(v, unescape))
    }

    /// Logout
    pub fn logout(&mut self) -> Result<()> {
        writeln!(&mut self.tx, "logout")?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Login with provided data
    ///
    /// On drop queryclient issues a logout
    pub fn login(&mut self, user: &str, password: &str) -> Result<()> {
        writeln!(
            &mut self.tx,
            "login {} {}",
            escape_arg(user),
            escape_arg(password)
        )?;

        let _ = self.read_response()?;

        Ok(())
    }

    /// Select server to perform commands on, by port
    pub fn select_server_by_port(&mut self, port: u16) -> Result<()> {
        writeln!(&mut self.tx, "use port={}", port)?;

        let _ = self.read_response()?;
        Ok(())
    }

    /// Create file directory in channel, has to be a valid path starting with `/`
    ///
    /// Performs ftcreatedir
    pub fn create_dir(&mut self, cid: usize, path: &str) -> Result<()> {
        writeln!(
            &mut self.tx,
            "ftcreatedir cid={} cpw= dirname={}",
            cid,
            escape_arg(path)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Delete File/Folder in channel, acts recursive on folders
    ///
    /// Example: `/My Directory` deletes everything inside that directory.
    ///
    /// Performs ftdeletefile
    pub fn delete_file(&mut self, cid: usize, path: &str) -> Result<()> {
        writeln!(
            &mut self.tx,
            "ftdeletefile cid={} cpw= name={}",
            cid,
            escape_arg(path)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Low-cost connection check
    ///
    /// Performs whoami command without parsing
    pub fn ping(&mut self) -> Result<()> {
        writeln!(&mut self.tx, "whoami")?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Select server to perform commands on, by server id
    pub fn select_server_by_id(&mut self, sid: usize) -> Result<()> {
        writeln!(&mut self.tx, "use sid={}", sid)?;

        let _ = self.read_response()?;
        Ok(())
    }

    /// Performs servergroupdelclient
    pub fn server_group_del_clients(&mut self, group: usize, cldbid: &[usize]) -> Result<()> {
        if cldbid.is_empty() {
            return Ok(());
        }
        writeln!(
            &mut self.tx,
            "servergroupdelclient sgid={} {}",
            group,
            Self::format_cldbids(cldbid)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Performs servergroupaddclient
    pub fn server_group_add_clients(&mut self, group: usize, cldbid: &[usize]) -> Result<()> {
        if cldbid.is_empty() {
            return Ok(());
        }
        let v = Self::format_cldbids(cldbid);
        writeln!(&mut self.tx, "servergroupaddclient sgid={} {}", group, v)?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Turn a list of client-db-ids into a list of cldbid=X
    fn format_cldbids(it: &[usize]) -> String {
        // would need itertools for format_with

        let mut res = String::new();
        let mut it = it.iter();
        if let Some(n) = it.next() {
            write!(res, "cldbid={}", n).unwrap();
        }
        for n in it {
            write!(res, "|cldbid={}", n).unwrap();
        }
        res
    }

    /// Read response and check error line
    fn read_response(&mut self) -> Result<Vec<String>> {
        let mut result: Vec<String> = Vec::new();
        let mut lr = (&mut self.rx).take(self.limit_lines_bytes);
        for _ in 0..self.limit_lines {
            let mut buffer = Vec::new();
            // damn cargo fmt..
            if lr.read_until(b'\r', &mut buffer).context(Io {
                context: "reading response: ",
            })? == 0
            {
                return ConnectionClosed {}.fail();
            }
            // we read until \r or max-read limit
            if buffer.ends_with(&[b'\r']) {
                buffer.pop();
                if buffer.ends_with(&[b'\n']) {
                    buffer.pop();
                }
            } else if lr.limit() == 0 {
                return ResponseLimit { response: result }.fail();
            } else {
                return InvalidResponse {
                    context: "expected \\r delimiter, got: ",
                    data: String::from_utf8_lossy(&buffer),
                }
                .fail();
            }

            if buffer.len() > 0 {
                let line = String::from_utf8(buffer).context(Utf8Error)?;
                #[cfg(feature = "debug_response")]
                println!("Read: {:?}", &line);
                if line.starts_with("error ") {
                    Self::check_ok(&line)?;
                    return Ok(result);
                }
                result.push(line);
            }
            lr.set_limit(LIMIT_LINE_BYTES);
        }
        ResponseLimit { response: result }.fail()
    }

    /// Get a list of client-DB-IDs for a given server group ID
    ///
    /// See servergroupclientlist
    pub fn get_servergroup_client_list(&mut self, server_group: usize) -> Result<Vec<usize>> {
        writeln!(&mut self.tx, "servergroupclientlist sgid={}", server_group)?;

        let resp = self.read_response()?;
        if let Some(line) = resp.get(0) {
            let data: Vec<usize> = line
                .split('|')
                .map(|e| {
                    if let Some(cldbid) = e.split('=').collect::<Vec<_>>().get(1) {
                        Ok(cldbid
                            .parse::<usize>()
                            .map_err(|_| Ts3Error::InvalidResponse {
                                context: "expected usize, got ",
                                data: line.to_string(),
                            })?)
                    } else {
                        Err(Ts3Error::InvalidResponse {
                            context: "expected data of cldbid=1, got ",
                            data: line.to_string(),
                        })
                    }
                })
                .collect::<Result<Vec<usize>>>()?;
            Ok(data)
        } else {
            Ok(Vec::new())
        }
    }

    /// Check if error line is ok
    fn check_ok(msg: &str) -> Result<()> {
        let result: Vec<&str> = msg.split(' ').collect();
        #[cfg(debug)]
        {
            // should only be invoked on `error` lines, sanity check
            assert_eq!(
                "check_ok invoked on non-error line",
                result.get(0),
                Some(&"error")
            );
        }
        if let (Some(id), Some(msg)) = (result.get(1), result.get(2)) {
            let split_id: Vec<&str> = id.split('=').collect();
            let split_msg: Vec<&str> = msg.split('=').collect();
            if let (Some(id), Some(msg)) = (split_id.get(1), split_msg.get(1)) {
                let id = id.parse::<usize>().map_err(|_| Ts3Error::InvalidResponse {
                    context: "expected usize, got ",
                    data: (*msg).to_string(), // clippy lint
                })?;
                if id != 0 {
                    return ServerError {
                        response: ErrorResponse {
                            id,
                            msg: unescape_val(*msg),
                        },
                    }
                    .fail();
                } else {
                    return Ok(());
                }
            }
        }
        Err(Ts3Error::InvalidResponse {
            context: "expected id and msg, got ",
            data: msg.to_string(),
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test_format_cldbids() {
        let ids = vec![0, 1, 2, 3];
        assert_eq!(
            "cldbid=0|cldbid=1|cldbid=2|cldbid=3",
            QueryClient::format_cldbids(&ids)
        );
        assert_eq!("", QueryClient::format_cldbids(&[]));
        assert_eq!("cldbid=0", QueryClient::format_cldbids(&ids[0..1]));
    }
}