Unverified Commit a5988c05 authored by Jack Rickard's avatar Jack Rickard
Browse files

Add `try_cmp` function to `X509NameRef`s

parent 4d392c96
Loading
Loading
Loading
Loading
+16 −1
Original line number Diff line number Diff line
@@ -10,7 +10,7 @@
use cfg_if::cfg_if;
use foreign_types::{ForeignType, ForeignTypeRef};
use libc::{c_int, c_long};
use std::cmp;
use std::cmp::{self, Ordering};
use std::error::Error;
use std::ffi::{CStr, CString};
use std::fmt;
@@ -1028,6 +1028,21 @@ impl X509NameRef {
        }
    }

    /// Compare two names, like [`Ord`] but it may fail.
    ///
    /// With OpenSSL versions from 3.0.0 this may return an error if the underlying `X509_NAME_cmp`
    /// call fails.
    /// For OpenSSL versions before 3.0.0 it will never return an error, but due to a bug it may
    /// spuriously return `Ordering::Less` if the `X509_NAME_cmp` call fails.
    #[corresponds(X509_NAME_cmp)]
    pub fn try_cmp(&self, other: &X509NameRef) -> Result<Ordering, ErrorStack> {
        let cmp = unsafe { ffi::X509_NAME_cmp(self.as_ptr(), other.as_ptr()) };
        if cfg!(ossl300) && cmp == -2 {
            return Err(ErrorStack::get());
        }
        Ok(cmp.cmp(&0))
    }

    to_der! {
        /// Serializes the certificate into a DER-encoded X509 name structure.
        ///
+13 −0
Original line number Diff line number Diff line
use std::cmp::Ordering;

use crate::asn1::Asn1Time;
use crate::bn::{BigNum, MsbOption};
use crate::hash::MessageDigest;
@@ -527,3 +529,14 @@ fn test_convert_req_to_text() {
        );
    }
}

#[test]
fn test_name_cmp() {
    let cert = include_bytes!("../../test/cert.pem");
    let cert = X509::from_pem(cert).unwrap();

    let subject = cert.subject_name();
    let issuer = cert.issuer_name();
    assert_eq!(Ordering::Equal, subject.try_cmp(subject).unwrap());
    assert_eq!(Ordering::Greater, subject.try_cmp(issuer).unwrap());
}