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
//! Asynchronous client to remote [Coturn] server.
//!
//! [Coturn]: https://github.com/coturn/coturn

use std::io;

use bytes::Bytes;
use derive_more::{Display, From};
use futures::{SinkExt, StreamExt};
use tokio::net::{TcpStream, ToSocketAddrs};
use tokio_util::codec::Framed;

use crate::proto::{
    CoturnCliCodec, CoturnCliCodecError, CoturnCliRequest, CoturnCliResponse,
    CoturnResponseParseError,
};

/// Errors that can be returned by [`CoturnTelnetConnection`].
#[derive(Debug, Display, From)]
pub enum CoturnTelnetError {
    /// Underlying transport encountered error on I/O operation.
    ///
    /// You should try to recreate [`CoturnTelnetConnection`].
    #[display(fmt = "Underlying transport failed on I/O operation: {}", _0)]
    IoFailed(io::Error),

    /// Underlying stream exhausted.
    ///
    /// You should try to recreate [`CoturnTelnetConnection`].
    #[display(fmt = "Disconnected from Coturn telnet server")]
    Disconnected,

    /// Unable to parse response from [Coturn] server.
    ///
    /// This is unrecoverable error.
    ///
    /// [Coturn]: https://github.com/coturn/coturn
    #[display(fmt = "Unable to parse response: {}", _0)]
    MessageParseError(CoturnResponseParseError),

    /// [Coturn] answered with unexpected message.
    ///
    /// This is unrecoverable error.
    ///
    /// [Coturn]: https://github.com/coturn/coturn
    #[display(fmt = "Unexpected response received: {:?}", _0)]
    UnexpectedMessage(CoturnCliResponse),

    /// Authentication failed.
    ///
    /// This is unrecoverable error.
    #[display(fmt = "Coturn server rejected provided password")]
    WrongPassword,
}

impl From<CoturnCliCodecError> for CoturnTelnetError {
    fn from(err: CoturnCliCodecError) -> Self {
        use CoturnCliCodecError::{BadResponse, IoFailed};

        match err {
            IoFailed(e) => Self::from(e),
            BadResponse(e) => Self::from(e),
        }
    }
}

/// Asynchronous connection to remote [Coturn] server via [Telnet] interface.
///
/// [Coturn]: https://github.com/coturn/coturn
/// [Telnet]: https://en.wikipedia.org/wiki/Telnet
#[derive(Debug)]
pub struct CoturnTelnetConnection(Framed<TcpStream, CoturnCliCodec>);

impl CoturnTelnetConnection {
    /// Opens a [Telnet] connection to a remote host using a [`TcpStream`] and
    /// performs authentication.
    ///
    /// # Errors
    ///
    /// Errors if couldn't open [`TcpStream`] or authentication failed.
    ///
    /// [Telnet]: https://en.wikipedia.org/wiki/Telnet
    pub async fn connect<A: ToSocketAddrs, B: Into<Bytes>>(
        addr: A,
        pass: B,
    ) -> Result<CoturnTelnetConnection, CoturnTelnetError> {
        let stream = TcpStream::connect(addr).await?;
        let mut this = Self(Framed::new(stream, CoturnCliCodec::default()));
        this.auth(pass.into()).await?;
        Ok(this)
    }

    /// Returns session IDs for [Coturn] server associated with the provided
    /// `username`.
    ///
    /// 1. Sends [`CoturnCliRequest::PrintSessions`] with the provided
    ///    `username`.
    /// 2. Awaits for [`CoturnCliResponse::Sessions`].
    ///
    /// # Errors
    ///
    /// - Unable to send message to remote server.
    /// - Transport error while waiting for server response.
    /// - Received an unexpected (not [`CoturnCliResponse::Sessions`]) response
    ///   from remote server.
    ///
    /// [Coturn]: https://github.com/coturn/coturn
    pub async fn print_sessions(
        &mut self,
        username: String,
    ) -> Result<Vec<String>, CoturnTelnetError> {
        use CoturnTelnetError::{Disconnected, UnexpectedMessage};

        self.0
            .send(CoturnCliRequest::PrintSessions(username))
            .await?;

        let response: CoturnCliResponse =
            self.0.next().await.ok_or(Disconnected)??;
        match response {
            CoturnCliResponse::Sessions(sessions) => Ok(sessions),
            _ => Err(UnexpectedMessage(response)),
        }
    }

