| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
use std::convert::TryFrom; |
| 8 |
use std::marker::PhantomData; |
| 9 |
use std::mem; |
| 10 |
use std::os::raw::c_uint; |
| 11 |
use std::ptr::null_mut; |
| 12 |
|
| 13 |
use crate::nss_prelude::*; |
| 14 |
use crate::prtypes::*; |
| 15 |
|
| 16 |
/// Implement a smart pointer for NSS objects. |
| 17 |
/// |
| 18 |
/// Most of the time the pointer is like a `Box`, but there are exceptions (e.g. |
| 19 |
/// PK11SymKey is internally reference counted so its pointer is like an `Arc`.) |
| 20 |
/// |
| 21 |
/// Named "scoped" because that is what NSS calls its `unique_ptr` typedefs. |
| 22 |
macro_rules! scoped_ptr { |
| 23 |
($name:ident, $target:ty, $dtor:path) => { |
| 24 |
pub struct $name { |
| 25 |
ptr: *mut $target, |
| 26 |
} |
| 27 |
|
| 28 |
impl $name { |
| 29 |
/// Create a new instance of `$name` from a pointer. |
| 30 |
/// |
| 31 |
/// # Errors |
| 32 |
/// When passed a null pointer generates an error. |
| 33 |
pub unsafe fn from_ptr(raw: *mut $target) -> Result<Self, $crate::err::Error> { |
| 34 |
let ptr = $crate::err::into_result(raw)?; |
| 35 |
Ok(Self { ptr }) |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
impl $crate::err::IntoResult for *mut $target { |
| 40 |
type Ok = $name; |
| 41 |
|
| 42 |
unsafe fn into_result(self) -> Result<Self::Ok, $crate::err::Error> { |
| 43 |
$name::from_ptr(self) |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
impl std::ops::Deref for $name { |
| 48 |
type Target = *mut $target; |
| 49 |
#[must_use] |
| 50 |
fn deref(&self) -> &*mut $target { |
| 51 |
&self.ptr |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
// Original implements DerefMut, but is that really a good idea? |
| 56 |
|
| 57 |
impl Drop for $name { |
| 58 |
fn drop(&mut self) { |
| 59 |
unsafe { $dtor(self.ptr) }; |
| 60 |
} |
| 61 |
} |
| 62 |
}; |
| 63 |
} |
| 64 |
|
| 65 |
macro_rules! impl_clone { |
| 66 |
($name:ty, $nss_fn:path) => { |
| 67 |
impl Clone for $name { |
| 68 |
#[must_use] |
| 69 |
fn clone(&self) -> Self { |
| 70 |
let ptr = unsafe { $nss_fn(self.ptr) }; |
| 71 |
assert!(!ptr.is_null()); |
| 72 |
Self { ptr } |
| 73 |
} |
| 74 |
} |
| 75 |
}; |
| 76 |
} |
| 77 |
|
| 78 |
impl SECItem { |
| 79 |
/// Return contents as a slice. |
| 80 |
/// |
| 81 |
/// Unsafe due to calling from_raw_parts, or if 'a outlives &self. This |
| 82 |
/// unsafety is encapsulated by the `as_slice` method of `SECItemBorrowed` |
| 83 |
/// and `SECItemMut`. |
| 84 |
/// |
| 85 |
/// Note that safe code can construct a SECItem pointing to anything. The |
| 86 |
/// same is not true of the safe wrappers `SECItemMut` and `SECItemBorrowed` |
| 87 |
/// because their inner SECItem is private. |
| 88 |
pub unsafe fn as_slice<'a>(&self) -> &'a [u8] { |
| 89 |
// Sanity check the type, as some types don't count bytes in `Item::len`. |
| 90 |
assert_eq!(self.type_, SECItemType::siBuffer); |
| 91 |
// Note: `from_raw_parts` requires non-null `data` even for zero-length |
| 92 |
// slices. |
| 93 |
if self.len != 0 { |
| 94 |
std::slice::from_raw_parts(self.data, usize::try_from(self.len).unwrap()) |
| 95 |
} else { |
| 96 |
&[] |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
unsafe fn destroy_secitem(item: *mut SECItem) { |
| 102 |
SECITEM_FreeItem(item, PRBool::from(true)); |
| 103 |
} |
| 104 |
scoped_ptr!(ScopedSECItem, SECItem, destroy_secitem); |
| 105 |
|
| 106 |
impl ScopedSECItem { |
| 107 |
/// This dereferences the pointer held by the item and makes a copy of the |
| 108 |
/// content that is referenced there. |
| 109 |
/// |
| 110 |
/// # Safety |
| 111 |
/// This dereferences two pointers. It doesn't get much less safe. |
| 112 |
pub unsafe fn into_vec(self) -> Vec<u8> { |
| 113 |
let b = self.ptr.as_ref().unwrap(); |
| 114 |
// Sanity check the type, as some types don't count bytes in `Item::len`. |
| 115 |
assert_eq!(b.type_, SECItemType::siBuffer); |
| 116 |
let slc = std::slice::from_raw_parts(b.data, usize::try_from(b.len).unwrap()); |
| 117 |
Vec::from(slc) |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
/// An owned SECItem. |
| 122 |
/// |
| 123 |
/// The SECItem structure is allocated by Rust. The buffer referenced by the |
| 124 |
/// SECItem is allocated by NSS. `SECITEM_FreeItem` will be called to free the |
| 125 |
/// buffer when the SECItemMut is dropped. |
| 126 |
/// |
| 127 |
/// This is used with NSS functions that return a variable amount of data. |
| 128 |
#[repr(transparent)] |
| 129 |
pub struct SECItemMut { |
| 130 |
inner: SECItem, |
| 131 |
} |
| 132 |
|
| 133 |
impl<'a> Drop for SECItemMut { |
| 134 |
#[allow(unused_must_use)] |
| 135 |
fn drop(&mut self) { |
| 136 |
// FreeItem unconditionally frees the buffer referenced by the SECItem. |
| 137 |
// If the second argument is true, it also frees the SECItem itself, |
| 138 |
// which we don't want to do, because rust owns that memory. |
| 139 |
unsafe { SECITEM_FreeItem(&mut self.inner, PRBool::from(false)) }; |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
impl AsRef<SECItem> for SECItemMut { |
| 144 |
fn as_ref(&self) -> &SECItem { |
| 145 |
&self.inner |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
impl AsMut<SECItem> for SECItemMut { |
| 150 |
fn as_mut(&mut self) -> &mut SECItem { |
| 151 |
&mut self.inner |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
impl SECItemMut { |
| 156 |
/// Return contents as a slice. |
| 157 |
pub fn as_slice(&self) -> &[u8] { |
| 158 |
unsafe { self.inner.as_slice() } |
| 159 |
} |
| 160 |
|
| 161 |
/// Make an empty `SECItemMut` for passing as a mutable `*SECItem` argument. |
| 162 |
pub fn make_empty() -> SECItemMut { |
| 163 |
SECItemMut { |
| 164 |
inner: SECItem { |
| 165 |
type_: SECItemType::siBuffer, |
| 166 |
data: null_mut(), |
| 167 |
len: 0, |
| 168 |
}, |
| 169 |
} |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
/// A borrowed SECItem. |
| 174 |
/// |
| 175 |
/// The SECItem structure is allocated by Rust. The buffer referenced by the |
| 176 |
/// SECItem may be allocated either by Rust or NSS. The SECItem does not own the |
| 177 |
/// buffer and will not free it when dropped. |
| 178 |
/// |
| 179 |
/// This is usually used to pass a reference to some borrowed rust memory to |
| 180 |
/// NSS. It is occasionally used to accept non-owned output data from NSS. |
| 181 |
#[repr(transparent)] |
| 182 |
pub struct SECItemBorrowed<'a> { |
| 183 |
inner: SECItem, |
| 184 |
phantom_data: PhantomData<&'a u8>, |
| 185 |
} |
| 186 |
|
| 187 |
impl<'a> AsRef<SECItem> for SECItemBorrowed<'a> { |
| 188 |
fn as_ref(&self) -> &SECItem { |
| 189 |
&self.inner |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
impl<'a> AsMut<SECItem> for SECItemBorrowed<'a> { |
| 194 |
/// Get a mutable reference to the underlying SECItem struct. |
| 195 |
/// |
| 196 |
/// Note that even if the SECItem struct is mutable, the buffer it |
| 197 |
/// references may not be. Take care not to pass the mutable |
| 198 |
/// SECItem to NSS routines that will violate mutability rules. |
| 199 |
// |
| 200 |
// TODO: Should we make the danger more obvious, by using a non-trait method |
| 201 |
// with "unsafe" in the name, or an unsafe method? |
| 202 |
fn as_mut(&mut self) -> &mut SECItem { |
| 203 |
&mut self.inner |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
impl<'a> SECItemBorrowed<'a> { |
| 208 |
/// Return contents as a slice. |
| 209 |
pub fn as_slice(&self) -> &'a [u8] { |
| 210 |
unsafe { self.inner.as_slice() } |
| 211 |
} |
| 212 |
|
| 213 |
/// Create an empty `SECItemBorrowed`. |
| 214 |
/// |
| 215 |
/// This can be used (1) to pass an empty item as an argument, and (2) as an |
| 216 |
/// output parameter when NSS returns a pointer to NSS-owned memory that |
| 217 |
/// should not be freed when the SECItem is dropped. If the memory should |
| 218 |
/// be freed when the SECItem is dropped, use SECItemMut. |
| 219 |
/// |
| 220 |
/// It is safe to let the caller specify any lifetime here because no |
| 221 |
/// borrowing is actually taking place. However, if the pointer in the |
| 222 |
/// returned item is modified, care must be taken that the specified |
| 223 |
/// lifetime accurately reflects the data referenced by the pointer. |
| 224 |
pub fn make_empty() -> SECItemBorrowed<'a> { |
| 225 |
SECItemBorrowed { |
| 226 |
inner: SECItem { |
| 227 |
type_: SECItemType::siBuffer, |
| 228 |
data: null_mut(), |
| 229 |
len: 0, |
| 230 |
}, |
| 231 |
phantom_data: PhantomData, |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
/// Create a `SECItemBorrowed` wrapping a slice. |
| 236 |
/// |
| 237 |
/// Creating this object is technically safe, but using it is extremely dangerous. |
| 238 |
/// Minimally, it can only be passed as a `const SECItem*` argument to functions, |
| 239 |
/// or those that treat their argument as `const`. |
| 240 |
pub fn wrap(buf: &'a [u8]) -> SECItemBorrowed<'a> { |
| 241 |
SECItemBorrowed { |
| 242 |
inner: SECItem { |
| 243 |
type_: SECItemType::siBuffer, |
| 244 |
data: buf.as_ptr() as *mut u8, |
| 245 |
len: c_uint::try_from(buf.len()).unwrap(), |
| 246 |
}, |
| 247 |
phantom_data: PhantomData, |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
/// Create a `SECItemBorrowed` wrapping a struct. |
| 252 |
/// |
| 253 |
/// Creating this object is technically safe, but using it is extremely dangerous. |
| 254 |
/// Minimally, it can only be passed as a `const SECItem*` argument to functions, |
| 255 |
/// or those that treat their argument as `const`. |
| 256 |
pub fn wrap_struct<T>(v: &'a T) -> SECItemBorrowed<'a> { |
| 257 |
SECItemBorrowed { |
| 258 |
inner: SECItem { |
| 259 |
type_: SECItemType::siBuffer, |
| 260 |
data: (v as *const T as *mut T).cast(), |
| 261 |
len: c_uint::try_from(mem::size_of::<T>()).unwrap(), |
| 262 |
}, |
| 263 |
phantom_data: PhantomData, |
| 264 |
} |
| 265 |
} |
| 266 |
} |