Skip to content

Commit e52d58f

Browse files
committed
Allow closing a session manually
Currently a session can only be closed on drop.
1 parent 4adf340 commit e52d58f

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

cryptoki/src/session/mod.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
55
use crate::context::Pkcs11;
66

7+
use crate::error::Result;
78
use cryptoki_sys::*;
89
use std::fmt::Formatter;
910
use std::marker::PhantomData;
@@ -72,15 +73,17 @@ impl<'a> Session<'a> {
7273
impl<'a> Session<'a> {
7374
/// Close a session
7475
/// This will be called on drop as well.
75-
pub fn close(self) {}
76+
pub fn close(self) -> Result<()> {
77+
self.close_inner()
78+
}
7679

7780
/// Get the raw handle of the session.
7881
pub fn handle(&self) -> CK_SESSION_HANDLE {
7982
self.handle
8083
}
8184

8285
pub(crate) fn client(&self) -> &Pkcs11 {
83-
&self.client
86+
self.client
8487
}
8588
}
8689

cryptoki/src/session/session_management.rs

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
//! Session management functions
44
55
use crate::context::Function;
6-
use crate::error::{Result, Rv};
6+
use crate::error::{Error, Result, Rv, RvError};
77
use crate::session::{Session, SessionInfo, UserType};
88
use crate::types::{AuthPin, RawAuthPin};
99

@@ -16,19 +16,13 @@ use std::convert::{TryFrom, TryInto};
1616

1717
impl Drop for Session<'_> {
1818
fn drop(&mut self) {
19-
#[inline(always)]
20-
fn close(session: &Session) -> Result<()> {
21-
unsafe {
22-
Rv::from(get_pkcs11!(session.client(), C_CloseSession)(
23-
session.handle(),
24-
))
25-
.into_result(Function::CloseSession)
19+
match self.close_inner() {
20+
Err(Error::Pkcs11(RvError::SessionClosed, Function::CloseSession)) => (), // the session has already been closed: ignore.
21+
Ok(()) => (),
22+
Err(err) => {
23+
error!("Failed to close session: {err}");
2624
}
2725
}
28-
29-
if let Err(err) = close(self) {
30-
error!("Failed to close session: {err}");
31-
}
3226
}
3327
}
3428

@@ -105,4 +99,13 @@ impl Session<'_> {
10599
SessionInfo::try_from(session_info)
106100
}
107101
}
102+
103+
// Helper function to be able to close a session only taking a reference.
104+
// This is used in the Drop trait function which only takes a reference as input.
105+
pub(super) fn close_inner(&self) -> Result<()> {
106+
unsafe {
107+
Rv::from(get_pkcs11!(self.client(), C_CloseSession)(self.handle()))
108+
.into_result(Function::CloseSession)
109+
}
110+
}
108111
}

0 commit comments

Comments
 (0)