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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use std::io::{self, Read, Write};

use bytes::{BufMut, BytesMut};
#[cfg(feature = "async")]
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tracing::{debug, error, info, trace};

use crate::{
    command::{Command, CommandList},
    parser,
    response::{Response, ResponseBuilder, ResponseFieldCache},
    MpdProtocolError,
};

/// Default receive buffer size
const DEFAULT_BUFFER_CAPACITY: usize = 4096;

/// A **blocking** connection to an MPD server.
#[derive(Debug)]
pub struct Connection<IO> {
    io: IO,
    protocol_version: Box<str>,
    field_cache: ResponseFieldCache,
    recv_buf: BytesMut,
    total_received: usize,
}

impl<IO> Connection<IO> {
    #[cfg(any(fuzzing, criterion))]
    #[allow(dead_code)]
    #[doc(hidden)]
    pub fn new_internal(io: IO) -> Connection<IO> {
        Connection {
            io,
            protocol_version: Box::from(""),
            field_cache: ResponseFieldCache::new(),
            recv_buf: BytesMut::zeroed(DEFAULT_BUFFER_CAPACITY),
            total_received: 0,
        }
    }

    /// Connect to an MPD server synchronously.
    #[tracing::instrument(skip_all, err)]
    pub fn connect(mut io: IO) -> Result<Connection<IO>, MpdProtocolError>
    where
        IO: Read,
    {
        let mut recv_buf = BytesMut::zeroed(DEFAULT_BUFFER_CAPACITY);
        let mut total_read = 0;

        let protocol_version = loop {
            let (data, amount_read) = read_to_buffer(&mut io, &mut recv_buf, &mut total_read)?;

            if amount_read == 0 {
                return Err(MpdProtocolError::Io(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "unexpected end of file while receiving greeting",
                )));
            }

            match parser::greeting(data) {
                Ok((_, version)) => {
                    info!(?version, "connected successfully");
                    break Box::from(version);
                }
                Err(e) if e.is_incomplete() => {
                    // The response was valid *so far*, try another read
                    trace!("greeting incomplete");
                }
                Err(_) => {
                    error!("invalid greeting");
                    return Err(MpdProtocolError::InvalidMessage);
                }
            }
        };

