use std::mem;
use std::slice;
use winapi::um::wincrypt;
use cert_context::CertContext;
use Inner;
pub struct CertChainContext(pub wincrypt::PCERT_CHAIN_CONTEXT);
unsafe impl Sync for CertChainContext {}
unsafe impl Send for CertChainContext {}
impl Clone for CertChainContext {
fn clone(&self) -> Self {
let rced = unsafe {
wincrypt::CertDuplicateCertificateChain(self.0) as *mut _
};
CertChainContext(rced)
}
}
impl Drop for CertChainContext {
fn drop(&mut self) {
unsafe {
wincrypt::CertFreeCertificateChain(self.0);
}
}
}
impl CertChainContext {
pub fn final_chain(&self) -> Option<CertChain> {
if let Some(chain) = self.chains().last(){
return Some(CertChain(chain.0, self.clone()));
}
None
}
pub fn get_chain(&self, index :usize) -> Option<CertChain> {
let cert_chain = unsafe {
let cert_chain = *self.0;
if index >= cert_chain.cChain as usize {
None
} else {
let chain_slice = slice::from_raw_parts(
cert_chain.rgpChain as *mut wincrypt::PCERT_SIMPLE_CHAIN,
cert_chain.cChain as usize);
Some(CertChain(chain_slice[index], self.clone()))
}
};
return cert_chain;
}
pub fn chains(&self) -> CertificateChains {
CertificateChains {
context: self,
idx: 0
}
}
}
pub struct CertChain(wincrypt::PCERT_SIMPLE_CHAIN, CertChainContext);
impl CertChain {
pub fn len(&self) -> usize {
unsafe {
(*self.0).cElement as usize
}
}
pub fn get(&self, idx: usize) -> Option<CertContext> {
let elements = unsafe {
let cert_chain = *self.0;
slice::from_raw_parts(
cert_chain.rgpElement as *mut &mut wincrypt::CERT_CHAIN_ELEMENT,
cert_chain.cElement as usize)
};
elements.get(idx).map(|el| {
let cert = unsafe {
CertContext::from_inner(el.pCertContext)
};
let rc_cert = cert.clone();
mem::forget(cert);
rc_cert
})
}
pub fn certificates(&self) -> Certificates {
Certificates {
chain: self,
idx: 0,
}
}
}
pub struct CertificateChains<'a> {
context: &'a CertChainContext,
idx: usize,
}
impl<'a> Iterator for CertificateChains<'a> {
type Item = CertChain;
fn next(&mut self) -> Option<CertChain> {
let idx = self.idx;
self.idx += 1;
self.context.get_chain(idx)
}
}
pub struct Certificates<'a> {
chain: &'a CertChain,
idx: usize,
}
impl<'a> Iterator for Certificates<'a> {
type Item = CertContext;
fn next(&mut self) -> Option<CertContext> {
let idx = self.idx;
self.idx += 1;
self.chain.get(idx)
}
}