Merge pull request #285 from jonhoo/fixups

Various fixups
This commit is contained in:
Jon Gjengset 2024-03-31 04:39:22 -04:00 committed by GitHub
commit 586b0a484c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 614 additions and 375 deletions

View file

@ -99,7 +99,7 @@ jobs:
# https://docs.github.com/en/actions/learn-github-actions/contexts#context-availability
strategy:
matrix:
msrv: ["1.57.0"] # base64 0.21 requires 1.57
msrv: ["1.65.0"]
name: ubuntu / ${{ matrix.msrv }}
steps:
- uses: actions/checkout@v4

836
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
[package]
name = "imap"
version = "3.0.0-alpha.12"
version = "3.0.0-alpha.13"
authors = ["Jon Gjengset <jon@thesquareplanet.com>",
"Matt McCoy <mattnenterprise@yahoo.com>"]
documentation = "https://docs.rs/imap/"
@ -23,19 +23,19 @@ test-full-imap = []
[dependencies]
native-tls = { version = "0.2.2", optional = true }
rustls-connector = { version = "0.18.0", optional = true, features = ["dangerous-configuration"] }
rustls-connector = { version = "0.19.0", optional = true }
regex = "1.0"
bufstream = "0.1.3"
imap-proto = "0.16.1"
nom = { version = "7.1.0", default-features = false }
base64 = "0.21"
base64 = "0.22"
chrono = { version = "0.4", default-features = false, features = ["std"]}
lazy_static = "1.4"
ouroboros = "0.16.0"
ouroboros = "0.18.0"
[dev-dependencies]
lettre = "0.10"
rustls-connector = "0.18.0"
lettre = "0.11"
rustls-connector = "0.19.0"
structopt = "0.3"
# to make -Zminimal-versions work
@ -44,6 +44,7 @@ encoding = { version = "0.2.32", optional = true }
failure = { version = "0.1.8", optional = true }
mime = { version = "0.3.4", optional = true }
openssl = { version = "0.10.60", optional = true }
openssl-macros = { version = "0.1.1", optional = true }
[[example]]
name = "basic"

View file