        Ok(Connection {
            io,
            protocol_version,
            field_cache: ResponseFieldCache::new(),
            recv_buf,
            total_received: 0,
        })
    }

    /// Send a command.
    ///
    /// # Errors
    ///
    /// This will return an error if writing to the given IO resource fails.
    #[tracing::instrument(skip(self), err)]
    pub fn send(&mut self, mut command: Command) -> Result<(), MpdProtocolError>
    where
        IO: Write,
    {
        command.0.put_u8(b'\n');
        self.io.write_all(&command.0)?;
        debug!(length = command.0.len(), "sent command");
        Ok(())
    }

    /// Send a command list.
    ///
    /// # Errors
    ///
    /// This will return an error if writing to the given IO resource fails.
    #[tracing::instrument(skip(self), err)]
    pub fn send_list(&mut self, command_list: CommandList) -> Result<(), MpdProtocolError>
    where
        IO: Write,
    {
        let buf = command_list.render();
        self.io.write_all(&buf)?;
        debug!(length = buf.len(), "sent command list");

        Ok(())
    }

    /// Receive a response from the server.
    ///
    /// This will return `Ok(Some(..))` when a complete response has been received, or `Ok(None)` if
    /// the connection is closed cleanly.
    ///
    /// # Errors
    ///
    /// This will return an error if:
    ///
    ///  - Reading from the given IO resource returns an error
    ///  - Malformed response data is received
    ///  - The connection is closed while a response is in progress
    #[tracing::instrument(skip(self), err)]
    pub fn receive(&mut self) -> Result<Option<Response>, MpdProtocolError>
    where
        IO: Read,
    {
        let mut response_builder = ResponseBuilder::new(&mut self.field_cache);

        loop {
            // Split off the read part of the receive buffer
            let buf_size = self.recv_buf.len();
            let remaining = self.recv_buf.split_off(self.total_received);

            // Try to parse response data from the initialized section of the buffer, removing the
            // consumed parts from the buffer
            let maybe_parsed = response_builder.parse(&mut self.recv_buf)?;

            // Update the length of the initialized section to the remaining length
            self.total_received = self.recv_buf.len();

            // Join back the remaining data with the main buffer, and readjust the length
            self.recv_buf.unsplit(remaining);
            self.recv_buf.resize(buf_size, 0);

            if let Some(response) = maybe_parsed {
                debug!(
                    frames = response.successful_frames(),
                    error = response.is_error(),
                    fields = response.field_count(),
                    "received complete response"
                );
                break Ok(Some(response));
            }

            let (_, amount_read) =
                read_to_buffer(&mut self.io, &mut self.recv_buf, &mut self.total_received)?;

            if amount_read == 0 {
                break if response_builder.is_frame_in_progress() || self.total_received != 0 {
                    error!("EOF while receiving response");
                    Err(MpdProtocolError::Io(io::Error::new(
                        io::ErrorKind::UnexpectedEof,
                        "unexpected end of file while receiving response",
                    )))
                } else {
                    debug!("clean EOF while receiving response");
                    Ok(None)
                };
            }
        }
    }

    /// Send a command and receive its response.
    ///
    /// This is essentially a shorthand for [`Connection::send`] followed by [`Connection::receive`].
    ///
    /// # Errors
    ///
    /// This will return an error if:
    ///
    ///  - Writing to or reading from the connection returns an error
    ///  - Malformed response data is received
    ///  - The connection is closed
    #[tracing::instrument(skip(self), err)]
    pub fn command(&mut self, command: Command) -> Result<Response, MpdProtocolError>
    where
        IO: Read + Write,
    {
        self.send(command)?;

        if let Some(r) = self.receive()? {
            Ok(r)
        } else {
            error!("connection was closed without a response to the command");
            Err(MpdProtocolError::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "connection was closed without a response to the command",
            )))
        }
    }

    /// Send a command list and receive its response(s).
    ///
    /// This is essentially a shorthand for [`Connection::send_list`] followed by [`Connection::receive`].
    ///
    /// # Errors
    ///
    /// This will return an error if:
    ///
    ///  - Writing to or reading from the connection returns an error
    ///  - Malformed response data is received
    ///  - The connection is closed
    #[tracing::instrument(skip(self), err)]
    pub fn command_list(&mut self, command_list: CommandList) -> Result<Response, MpdProtocolError>
    where
        IO: Read + Write,
    {
        self.send_list(command_list)?;

        if let Some(r) = self.receive()? {
            Ok(r)
        } else {
            error!("connection was closed without a response to the command");
            Err(MpdProtocolError::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "connection was closed without a response to the command",
            )))
        }
    }

    /// Returns the protocol version the server is using.
    pub fn protocol_version(&self) -> &str {
        &self.protocol_version
    }

    /// Extract the connection instance.
    pub fn into_inner(self) -> IO {
        self.io
    }
}

fn read_to_buffer<'a, R: Read>(
    mut io: R,
    buf: &'a mut BytesMut,
    total: &mut usize,
) -> Result<(&'a [u8], usize), io::Error> {
    let read = io.read(&mut buf[*total..])?;
    trace!(read);
    *total += read;

    if buf.len() == *total {
        trace!("need to grow buffer");
        buf.resize(buf.len() * 2, 0);
    }

    Ok((&buf[..*total], read))
}

/// An **asynchronous** connection to an MPD server.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
#[derive(Debug)]
pub struct AsyncConnection<IO>(Connection<IO>);

