comparison src/pam_ffi/response.rs @ 71:58f9d2a4df38

Reorganize everything again??? - Splits ffi/memory stuff into a bunch of stuff in the pam_ffi module. - Builds infrastructure for passing Messages and Responses. - Adds tests for some things at least.
author Paul Fisher <paul@pfish.zone>
date Tue, 03 Jun 2025 21:54:58 -0400
parents src/pam_ffi.rs@9f8381a1c09c
children 47eb242a4f88
comparison
equal deleted inserted replaced
70:9f8381a1c09c 71:58f9d2a4df38
1 //! Types used when dealing with PAM conversations.
2
3 use crate::pam_ffi::memory;
4 use crate::pam_ffi::memory::{CBinaryData, Immovable, NulError, TooBigError};
5 use std::ffi::{c_char, c_int, c_void, CStr};
6 use std::ops::{Deref, DerefMut};
7 use std::result::Result as StdResult;
8 use std::str::Utf8Error;
9 use std::{mem, ptr, slice};
10
11 #[repr(transparent)]
12 #[derive(Debug)]
13 pub struct RawTextResponse(RawResponse);
14
15 impl RawTextResponse {
16 /// Allocates a new text response on the C heap.
17 ///
18 /// Both `self` and its internal pointer are located on the C heap.
19 /// You are responsible for calling [`free`](Self::free_contents)
20 /// on the pointer you get back when you're done with it.
21 pub fn fill(dest: &mut RawResponse, text: impl AsRef<str>) -> StdResult<&mut Self, NulError> {
22 dest.data = memory::malloc_str(text)?.cast();
23 Ok(unsafe { &mut *(dest as *mut RawResponse as *mut Self) })
24 }
25
26 /// Gets the string stored in this response.
27 pub fn contents(&self) -> StdResult<&str, Utf8Error> {
28 // SAFETY: This data is either passed from PAM (so we are forced to
29 // trust it) or was created by us in TextResponseInner::alloc.
30 // In either case, it's going to be a valid null-terminated string.
31 unsafe { CStr::from_ptr(self.0.data as *const c_char) }.to_str()
32 }
33
34 /// Releases memory owned by this response.
35 ///
36 /// # Safety
37 ///
38 /// You are responsible for no longer using this after calling free.
39 pub unsafe fn free_contents(&mut self) {
40 let data = self.0.data;
41 memory::zero_c_string(data);
42 libc::free(data);
43 self.0.data = ptr::null_mut()
44 }
45 }
46
47 /// A [`RawResponse`] with [`CBinaryData`] in it.
48 #[repr(transparent)]
49 #[derive(Debug)]
50 pub struct RawBinaryResponse(RawResponse);
51
52 impl RawBinaryResponse {
53 /// Allocates a new binary response on the C heap.
54 ///
55 /// The `data_type` is a tag you can use for whatever.
56 /// It is passed through PAM unchanged.
57 ///
58 /// The referenced data is copied to the C heap. We do not take ownership.
59 /// You are responsible for calling [`free`](Self::free_contents)
60 /// on the pointer you get back when you're done with it.
61 pub fn fill<'a>(
62 dest: &'a mut RawResponse,
63 data: &[u8],
64 data_type: u8,
65 ) -> StdResult<&'a mut Self, TooBigError> {
66 dest.data = CBinaryData::alloc(data, data_type)? as *mut c_void;
67 Ok(unsafe {
68 (dest as *mut RawResponse)
69 .cast::<RawBinaryResponse>()
70 .as_mut()
71 .unwrap()
72 })
73 }
74
75 /// Gets the binary data in this response.
76 pub fn contents(&self) -> &[u8] {
77 self.data().contents()
78 }
79
80 /// Gets the `data_type` tag that was embedded with the message.
81 pub fn data_type(&self) -> u8 {
82 self.data().data_type()
83 }
84
85 #[inline]
86 fn data(&self) -> &CBinaryData {
87 // SAFETY: This was either something we got from PAM (in which case
88 // we trust it), or something that was created with
89 // BinaryResponseInner::alloc. In both cases, it points to valid data.
90 unsafe { &*(self.0.data as *const CBinaryData) }
91 }
92
93 /// Releases memory owned by this response.
94 ///
95 /// # Safety
96 ///
97 /// You are responsible for not using this after calling free.
98 pub unsafe fn free_contents(&mut self) {
99 let data_ref = (self.0.data as *mut CBinaryData).as_mut();
100 if let Some(d) = data_ref {
101 d.zero_contents()
102 }
103 libc::free(self.0.data);
104 self.0.data = ptr::null_mut()
105 }
106 }
107
108 /// Generic version of response data.
109 ///
110 /// This has the same structure as [`RawBinaryResponse`]
111 /// and [`RawTextResponse`].
112 #[repr(C)]
113 #[derive(Debug)]
114 pub struct RawResponse {
115 /// Pointer to the data returned in a response.
116 /// For most responses, this will be a [`CStr`], but for responses to
117 /// [`MessageStyle::BinaryPrompt`]s, this will be [`CBinaryData`]
118 /// (a Linux-PAM extension).
119 data: *mut c_void,
120 /// Unused.
121 return_code: c_int,
122 _marker: Immovable,
123 }
124
125 /// A contiguous block of responses.
126 #[derive(Debug)]
127 #[repr(C)]
128 pub struct OwnedResponses {
129 base: *mut RawResponse,
130 count: usize,
131 }
132
133 impl OwnedResponses {
134 /// Allocates an owned list of responses on the C heap.
135 fn alloc(count: usize) -> Self {
136 OwnedResponses {
137 // SAFETY: We are doing allocation here.
138 base: unsafe { libc::calloc(count, size_of::<RawResponse>()) } as *mut RawResponse,
139 count: count,
140 }
141 }
142
143 /// Takes ownership of a list of responses allocated on the C heap.
144 ///
145 /// # Safety
146 ///
147 /// It's up to you to make sure you pass a valid pointer.
148 unsafe fn from_c_heap(base: *mut RawResponse, count: usize) -> Self {
149 OwnedResponses { base, count }
150 }
151 }
152
153 impl From<OwnedResponses> for *mut RawResponse {
154 /// Converts this into a pointer to `RawResponse`.
155 ///
156 /// The backing data is no longer freed.
157 fn from(value: OwnedResponses) -> Self {
158 let ret = value.base;
159 mem::forget(value);
160 ret
161 }
162 }
163
164 impl Deref for OwnedResponses {
165 type Target = [RawResponse];
166 fn deref(&self) -> &Self::Target {
167 // SAFETY: We allocated this ourselves, or it was provided to us by PAM.
168 unsafe { slice::from_raw_parts(self.base, self.count) }
169 }
170 }
171
172 impl DerefMut for OwnedResponses {
173 fn deref_mut(&mut self) -> &mut Self::Target {
174 // SAFETY: We allocated this ourselves, or it was provided to us by PAM.
175 unsafe { slice::from_raw_parts_mut(self.base, self.count) }
176 }
177 }
178
179 impl Drop for OwnedResponses {
180 fn drop(&mut self) {
181 // SAFETY: We allocated this ourselves, or it was provided to us by PAM.
182 unsafe {
183 for resp in self.iter_mut() {
184 libc::free(resp.data)
185 }
186 libc::free(self.base as *mut c_void)
187 }
188 }
189 }
190
191 #[cfg(test)]
192 mod tests {
193
194 use super::{OwnedResponses, RawBinaryResponse, RawTextResponse};
195
196 #[test]
197 fn test_text_response() {
198 let mut responses = OwnedResponses::alloc(2);
199 let text = RawTextResponse::fill(&mut responses[0], "hello").unwrap();
200 let data = text.contents().expect("valid");
201 assert_eq!("hello", data);
202 unsafe {
203 text.free_contents();
204 text.free_contents();
205 }
206 RawTextResponse::fill(&mut responses[1], "hell\0").expect_err("should error; contains nul");
207 }
208
209 #[test]
210 fn test_binary_response() {
211 let mut responses = OwnedResponses::alloc(1);
212 let real_data = [1, 2, 3, 4, 5, 6, 7, 8];
213 let resp = RawBinaryResponse::fill(&mut responses[0], &real_data, 7)
214 .expect("alloc should succeed");
215 let data = resp.contents();
216 assert_eq!(&real_data, data);
217 assert_eq!(7, resp.data_type());
218 unsafe {
219 resp.free_contents();
220 resp.free_contents();
221 }
222 }
223
224 #[test]
225 #[ignore]
226 fn test_binary_response_too_big() {
227 let big_data: Vec<u8> = vec![0xFFu8; 10_000_000_000];
228 let mut responses = OwnedResponses::alloc(1);
229 RawBinaryResponse::fill(&mut responses[0], &big_data, 0).expect_err("this is too big!");
230 }
231 }