@ -8,15 +8,16 @@ use std::ops::{Deref, DerefMut};
use std::str;
use std::sync::mpsc;
use crate::error::TagMismatch;
use super::authenticator::Authenticator;
use super::error::{Bad, Bye, Error, No, ParseError, Result, ValidateError};
use super::error::{Bad, Bye, Error, No, ParseError, Result, TagMismatch, ValidateError};
use super::extensions;
use super::parse::*;
use super::types::*;
use super::utils::*;
#[cfg(doc)]
use imap_proto::NameAttribute;
static TAG_PREFIX: &str = "a";
const INITIAL_TAG: u32 = 0;
const CR: u8 = 0x0d;
@ -176,9 +177,14 @@ pub struct Connection<T: Read + Write> {
impl<T: Read + Write> Connection<T> {
/// Manually increment the current tag.
///
/// This function can be manually executed by callers when the
/// previous tag was not reused, for example when a timeout did
/// not write anything on the stream.
/// If writing a command to the server fails, [`Client`] assumes that the command did not reach
/// the server, and thus that the next tag that should be sent is still the one used for the
/// failed command. However, it could be the case that the command _did_ reach the server
/// before failing, and thus a fresh tag needs to be issued instead.
///
/// This function can be used to attempt to manually re-synchronize the client's tag tracker in
/// such cases. It forcibly increments the client's tag counter such that the next command
/// sent to the server will have a tag that is one greater than it otherwise would.
pub fn skip_tag(&mut self) {
self.tag += 1;
}
@ -1736,7 +1742,6 @@ pub(crate) mod testutils {
#[cfg(test)]
mod tests {
use super::super::error::Result;
use super::super::mock_stream::MockStream;
use super::*;
use imap_proto::types::Capability;

View file

@ -11,7 +11,8 @@ use crate::extensions::idle::SetReadTimeout;
#[cfg(feature = "rustls-tls")]
use rustls_connector::{
rustls,
rustls::{Certificate, ClientConfig, RootCertStore, ServerName},
rustls::pki_types::{CertificateDer, ServerName},
rustls::{ClientConfig, RootCertStore},
rustls_native_certs::load_native_certs,
RustlsConnector,
};
@ -19,20 +20,43 @@ use rustls_connector::{
use std::sync::Arc;
#[cfg(feature = "rustls-tls")]
struct NoCertVerification;
#[derive(Debug)]
struct NoCertVerification(Arc<rustls::client::WebPkiServerVerifier>);
#[cfg(feature = "rustls-tls")]
impl rustls::client::ServerCertVerifier for NoCertVerification {
impl rustls::client::danger::ServerCertVerifier for NoCertVerification {
fn verify_server_cert(
&self,
_: &Certificate,
_: &[Certificate],
_: &ServerName,
_: &mut dyn Iterator<Item = &[u8]>,
_: &CertificateDer<'_>,
_: &[CertificateDer<'_>],
_: &ServerName<'_>,
_: &[u8],
_: std::time::SystemTime,
) -> std::result::Result<rustls::client::ServerCertVerified, rustls::Error> {
Ok(rustls::client::ServerCertVerified::assertion())
_: rustls::pki_types::UnixTime,
) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
self.0.verify_tls12_signature(message, cert, dss)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> std::prelude::v1::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error>
{
self.0.verify_tls13_signature(message, cert, dss)
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
self.0.supported_verify_schemes()
}
}
@ -41,7 +65,7 @@ lazy_static! {
static ref CACERTS: RootCertStore = {
let mut store = RootCertStore::empty();
for cert in load_native_certs().unwrap_or_else(|_| vec![]) {
if let Ok(_) = store.add(&Certificate(cert.0)) {}
if let Ok(_) = store.add(cert) {}
}
store
};
@ -335,14 +359,16 @@ where
#[cfg(feature = "rustls-tls")]
fn build_tls_rustls(&self, tcp: TcpStream) -> Result<Connection> {
let mut config = ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(CACERTS.clone())
.with_no_client_auth();
if self.skip_tls_verify {
let no_cert_verifier = NoCertVerification;
config
.dangerous()
.set_certificate_verifier(Arc::new(no_cert_verifier));
.set_certificate_verifier(Arc::new(NoCertVerification(
rustls::client::WebPkiServerVerifier::builder(Arc::new(CACERTS.clone()))
.build()
.expect("can construct standard verifier"),
)));
}
let ssl_conn: RustlsConnector = config.into();
Ok(Box::new(ssl_conn.connect(self.domain.as_ref(), tcp)?))

View file

@ -107,7 +107,9 @@ pub enum Error {
MissingStatusResponse,
/// The server responded with a different command tag than the one we just sent.
///
/// A new session must generally be established to recover from this.
/// A new session must generally be established to recover from this. You can also use
/// [`Connection::skip_tag`](crate::client::Connection::skip_tag) (which is available through
/// both [`Client`](crate::Client) and [`Session`](crate::Session)).
TagMismatch(TagMismatch),
/// StartTls is not available on the server
StartTlsNotAvailable,

View file

@ -247,27 +247,27 @@ impl<'a, T: Read + Write + 'a> Drop for Handle<'a, T> {
}
}
impl<'a> SetReadTimeout for Connection {
impl SetReadTimeout for Connection {
fn set_read_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
self.deref_mut().set_read_timeout(timeout)
}
}
impl<'a> SetReadTimeout for TcpStream {
impl SetReadTimeout for TcpStream {
fn set_read_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
TcpStream::set_read_timeout(self, timeout).map_err(Error::Io)
}
}
#[cfg(feature = "native-tls")]
impl<'a> SetReadTimeout for TlsStream<TcpStream> {
impl SetReadTimeout for TlsStream<TcpStream> {
fn set_read_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
self.get_ref().set_read_timeout(timeout).map_err(Error::Io)
}
}
#[cfg(feature = "rustls-tls")]
impl<'a> SetReadTimeout for RustlsStream<TcpStream> {
impl SetReadTimeout for RustlsStream<TcpStream> {
fn set_read_timeout(&mut self, timeout: Option<Duration>) -> Result<()> {
self.get_ref().set_read_timeout(timeout).map_err(Error::Io)
}

View file

@ -32,7 +32,7 @@ impl ExtendedNames {
ExtendedNamesTryBuilder {
data: owned,
extended_names_builder: |input| {
let mut lines: &[u8] = &input;
let mut lines: &[u8] = input;
let mut names = Vec::new();
let mut current_name: Option<Name<'_>> = None;
let mut current_mailbox: Option<Mailbox> = None;

View file

@ -33,12 +33,12 @@ impl CmdListItemFormat for Metadata {
"{} {}",
validate_str(
synopsis,
&format!("entry#{}", item_index + 1),
format!("entry#{}", item_index + 1),
self.entry.as_str()
)?,
self.value
.as_ref()
.map(|v| validate_str(synopsis, &format!("value#{}", item_index + 1), v.as_str()))
.map(|v| validate_str(synopsis, format!("value#{}", item_index + 1), v.as_str()))
.unwrap_or_else(|| Ok("NIL".to_string()))?
))
}

View file

@ -2,8 +2,6 @@ use imap_proto::{MailboxDatum, Response, ResponseCode, StatusAttribute};
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashSet;
use std::convert::TryFrom;
use std::iter::Extend;
use std::sync::mpsc;
use super::error::{Error, ParseError, Result};

View file

@ -13,6 +13,8 @@
//! imap = { version = "3.0", features = ["test_helpers"] }
//! ```
//!
#[cfg(doc)]
use crate::{extensions::list_status::ExtendedNames, types::*};
/// Methods to build a [`Capabilities`] response object
pub mod capabilities {

View file

@ -162,12 +162,12 @@ pub struct Acl<'a> {
impl<'a> Acl<'a> {
/// Return the mailbox the ACL entries belong to
pub fn mailbox(&self) -> &str {
&*self.mailbox
&self.mailbox
}
/// Returns a list of identifier/rights pairs for the mailbox
pub fn acls(&self) -> &[AclEntry<'_>] {
&*self.acls
&self.acls
}
}
@ -244,12 +244,12 @@ pub struct ListRights<'a> {
impl ListRights<'_> {
/// Returns the mailbox for the rights
pub fn mailbox(&self) -> &str {
&*self.mailbox
&self.mailbox
}
/// Returns the user identifier for the rights
pub fn identifier(&self) -> &str {
&*self.identifier
&self.identifier
}
/// Returns the set of rights that are always provided for this identifier
@ -318,7 +318,7 @@ pub struct MyRights<'a> {
impl MyRights<'_> {
/// Returns the mailbox for the rights
pub fn mailbox(&self) -> &str {
&*self.mailbox
&self.mailbox
}
/// Returns the rights for the mailbox

View file

@ -1,5 +1,8 @@
use imap_proto::UidSetMember;
#[cfg(doc)]
use crate::types::Uid;
/// Meta-information about a message, as returned by
/// [`APPEND`](https://tools.ietf.org/html/rfc3501#section-6.3.11).
/// Note that `APPEND` only returns any data if certain extensions are enabled,

View file

@ -64,7 +64,7 @@ impl Capabilities {
}
/// Check if the server has the given capability.
pub fn has<'a>(&self, cap: &Capability<'a>) -> bool {
pub fn has(&self, cap: &Capability<'_>) -> bool {
self.borrow_capabilities().contains(cap)
}

View file

@ -64,7 +64,7 @@ impl Deleted {
pub fn from_expunged(v: Vec<u32>, mod_seq: Option<u64>) -> Self {
Self {
messages: DeletedMessages::Expunged(v),
mod_seq: mod_seq,
mod_seq,
}
}
@ -73,7 +73,7 @@ impl Deleted {
pub fn from_vanished(v: Vec<RangeInclusive<u32>>, mod_seq: Option<u64>) -> Self {
Self {
messages: DeletedMessages::Vanished(v),
mod_seq: mod_seq,
mod_seq,
}
}

View file

@ -1,5 +1,8 @@
use std::borrow::Cow;
#[cfg(doc)]
use crate::types::Mailbox;
/// With the exception of [`Flag::Custom`], these flags are system flags that are pre-defined in
/// [RFC 3501 section 2.3.2](https://tools.ietf.org/html/rfc3501#section-2.3.2). All system flags
/// begin with `\` in the IMAP protocol. Certain system flags (`\Deleted` and `\Seen`) have

View file

@ -92,7 +92,7 @@ impl<'a> Name<'a> {
/// the name is also valid as an argument for commands, such as `SELECT`, that accept mailbox
/// names.
pub fn name(&self) -> &str {
&*self.name
&self.name
}
/// Get an owned version of this [`Name`].

View file

@ -9,7 +9,7 @@ use std::sync::mpsc;
/// From [SETQUOTA Resource limit](https://datatracker.ietf.org/doc/html/rfc2087#section-4.1)
///
/// Used by [`Session::set_quota`]
/// Used by [`Session::set_quota`](crate::Session::set_quota).
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct QuotaResourceLimit<'a> {
@ -35,7 +35,7 @@ impl Display for QuotaResourceLimit<'_> {
/// From [Resources](https://datatracker.ietf.org/doc/html/rfc2087#section-3)
///
/// Used by [`QuotaLimit`], and [`QuotaResource`]
/// Used by [`QuotaResourceLimit`], and [`QuotaResource`]
#[derive(Debug, Eq, PartialEq, Clone)]
#[non_exhaustive]
pub enum QuotaResourceName<'a> {
@ -128,7 +128,7 @@ impl QuotaResponse {
/// From [QUOTA Response](https://datatracker.ietf.org/doc/html/rfc2087#section-5.1)
///
/// Used by [`QuotaResponse`] and [`QuotaRoot`]
/// Used by [`QuotaResponse`] and [`QuotaRootResponse`]
#[derive(Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Quota<'a> {
@ -234,7 +234,7 @@ impl QuotaRootResponse {
/// The mailbox name
pub fn mailbox_name(&self) -> &str {
&*self.borrow_inner().quota_root.mailbox_name
&self.borrow_inner().quota_root.mailbox_name
}
/// The list of quota roots for the mailbox name (could be empty)
@ -243,7 +243,7 @@ impl QuotaRootResponse {
.quota_root
.quota_root_names
.iter()
.map(|e| &*e.as_ref())
.map(|e| e.as_ref())
}
/// The set of quotas for each named quota root (could be empty)

View file

@ -1,5 +1,3 @@
use std::convert::TryFrom;
use super::{Flag, Seq};
/// re-exported from imap_proto;
@ -77,7 +75,7 @@ pub enum UnsolicitedResponse {
// TODO: the spec doesn't seem to say anything about when these may be received as unsolicited?
Flags(Vec<Flag<'static>>),
/// An unsolicited METADATA response (https://tools.ietf.org/html/rfc5464#section-4.4.2)
/// An unsolicited [METADATA response](https://tools.ietf.org/html/rfc5464#section-4.4.2)
/// that reports a change in a server or mailbox annotation.
Metadata {
/// Mailbox name for which annotations were changed.

View file

@ -45,7 +45,10 @@ fn starttls_force() {
assert!(list_mailbox(&mut s).is_ok());
}
#[cfg(any(feature = "native-tls", feature = "rustls-tls"))]
#[cfg(all(
any(feature = "native-tls", feature = "rustls-tls"),
feature = "test-full-imap"
))]
#[test]
fn tls_force() {
let user = "tls@localhost";