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
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Slot and token management functions

use crate::error::{Result, Rv};
use crate::label_from_str;
use crate::mechanism::{MechanismInfo, MechanismType};
use crate::slot::{Slot, SlotInfo, TokenInfo};
use crate::types::AuthPin;
use crate::{
    context::Pkcs11,
    error::{Error, RvError},
};
use cryptoki_sys::{
    CKF_DONT_BLOCK, CK_BBOOL, CK_FALSE, CK_FLAGS, CK_MECHANISM_INFO, CK_SLOT_ID, CK_SLOT_INFO,
    CK_TOKEN_INFO, CK_TRUE,
};
use secrecy::ExposeSecret;
use std::convert::{TryFrom, TryInto};

use crate::error::RvError::BufferTooSmall;

use super::Function;

impl Pkcs11 {
    #[inline(always)]
    fn get_slots(&self, with_token: CK_BBOOL) -> Result<Vec<Slot>> {
        let mut slot_count = 0;
        let rval = unsafe {
            get_pkcs11!(self, C_GetSlotList)(with_token, std::ptr::null_mut(), &mut slot_count)
        };
        Rv::from(rval).into_result(Function::GetSlotList)?;

        let mut slots;
        loop {
            slots = vec![0; slot_count as usize];
            let rval = unsafe {
                get_pkcs11!(self, C_GetSlotList)(with_token, slots.as_mut_ptr(), &mut slot_count)
            };
            // Account for a race condition between the call to get the
            // slot_count and the last call in which the number of slots grew.
            // In this case, slot_count will have been updated to the larger amount
            // and we want to loop again with a resized buffer.
            if !matches!(Rv::from(rval), Rv::Error(BufferTooSmall)) {
                // Account for other possible error types
                Rv::from(rval).into_result(Function::GetSlotList)?;
                // Otherwise, we have a valid list to process
                break;
            }
        }
        // Account for the same race condition, but with a shrinking slot_count
        slots.truncate(slot_count as usize);
        Ok(slots.into_iter().map(Slot::new).collect())
    }

    /// Get all slots available with a token
    pub fn get_slots_with_token(&self) -> Result<Vec<Slot>> {
        self.get_slots(CK_TRUE)
    }

    /// Get all slots
    pub fn get_all_slots(&self) -> Result<Vec<Slot>> {
        self.get_slots(CK_FALSE)
    }

    /// Get all slots available with a token
    pub fn get_slots_with_initialized_token(&self) -> Result<Vec<Slot>> {
        let slots = self.get_slots_with_token()?;

        slots
            .into_iter()
            .filter_map(|slot| match self.get_token_info(slot) {
                Ok(token_info) => {
                    if token_info.token_initialized() {
                        Some(Ok(slot))
                    } else {
                        None
                    }
                }
                Err(e) => Some(Err(e)),
            })
            .collect()
    }

    /// Initialize a token
    ///
    /// Currently will use an empty label for all tokens.
    pub fn init_token(&self, slot: Slot, pin: &AuthPin, label: &str) -> Result<()> {
        let label = label_from_str(label);
        unsafe {
            Rv::from(get_pkcs11!(self, C_InitToken)(
                slot.into(),
                pin.expose_secret().as_ptr() as *mut u8,
                pin.expose_secret().len().try_into()?,
                label.as_ptr() as *mut u8,
            ))
            .into_result(Function::InitToken)
        }
    }

    /// Returns the slot info
    pub fn get_slot_info(&self, slot: Slot) -> Result<SlotInfo> {
        unsafe {
            let mut slot_info = CK_SLOT_INFO::default();
            Rv::from(get_pkcs11!(self, C_GetSlotInfo)(
                slot.into(),
                &mut slot_info,
            ))
            .into_result(Function::GetSlotInfo)?;
            Ok(SlotInfo::from(slot_info))
        }
    }

    /// Returns information about a specific token
    pub fn get_token_info(&self, slot: Slot) -> Result<TokenInfo> {
        unsafe {
            let mut token_info = CK_TOKEN_INFO::default();
            Rv::from(get_pkcs11!(self, C_GetTokenInfo)(
                slot.into(),
                &mut token_info,
            ))
            .into_result(Function::GetTokenInfo)?;
            TokenInfo::try_from(token_info)
        }
    }

    /// Get all mechanisms support by a slot
    pub fn get_mechanism_list(&self, slot: Slot) -> Result<Vec<MechanismType>> {
        let mut mechanism_count = 0;

        unsafe {
            Rv::from(get_pkcs11!(self, C_GetMechanismList)(
                slot.into(),
                std::ptr::null_mut(),
                &mut mechanism_count,
            ))
            .into_result(Function::GetMechanismList)?;
        }

        let mut mechanisms = vec![0; mechanism_count.try_into()?];

        unsafe {
            Rv::from(get_pkcs11!(self, C_GetMechanismList)(
                slot.into(),
                mechanisms.as_mut_ptr(),
                &mut mechanism_count,
            ))
            .into_result(Function::GetMechanismList)?;
        }

        // Truncate mechanisms if count decreased.
        mechanisms.truncate(mechanism_count.try_into()?);

        Ok(mechanisms
            .into_iter()
            .filter_map(|type_| type_.try_into().ok())
            .collect())
    }

    /// Get detailed information about a mechanism for a slot
    pub fn get_mechanism_info(&self, slot: Slot, type_: MechanismType) -> Result<MechanismInfo> {
        unsafe {
            let mut mechanism_info = CK_MECHANISM_INFO::default();
            Rv::from(get_pkcs11!(self, C_GetMechanismInfo)(
                slot.into(),
                type_.into(),
                &mut mechanism_info,
            ))
            .into_result(Function::GetMechanismInfo)?;
            Ok(MechanismInfo::from(mechanism_info))
        }
    }

    fn wait_for_slot_event_impl(&self, flags: CK_FLAGS) -> Result<Slot> {
        unsafe {
            let mut slot: CK_SLOT_ID = 0;
            let wait_for_slot_event = get_pkcs11!(self, C_WaitForSlotEvent);
            let rv = wait_for_slot_event(flags, &mut slot, std::ptr::null_mut());
            Rv::from(rv).into_result(Function::WaitForSlotEvent)?;
            Ok(Slot::new(slot))
        }
    }

    /// Wait for slot events (insertion or removal of a token)
    pub fn wait_for_slot_event(&self) -> Result<Slot> {
        self.wait_for_slot_event_impl(0)
    }

    /// Get the latest slot event (insertion or removal of a token)
    pub fn get_slot_event(&self) -> Result<Option<Slot>> {
        match self.wait_for_slot_event_impl(CKF_DONT_BLOCK) {
            Err(Error::Pkcs11(RvError::NoEvent, Function::WaitForSlotEvent)) => Ok(None),
            Ok(slot) => Ok(Some(slot)),
            Err(x) => Err(x),
        }
    }
}