#[cfg(feature = "async")]
impl<IO> AsyncConnection<IO> {
    /// Connect to an MPD server asynchronously.
    ///
    /// # Errors
    ///
    /// This will return an error if:
    ///
    ///  - Reading from the given IO resource returns an error
    ///  - A malformed greeting is received
    ///  - The connection is closed before a complete greeting could be read
    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
    #[tracing::instrument(skip_all, err)]
    pub async fn connect(mut io: IO) -> Result<AsyncConnection<IO>, MpdProtocolError>
    where
        IO: AsyncRead + Unpin,
    {
        let mut recv_buf = BytesMut::with_capacity(DEFAULT_BUFFER_CAPACITY);

        let protocol_version = loop {
            let read = io.read_buf(&mut recv_buf).await?;
            trace!(read);

            if read == 0 {
                return Err(MpdProtocolError::Io(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "unexpected end of file while receiving greeting",
                )));
            }

            match parser::greeting(&recv_buf) {
                Ok((_, version)) => {
                    info!(?version, "connected successfully");
                    break Box::from(version);
                }
                Err(e) if e.is_incomplete() => {
                    // The response was valid *so far*, try another read
                    trace!("greeting incomplete");
                }
                Err(_) => {
                    error!("invalid greeting");
                    return Err(MpdProtocolError::InvalidMessage);
                }
            }
        };

        recv_buf.clear();

        Ok(AsyncConnection(Connection {
            io,
            protocol_version,
            field_cache: ResponseFieldCache::new(),
            recv_buf,
            total_received: 0,
        }))
    }

    /// Send a command.
    ///
    /// # Errors
    ///
    /// This will return an error if writing to the given IO resource fails.
    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
    #[tracing::instrument(skip(self), err)]
    pub async fn send(&mut self, mut command: Command) -> Result<(), MpdProtocolError>
    where
        IO: AsyncWrite + Unpin,
    {
        command.0.put_u8(b'\n');
        self.0.io.write_all(&command.0).await?;
        debug!(length = command.0.len(), "sent command");
        Ok(())
    }

    /// Send a command list.
    ///
    /// # Errors
    ///
    /// This will return an error if writing to the given IO resource fails.
    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
    #[tracing::instrument(skip(self), err)]
    pub async fn send_list(&mut self, command_list: CommandList) -> Result<(), MpdProtocolError>
    where
        IO: AsyncWrite + Unpin,
    {
        let buf = command_list.render();
        self.0.io.write_all(&buf).await?;
        debug!(length = buf.len(), "sent command");
        Ok(())
    }

    /// Receive a response from the server.
    ///
    /// This will return `Ok(Some(..))` when a complete response has been received, or `Ok(None)` if
    /// the connection is closed cleanly.
    ///
    /// # Errors
    ///
    /// This will return an error if:
    ///
    ///  - Reading from the given IO resource returns an error
    ///  - Malformed response data is received
    ///  - The connection is closed while a response is in progress
    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
    #[tracing::instrument(skip(self), err)]
    pub async fn receive(&mut self) -> Result<Option<Response>, MpdProtocolError>
    where
        IO: AsyncRead + Unpin,
    {
        let mut response_builder = ResponseBuilder::new(&mut self.0.field_cache);

        loop {
            if let Some(response) = response_builder.parse(&mut self.0.recv_buf)? {
                debug!(
                    frames = response.successful_frames(),
                    fields = response.field_count(),
                    error = response.is_error(),
                    "received complete response"
                );
                break Ok(Some(response));
            }

            let read = self.0.io.read_buf(&mut self.0.recv_buf).await?;
            trace!(read);

            if read == 0 {
                break if response_builder.is_frame_in_progress() || !self.0.recv_buf.is_empty() {
                    error!("EOF while receiving response");
                    Err(MpdProtocolError::Io(io::Error::new(
                        io::ErrorKind::UnexpectedEof,
                        "unexpected end of file while receiving response",
                    )))
                } else {
                    debug!("clean EOF while receiving");
                    Ok(None)
                };
            }
        }
    }

    /// Send a command and receive its response.
    ///
    /// This is essentially a shorthand for [`AsyncConnection::send`] followed by
    /// [`AsyncConnection::receive`].
    ///
    /// # Errors
    ///
    /// This will return an error if:
    ///
    ///  - Writing to or reading from the connection returns an error
    ///  - Malformed response data is received
    ///  - The connection is closed
    #[tracing::instrument(skip(self), err)]
    pub async fn command(&mut self, command: Command) -> Result<Response, MpdProtocolError>
    where
        IO: AsyncRead + AsyncWrite + Unpin,
    {
        self.send(command).await?;

        if let Some(r) = self.receive().await? {
            Ok(r)
        } else {
            error!("connection was closed without a response to the command");
            Err(MpdProtocolError::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "connection was closed without a response to the command",
            )))
        }
    }

    /// Send a command list and receive its response(s).
    ///
    /// This is essentially a shorthand for [`AsyncConnection::send_list`] followed by
    /// [`AsyncConnection::receive`].
    ///
    /// # Errors
    ///
    /// This will return an error if:
    ///
    ///  - Writing to or reading from the connection returns an error
    ///  - Malformed response data is received
    ///  - The connection is closed
    #[tracing::instrument(skip(self), err)]
    pub async fn command_list(
        &mut self,
        command_list: CommandList,
    ) -> Result<Response, MpdProtocolError>
    where
        IO: AsyncRead + AsyncWrite + Unpin,
    {
        self.send_list(command_list).await?;

        if let Some(r) = self.receive().await? {
            Ok(r)
        } else {
            error!("connection was closed without a response to the command");
            Err(MpdProtocolError::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "connection was closed without a response to the command",
            )))
        }
    }

    /// Returns the protocol version the server is using.
    pub fn protocol_version(&self) -> &str {
        &self.0.protocol_version
    }

    /// Extract the connection instance.
    pub fn into_inner(self) -> IO {
        self.0.io
    }
}

