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
use std::borrow::Borrow;
use std::convert::{TryFrom, TryInto};
use std::net::ToSocketAddrs;

use log::*;

use crate::error::{Error, Result};

use crate::raw::connection::{ConnectionConfig, NntpConnection};
use crate::raw::response::RawResponse;
use crate::types::command as cmd;
use crate::types::prelude::*;

/// A client that returns typed responses and provides state management
///
/// `NntpClient` is built on top of [`NntpConnection`] and offers several niceties:
///
/// 1. Responses from the server are typed and semantically validated
/// 2. Management of the connection state (e.g. current group, known capabilities)
///
/// In exchange for these niceties, `NntpClient` does not provide the low-allocation guarantees
/// that `NntpConnection` does. If you are really concerned about memory management,
/// you may want to use the [`NntpConnection`].
#[derive(Debug)]
pub struct NntpClient {
    conn: NntpConnection,
    config: ClientConfig,
    capabilities: Capabilities,
    group: Option<Group>,
}

impl NntpClient {
    /// Get the raw [`NntpConnection`] for the client
    ///
    /// # Usage
    ///
    /// NNTP is a **STATEFUL PROTOCOL** and misusing the underlying connection may mess up the
    /// state in the client that owns the connection.
    ///
    /// For example, manually sending a `GROUP`  command would leave change the group of
    /// the connection but will not update the NntpClient's internal record.
    ///
    /// Caveat emptor!
    pub fn conn(&mut self) -> &mut NntpConnection {
        &mut self.conn
    }

    /// Send a command
    ///
    /// This is useful if you want to use a command you have implemented or one that is not
    /// provided by a client method
    ///
    /// # Example
    ///
    /// Say we have a server that uses mode switching for whatever reason. Brokaw implements
    /// a [`ModeReader`](cmd::ModeReader) command but it does not provide a return type.
    /// We implement one in the following example
    /// <details><summary>MOTD</summary>
    ///
    /// ```no_run
    /// use std::convert::{TryFrom, TryInto};
    /// use brokaw::types::prelude::*;
    /// use brokaw::types::command as cmd;
    ///
    /// struct Motd {
    ///     posting_allowed: bool,
    ///     motd: String,
    /// }
    ///
    /// impl TryFrom<RawResponse> for Motd {
    ///     type Error = String;
    ///
    ///     fn try_from(resp: RawResponse) -> Result<Self, Self::Error> {
    ///         let posting_allowed = match resp.code() {
    ///             ResponseCode::Known(Kind::PostingAllowed) => true,
    ///             ResponseCode::Known(Kind::PostingNotPermitted) => false,
    ///             ResponseCode::Known(Kind::PermanentlyUnavailable) => {
    ///                 return Err("Server is gone forever".to_string());
    ///             }
    ///             ResponseCode::Known(Kind::TemporarilyUnavailable) => {
    ///                 return Err("Server is down?".to_string());
    ///             }
    ///             code => return Err(format!("Unexpected {:?}", code))
    ///         };
    ///         let mut motd = String::from_utf8_lossy(resp.first_line_without_code())
    ///             .to_string();
    ///
    ///         Ok(Motd { posting_allowed, motd })
    ///     }
    /// }
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     use brokaw::client::{NntpClient, ClientConfig};
    ///     let mut client = ClientConfig::default()
    ///         .connect(("news.modeswitching.notreal", 119))?;
    ///
    ///     let resp: Motd = client.command(cmd::ModeReader)?.try_into()?;
    ///     println!("Motd: {}", resp.motd);
    ///     Ok(())
    /// }
    /// ```
    /// </details>
    pub fn command(&mut self, c: impl NntpCommand) -> Result<RawResponse> {
        let resp = self.conn.command(&c)?;
        Ok(resp)
    }

    /// Get the currently selected group
    pub fn config(&self) -> &ClientConfig {
        &self.config
    }

    /// Get the last selected group
    pub fn group(&self) -> Option<&Group> {
        self.group.as_ref()
    }

