comparison libpam-sys/src/helpers.rs @ 106:49d9e2b5c189

An irresponsible mix of implementing libpam-sys and other stuff.
author Paul Fisher <paul@pfish.zone>
date Thu, 26 Jun 2025 22:41:28 -0400
parents
children bb465393621f
comparison
equal deleted inserted replaced
105:13b4d2a19674 106:49d9e2b5c189
1 //! This module contains a few non-required helpers to deal with some of the
2 //! more annoying memory-twiddling in the PAM API.
3 //!
4 //! Using these is optional but you might find it useful.
5 use std::error::Error;
6 use std::marker::{PhantomData, PhantomPinned};
7 use std::mem::ManuallyDrop;
8 use std::ptr::NonNull;
9 use std::{fmt, slice};
10
11 /// Error returned when attempting to allocate a buffer that is too big.
12 ///
13 /// This is specifically used in [`OwnedBinaryPayload`] when you try to allocate
14 /// a message larger than 2<sup>32</sup> bytes.
15 #[derive(Debug, PartialEq)]
16 pub struct TooBigError {
17 pub size: usize,
18 pub max: usize,
19 }
20
21 impl Error for TooBigError {}
22
23 impl fmt::Display for TooBigError {
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 write!(
26 f,
27 "can't allocate a message of {size} bytes (max {max})",
28 size = self.size,
29 max = self.max
30 )
31 }
32 }
33
34 /// A trait wrapping memory management.
35 ///
36 /// This is intended to allow you to bring your own allocator for
37 /// [`OwnedBinaryPayload`]s.
38 ///
39 /// For an implementation example, see the implementation of this trait
40 /// for [`Vec`].
41 pub trait Buffer<T: Default> {
42 /// Allocates a buffer of `len` elements, filled with the default.
43 fn allocate(len: usize) -> Self;
44
45 fn as_ptr(&self) -> *const T;
46
47 /// Returns a slice view of `size` elements of the given memory.
48 ///
49 /// # Safety
50 ///
51 /// The caller must not request more elements than are allocated.
52 unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T];
53
54 /// Consumes this ownership and returns a pointer to the start of the arena.
55 fn into_ptr(self) -> NonNull<T>;
56
57 /// "Adopts" the memory at the given pointer, taking it under management.
58 ///
59 /// Running the operation:
60 ///
61 /// ```
62 /// # use libpam_sys::helpers::Buffer;
63 /// # fn test<T: Default, OwnerType: Buffer<T>>(bytes: usize) {
64 /// let owner = OwnerType::allocate(bytes);
65 /// let ptr = owner.into_ptr();
66 /// let owner = unsafe { OwnerType::from_ptr(ptr, bytes) };
67 /// # }
68 /// ```
69 ///
70 /// must be a no-op.
71 ///
72 /// # Safety
73 ///
74 /// The pointer must be valid, and the caller must provide the exact size
75 /// of the given arena.
76 unsafe fn from_ptr(ptr: NonNull<T>, bytes: usize) -> Self;
77 }
78
79 impl<T: Default> Buffer<T> for Vec<T> {
80 fn allocate(bytes: usize) -> Self {
81 (0..bytes).map(|_| Default::default()).collect()
82 }
83
84 fn as_ptr(&self) -> *const T {
85 Vec::as_ptr(self)
86 }
87
88 unsafe fn as_mut_slice(&mut self, bytes: usize) -> &mut [T] {
89 debug_assert!(bytes <= self.len());
90 Vec::as_mut(self)
91 }
92
93 fn into_ptr(self) -> NonNull<T> {
94 let mut me = ManuallyDrop::new(self);
95 // SAFETY: a Vec is guaranteed to have a nonzero pointer.
96 unsafe { NonNull::new_unchecked(me.as_mut_ptr()) }
97 }
98
99 unsafe fn from_ptr(ptr: NonNull<T>, bytes: usize) -> Self {
100 Vec::from_raw_parts(ptr.as_ptr(), bytes, bytes)
101 }
102 }
103
104 /// A binary message owned by some storage.
105 ///
106 /// This is an owned, memory-managed version of [`BinaryPayload`].
107 /// The `O` type manages the memory where the payload lives.
108 /// [`Vec<u8>`] is one such manager and can be used when ownership
109 /// of the data does not need to transit through PAM.
110 #[derive(Debug)]
111 pub struct OwnedBinaryPayload<Owner: Buffer<u8>>(Owner);
112
113 impl<O: Buffer<u8>> OwnedBinaryPayload<O> {
114 /// Allocates a new OwnedBinaryPayload.
115 ///
116 /// This will return a [`TooBigError`] if you try to allocate too much
117 /// (more than [`BinaryPayload::MAX_SIZE`]).
118 pub fn new(data_type: u8, data: &[u8]) -> Result<Self, TooBigError> {
119 let total_len: u32 = (data.len() + 5).try_into().map_err(|_| TooBigError {
120 size: data.len(),
121 max: BinaryPayload::MAX_SIZE,
122 })?;
123 let total_len = total_len as usize;
124 let mut buf = O::allocate(total_len);
125 // SAFETY: We just allocated this exact size.
126 BinaryPayload::fill(unsafe { &mut buf.as_mut_slice(total_len) }, data_type, data);
127 Ok(Self(buf))
128 }
129
130 /// The contents of the buffer.
131 pub fn contents(&self) -> (u8, &[u8]) {
132 unsafe { BinaryPayload::contents(self.as_ptr()) }
133 }
134
135 /// The total bytes needed to store this, including the header.
136 pub fn total_bytes(&self) -> usize {
137 unsafe {
138 self.0
139 .as_ptr()
140 .cast::<BinaryPayload>()
141 .as_ref()
142 .unwrap_unchecked()
143 .total_bytes()
144 }
145 }
146
147 /// Unwraps this into the raw storage backing it.
148 pub fn into_inner(self) -> O {
149 self.0
150 }
151
152 /// Gets a const pointer to the start of the message's buffer.
153 pub fn as_ptr(&self) -> *const BinaryPayload {
154 self.0.as_ptr().cast()
155 }
156
157 /// Consumes ownership of this message and converts it to a raw pointer
158 /// to the start of the message.
159 ///
160 /// To clean this up, you should eventually pass it into [`Self::from_ptr`]
161 /// with the same `O` ownership type.
162 pub fn into_ptr(self) -> NonNull<BinaryPayload> {
163 self.0.into_ptr().cast()
164 }
165
166 /// Takes ownership of the given pointer.
167 ///
168 /// # Safety
169 ///
170 /// You must provide a valid pointer, allocated by (or equivalent to one
171 /// allocated by) [`Self::new`]. For instance, passing a pointer allocated
172 /// by `malloc` to `OwnedBinaryPayload::<Vec<u8>>::from_ptr` is not allowed.
173 pub unsafe fn from_ptr(ptr: NonNull<BinaryPayload>) -> Self {
174 Self(O::from_ptr(ptr.cast(), ptr.as_ref().total_bytes() as usize))
175 }
176 }
177
178 /// The structure of the "binary message" payload for the `PAM_BINARY_PROMPT`
179 /// extension from Linux-PAM.
180 pub struct BinaryPayload {
181 /// The total length of the message, including this header,
182 /// as a u32 in network byte order (big endian).
183 total_length: [u8; 4],
184 /// A tag used to provide some kind of hint as to what the data is.
185 /// This is not defined by PAM.
186 data_type: u8,
187 /// Where the data itself would start, used as a marker to make this
188 /// not [`Unpin`] (since it is effectively an intrusive data structure
189 /// pointing to immediately after itself).
190 _marker: PhantomData<PhantomPinned>,
191 }
192
193 impl BinaryPayload {
194 /// The most data it's possible to put into a [`BinaryPayload`].
195 pub const MAX_SIZE: usize = (u32::MAX - 5) as usize;
196
197 /// Fills in the provided buffer with the given data.
198 ///
199 /// This uses [`copy_from_slice`](slice::copy_from_slice) internally,
200 /// so `buf` must be exactly 5 bytes longer than `data`, or this function
201 /// will panic.
202 pub fn fill(buf: &mut [u8], data_type: u8, data: &[u8]) {
203 let ptr: *mut Self = buf.as_mut_ptr().cast();
204 // SAFETY: We're given a slice, which always has a nonzero pointer.
205 let me = unsafe { ptr.as_mut().unwrap_unchecked() };
206 me.total_length = u32::to_be_bytes(buf.len() as u32);
207 me.data_type = data_type;
208 buf[5..].copy_from_slice(data)
209 }
210
211 /// The size of the message contained in the buffer.
212 fn len(&self) -> usize {
213 self.total_bytes().saturating_sub(5)
214 }
215
216 /// The total storage needed for the message, including header.
217 pub fn total_bytes(&self) -> usize {
218 u32::from_be_bytes(self.total_length) as usize
219 }
220
221 /// Gets the contents of the BinaryMessage starting at the given location.
222 ///
223 /// # Safety
224 ///
225 /// You must pass in a valid pointer, and ensure that the pointer passed in
226 /// outlives your borrow lifetime `'a`.
227 unsafe fn contents<'a>(ptr: *const Self) -> (u8, &'a [u8]) {
228 let header: &Self = ptr.as_ref().unwrap_unchecked();
229 let typ = header.data_type;
230 (
231 typ,
232 slice::from_raw_parts(ptr.cast::<u8>().offset(5), header.len()),
233 )
234 }
235 }
236
237 #[cfg(test)]
238 mod tests {
239 use super::*;
240
241 type VecPayload = OwnedBinaryPayload<Vec<u8>>;
242
243 #[test]
244 fn test_binary_payload() {
245 let simple_message = &[0u8, 0, 0, 16, 0xff, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
246 let empty = &[0u8; 5];
247
248 assert_eq!((0xff, &[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10][..]), unsafe {
249 BinaryPayload::contents(simple_message.as_ptr().cast())
250 });
251 assert_eq!((0x00, &[][..]), unsafe {
252 BinaryPayload::contents(empty.as_ptr().cast())
253 });
254 }
255
256 #[test]
257 fn test_owned_binary_payload() {
258 let (typ, data) = (
259 112,
260 &[0, 1, 1, 8, 9, 9, 9, 8, 8, 1, 9, 9, 9, 1, 1, 9, 7, 2, 5, 3][..],
261 );
262 let payload = VecPayload::new(typ, data).unwrap();
263 assert_eq!((typ, data), payload.contents());
264 let ptr = payload.into_ptr();
265 let payload = unsafe { VecPayload::from_ptr(ptr) };
266 assert_eq!((typ, data), payload.contents());
267 }
268
269 #[test]
270 #[ignore]
271 fn test_owned_too_big() {
272 let data = vec![0xFFu8; 0x1_0000_0001];
273 assert_eq!(
274 TooBigError {
275 max: 0xffff_fffa,
276 size: 0x1_0000_0001
277 },
278 VecPayload::new(5, &data).unwrap_err()
279 )
280 }
281 }