#[cfg(test)]
mod tests_sync {
    use assert_matches::assert_matches;

    use super::*;

    fn new_conn<IO>(io: IO) -> Connection<IO> {
        Connection {
            io,
            field_cache: ResponseFieldCache::new(),
            protocol_version: Box::from(""),
            recv_buf: BytesMut::zeroed(DEFAULT_BUFFER_CAPACITY),
            total_received: 0,
        }
    }

    #[test]
    fn connect() {
        let io: &[u8] = b"OK MPD 0.23.3\n";
        let connection = Connection::connect(io).unwrap();
        assert_eq!(connection.protocol_version(), "0.23.3");
    }

    #[test]
    fn connect_eof() {
        let io: &[u8] = b"OK MPD 0.23.3";
        let connection = Connection::connect(io).unwrap_err();
        assert_matches!(connection, MpdProtocolError::Io(e) if e.kind() == io::ErrorKind::UnexpectedEof);
    }

    #[test]
    fn connect_invalid() {
        let io: &[u8] = b"foobar\n";
        let connection = Connection::connect(io).unwrap_err();
        assert_matches!(connection, MpdProtocolError::InvalidMessage);
    }

    #[test]
    fn send() {
        let mut io = Vec::new();
        let mut connection = new_conn(&mut io);

        connection
            .send(Command::new("foo").argument("bar"))
            .unwrap();

        assert_eq!(io, b"foo bar\n");
    }

    #[test]
    fn send_list() {
        let mut io = Vec::new();
        let mut connection = new_conn(&mut io);

        let list = CommandList::new(Command::new("foo")).command(Command::new("bar"));

        connection.send_list(list).unwrap();

        assert_eq!(
            io,
            b"command_list_ok_begin\n\
              foo\n\
              bar\n\
              command_list_end\n"
        );
    }

    #[test]
    fn receive() {
        let io: &[u8] = b"foo: bar\nOK\n";
        let mut connection = new_conn(io);

        let response = connection.receive();

        assert_matches!(response, Ok(Some(_)));
    }

    #[test]
    fn receive_eof() {
        let io: &[u8] = b"foo: bar\nOK";
        let mut connection = new_conn(io);

        let response = connection.receive();

        assert_matches!(response, Err(MpdProtocolError::Io(e)) if e.kind() == io::ErrorKind::UnexpectedEof);
    }
}

#[cfg(test)]
#[cfg(feature = "async")]
mod tests_async {
    use assert_matches::assert_matches;
    use tokio_test::io::Builder as MockBuilder;

    use super::*;

    fn new_conn<IO>(io: IO) -> AsyncConnection<IO> {
        AsyncConnection(Connection {
            io,
            field_cache: ResponseFieldCache::new(),
            protocol_version: Box::from(""),
            recv_buf: BytesMut::new(),
            total_received: 0,
        })
    }