    /// Select a newsgroup
    pub fn select_group(&mut self, name: impl AsRef<str>) -> Result<Group> {
        let resp = self.conn.command(&cmd::Group(name.as_ref().to_string()))?;

        match resp.code() {
            ResponseCode::Known(Kind::GroupSelected) => {
                let group = Group::try_from(&resp)?;
                self.group = Some(group.clone());
                Ok(group)
            }
            ResponseCode::Known(Kind::NoSuchNewsgroup) => Err(Error::failure(resp)),
            code => Err(Error::Failure {
                code,
                msg: Some(format!("{}", resp.first_line_to_utf8_lossy())),
                resp,
            }),
        }
    }

    /// The capabilities cached in the client
    pub fn capabilities(&self) -> &Capabilities {
        &self.capabilities
    }

    /// Retrieve updated capabilities from the server
    pub fn update_capabilities(&mut self) -> Result<&Capabilities> {
        let resp = self
            .conn
            .command(&cmd::Capabilities)?
            .fail_unless(Kind::Capabilities)?;

        let capabilities = Capabilities::try_from(&resp)?;

        self.capabilities = capabilities;

        Ok(&self.capabilities)
    }

    /// Retrieve an article from the server
    ///
    ///
    /// # Text Articles
    ///
    /// Binary articles can be converted to text using the [`to_text`](BinaryArticle::to_text)
    /// and [`to_text_lossy`](BinaryArticle::to_text) methods. Note that the former is fallible
    /// as it will validate that the body of the article is UTF-8.
    ///
    /// ```
    /// use brokaw::client::NntpClient;
    /// use brokaw::error::Result;
    /// use brokaw::types::prelude::*;
    /// use brokaw::types::command::Article;
    ///
    /// fn checked_conversion(client: &mut NntpClient) -> Result<TextArticle> {
    ///     client.article(Article::Number(42))
    ///         .and_then(|b| b.to_text())
    /// }
    ///
    /// fn lossy_conversion(client: &mut NntpClient) -> Result<TextArticle> {
    ///     client.article(Article::Number(42))
    ///         .map(|b| b.to_text_lossy())
    /// }
    ///
    /// ```
    pub fn article(&mut self, article: cmd::Article) -> Result<BinaryArticle> {
        let resp = self.conn.command(&article)?.fail_unless(Kind::Article)?;

        resp.borrow().try_into()
    }

    /// Retrieve the body for an article
    pub fn body(&mut self, body: cmd::Body) -> Result<Body> {
        let resp = self.conn.command(&body)?.fail_unless(Kind::Head)?;
        resp.borrow().try_into()
    }

    /// Retrieve the headers for an article
    pub fn head(&mut self, head: cmd::Head) -> Result<Head> {
        let resp = self.conn.command(&head)?.fail_unless(Kind::Head)?;
        resp.borrow().try_into()
    }

    /// Retrieve the status of an article
    pub fn stat(&mut self, stat: cmd::Stat) -> Result<Option<Stat>> {
        let resp = self.conn.command(&stat)?;
        match resp.code() {
            ResponseCode::Known(Kind::ArticleExists) => resp.borrow().try_into().map(Some),
            ResponseCode::Known(Kind::NoArticleWithMessageId)
            | ResponseCode::Known(Kind::InvalidCurrentArticleNumber)
            | ResponseCode::Known(Kind::NoArticleWithNumber) => Ok(None),
            _ => Err(Error::failure(resp)),
        }
    }

    /// Close the connection to the server
    pub fn close(&mut self) -> Result<RawResponse> {
        let resp = self
            .conn
            .command(&cmd::Quit)?
            .fail_unless(Kind::ConnectionClosing)?;

        Ok(resp)
    }
}

/// Configuration for an [`NntpClient`]
#[derive(Clone, Debug, Default)]
pub struct ClientConfig {
    authinfo: Option<(String, String)>,
    group: Option<String>,
    conn_config: ConnectionConfig,
}

impl ClientConfig {
    /// Perform an AUTHINFO USER/PASS authentication after connecting to the server
    ///
    /// https://tools.ietf.org/html/rfc4643#section-2.3
    pub fn authinfo_user_pass(
        &mut self,
        username: impl AsRef<str>,
        password: impl AsRef<str>,
    ) -> &mut Self {
        self.authinfo = Some((username.as_ref().to_string(), password.as_ref().to_string()));
        self
    }