    /// Closes session on [Coturn] server destroying this session's allocations
    /// and channels.
    ///
    /// 1. Sends [`CoturnCliRequest::CloseSession`] with the provided
    ///    `session_id`.
    /// 2. Awaits for [`CoturnCliResponse::Ready`].
    ///
    /// # Errors
    ///
    /// - Unable to send message to remote server.
    /// - Transport error while waiting for server response.
    /// - Received an unexpected (not [`CoturnCliResponse::Ready`]) response
    ///   from remote server.
    ///
    /// [Coturn]: https://github.com/coturn/coturn
    pub async fn delete_session(
        &mut self,
        session_id: String,
    ) -> Result<(), CoturnTelnetError> {
        use CoturnTelnetError::{Disconnected, UnexpectedMessage};

        self.0
            .send(CoturnCliRequest::CloseSession(session_id))
            .await?;

        let response: CoturnCliResponse =
            self.0.next().await.ok_or(Disconnected)??;
        match response {
            CoturnCliResponse::Ready => Ok(()),
            _ => Err(UnexpectedMessage(response)),
        }
    }

    /// Closes multiple sessions on [Coturn] server destroying their allocations
    /// and channels.
    ///
    /// For each provided session id:
    /// 1. Sends [`CoturnCliRequest::CloseSession`] with specified session id.
    /// 2. Awaits for [`CoturnCliResponse::Ready`].
    ///
    /// # Errors
    ///
    /// - Unable to send message to remote server.
    /// - Transport error while waiting for server response.
    /// - Received an unexpected (not [`CoturnCliResponse::Sessions`]) response
    ///   from remote server.
    ///
    /// [Coturn]: https://github.com/coturn/coturn
    pub async fn delete_sessions<T: IntoIterator<Item = String>>(
        &mut self,
        session_ids: T,
    ) -> Result<(), CoturnTelnetError> {
        for id in session_ids {
            self.delete_session(id).await?;
        }
        Ok(())
    }

    /// Authenticates [`CoturnTelnetConnection`].
    ///
    /// 1. Awaits for [`CoturnCliResponse::EnterPassword`].
    /// 2. Sends [`CoturnCliRequest::Auth`].
    /// 3. Awaits for [`CoturnCliResponse::Ready`].
    ///
    /// # Errors
    ///
    /// - Unable to send message to remote server.
    /// - Transport error while waiting for server response.
    /// - First message received is not [`CoturnCliResponse::EnterPassword`].
    /// - Second message received is not [`CoturnCliResponse::Ready`].
    async fn auth(&mut self, pass: Bytes) -> Result<(), CoturnTelnetError> {
        use CoturnTelnetError::{
            Disconnected, UnexpectedMessage, WrongPassword,
        };

        let response = self.0.next().await.ok_or(Disconnected)??;
        if let CoturnCliResponse::EnterPassword = response {
        } else {
            return Err(UnexpectedMessage(response));
        };

        self.0.send(CoturnCliRequest::Auth(pass)).await?;

        let response = self.0.next().await.ok_or(Disconnected)??;
        match response {
            CoturnCliResponse::EnterPassword => Err(WrongPassword),
            CoturnCliResponse::Ready => Ok(()),
            _ => Err(UnexpectedMessage(response)),
        }
    }

    /// Pings [Coturn] server via [Telnet].
    ///
    /// # Errors
    ///
    /// - Unable to send message to remote server.
    /// - Transport error while waiting for server response.
    /// - First message received is not [`CoturnCliResponse::UnknownCommand`].
    ///
    /// [Coturn]: https://github.com/coturn/coturn
    /// [Telnet]: https://en.wikipedia.org/wiki/Telnet
    pub async fn ping(&mut self) -> Result<(), CoturnTelnetError> {
        use CoturnTelnetError::{Disconnected, UnexpectedMessage};

        self.0.send(CoturnCliRequest::Ping).await?;

        let response: CoturnCliResponse =
            self.0.next().await.ok_or(Disconnected)??;
        if let CoturnCliResponse::UnknownCommand = response {
            Ok(())
        } else {
            Err(UnexpectedMessage(response))
        }
    }
}