    #[tokio::test]
    async fn connect() {
        let io = MockBuilder::new().read(b"OK MPD 0.23.3\n").build();
        let connection = AsyncConnection::connect(io).await.unwrap();
        assert_eq!(connection.protocol_version(), "0.23.3");
    }

    #[tokio::test]
    async fn connect_split_read() {
        let io = MockBuilder::new()
            .read(b"OK MPD 0.23.3")
            .read(b"\n")
            .build();
        let connection = AsyncConnection::connect(io).await.unwrap();
        assert_eq!(connection.protocol_version(), "0.23.3");
    }

    #[tokio::test]
    async fn connect_eof() {
        let io = MockBuilder::new().read(b"OK MPD 0.23.3").build(); // no newline
        let connection = AsyncConnection::connect(io).await.unwrap_err();
        assert_matches!(connection, MpdProtocolError::Io(e) if e.kind() == io::ErrorKind::UnexpectedEof);
    }

    #[tokio::test]
    async fn connect_invalid() {
        let io = MockBuilder::new().read(b"OK foobar\n").build();
        let connection = AsyncConnection::connect(io).await.unwrap_err();
        assert_matches!(connection, MpdProtocolError::InvalidMessage);
    }

    #[tokio::test]
    async fn send_single() {
        let io = MockBuilder::new().write(b"status\n").build();
        let mut connection = new_conn(io);

        connection.send(Command::new("status")).await.unwrap();
    }

    #[tokio::test]
    async fn send_list() {
        let list = CommandList::new(Command::new("foo")).command(Command::new("bar"));
        let io = MockBuilder::new()
            .write(
                b"command_list_ok_begin\n\
                  foo\n\
                  bar\n\
                  command_list_end\n",
            )
            .build();
        let mut connection = new_conn(io);

        connection.send_list(list).await.unwrap();
    }

    #[tokio::test]
    async fn send_list_single() {
        let list = CommandList::new(Command::new("foo"));
        let io = MockBuilder::new().write(b"foo\n").build(); // skips command list wrapping
        let mut connection = new_conn(io);

        connection.send_list(list).await.unwrap();
    }

    #[tokio::test]
    async fn receive() {
        let io = MockBuilder::new().read(b"foo: bar\nOK\n").build();
        let mut connection = new_conn(io);

        let response = connection.receive().await.unwrap();

        assert_matches!(response, Some(response) if response.is_success());
    }

    #[tokio::test]
    async fn receive_split_read() {
        let io = MockBuilder::new().read(b"foo: bar\nOK").read(b"\n").build();
        let mut connection = new_conn(io);

        let response = connection.receive().await.unwrap();

        assert_matches!(response, Some(response) if response.is_success());
    }

    #[tokio::test]
    async fn receive_eof_clean() {
        let io = MockBuilder::new().build();
        let mut connection = new_conn(io);

        let response = connection.receive().await.unwrap();

        assert_eq!(response, None);
    }

    #[tokio::test]
    async fn receive_eof() {
        let io = MockBuilder::new().read(b"foo: bar\n").build();
        let mut connection = new_conn(io);

        let error = connection.receive().await.unwrap_err();

        assert_matches!(error, MpdProtocolError::Io(e) if e.kind() == io::ErrorKind::UnexpectedEof);
    }

    #[tokio::test]
    async fn receive_multiple() {
        let io = MockBuilder::new().read(b"OK\nOK\n").build();
        let mut connection = new_conn(io);

        let response = connection.receive().await.unwrap();
        assert_matches!(response, Some(response) if response.is_success());

        let response = connection.receive().await.unwrap();
        assert_matches!(response, Some(response) if response.is_success());

        let response = connection.receive().await.unwrap();
        assert_matches!(response, None);
    }

    #[tokio::test]
    async fn command() {
        let io = MockBuilder::new()
            .write(b"foo\n")
            .read(b"bar: baz\nOK\n")
            .build();
        let mut connection = new_conn(io);

        let resp = connection.command(Command::new("foo")).await.unwrap();
        assert_eq!(resp.field_count(), 1);
    }
}