    /// Join a group upon connection
    ///
    /// If this is set to None then no `GROUP` command will be sent when the client is initialized
    pub fn group(&mut self, name: Option<impl AsRef<str>>) -> &mut Self {
        self.group = name.map(|s| s.as_ref().to_string());
        self
    }

    /// Use the default TLS configuration
    pub fn default_tls(&mut self, domain: String) -> Result<&mut Self> {
        self.conn_config.default_tls(domain)?;
        Ok(self)
    }

    /// Set the configuration of the underlying [`NntpConnection`]
    ///
    /// Note that this will override the TLS configuration set by [`default_tls`](Self::default_tls)
    pub fn connection_config(&mut self, config: ConnectionConfig) -> &mut Self {
        self.conn_config = config;
        self
    }

    /// Resolves the configuration into a client
    pub fn connect(&self, addr: impl ToSocketAddrs) -> Result<NntpClient> {
        let (mut conn, conn_response) = NntpConnection::connect(addr, self.conn_config.clone())?;

        debug!(
            "Connected. Server returned `{}`",
            conn_response.first_line_to_utf8_lossy()
        );

        // FIXME(ux) check capabilities before attempting auth info
        if let Some((username, password)) = &self.authinfo {
            if self.conn_config.tls_config.is_none() {
                warn!("TLS is not enabled, credentials will be sent in the clear!");
            }
            debug!("Authenticating with AUTHINFO USER/PASS");
            authenticate(&mut conn, username, password)?;
        }

        debug!("Retrieving capabilities...");
        let capabilities = get_capabilities(&mut conn)?;

        let group = if let Some(name) = &self.group {
            debug!("Connecting to group {}...", name);
            select_group(&mut conn, name)?.into()
        } else {
            debug!("No initial group specified");
            None
        };

        Ok(NntpClient {
            conn,
            config: self.clone(),
            capabilities,
            group,
        })
    }
}

impl RawResponse {}

/// Perform an AUTHINFO USER/PASS exchange
fn authenticate(
    conn: &mut NntpConnection,
    username: impl AsRef<str>,
    password: impl AsRef<str>,
) -> Result<()> {
    debug!("Sending AUTHINFO USER");
    let user_resp = conn.command(&cmd::AuthInfo::User(username.as_ref().to_string()))?;

    if user_resp.code != ResponseCode::from(381) {
        return Err(Error::Failure {
            code: user_resp.code,
            resp: user_resp,
            msg: Some("AUTHINFO USER failed".to_string()),
        });
    }

    debug!("Sending AUTHINFO PASS");
    let pass_resp = conn.command(&cmd::AuthInfo::Pass(password.as_ref().to_string()))?;

    if pass_resp.code() != ResponseCode::Known(Kind::AuthenticationAccepted) {
        return Err(Error::Failure {
            code: pass_resp.code,
            resp: pass_resp,
            msg: Some("AUTHINFO PASS failed".to_string()),
        });
    }
    debug!("Successfully authenticated");

    Ok(())
}

fn get_capabilities(conn: &mut NntpConnection) -> Result<Capabilities> {
    let resp = conn.command(&cmd::Capabilities)?;

    if resp.code() != ResponseCode::Known(Kind::Capabilities) {
        Err(Error::failure(resp))
    } else {
        Capabilities::try_from(&resp)
    }
}

fn select_group(conn: &mut NntpConnection, group: impl AsRef<str>) -> Result<Group> {
    let resp = conn.command(&cmd::Group(group.as_ref().to_string()))?;

    match resp.code() {
        ResponseCode::Known(Kind::GroupSelected) => Group::try_from(&resp),
        ResponseCode::Known(Kind::NoSuchNewsgroup) => Err(Error::failure(resp)),
        code => Err(Error::Failure {
            code,
            msg: Some(format!("{}", resp.first_line_to_utf8_lossy())),
            resp,
        }),
    }
}