pam_kanidm/pam/
conv.rs

1use std::ffi::{CStr, CString};
2use std::ptr;
3
4use libc::{c_char, c_int};
5
6use crate::pam::constants::{PamResultCode, *};
7use crate::pam::module::{PamItem, PamResult};
8
9#[allow(missing_copy_implementations)]
10pub enum AppDataPtr {}
11
12#[repr(C)]
13struct PamMessage {
14    msg_style: PamMessageStyle,
15    msg: *const c_char,
16}
17
18#[repr(C)]
19struct PamResponse {
20    resp: *const c_char,
21    resp_retcode: AlwaysZero,
22}
23
24/// `PamConv` acts as a channel for communicating with user.
25///
26/// Communication is mediated by the pam client (the application that invoked
27/// pam).  Messages sent will be relayed to the user by the client, and response
28/// will be relayed back.
29#[repr(C)]
30pub struct PamConv {
31    conv: extern "C" fn(
32        num_msg: c_int,
33        pam_message: &&PamMessage,
34        pam_response: &mut *const PamResponse,
35        appdata_ptr: *const AppDataPtr,
36    ) -> PamResultCode,
37    appdata_ptr: *const AppDataPtr,
38}
39
40impl PamConv {
41    /// Sends a message to the pam client.
42    ///
43    /// This will typically result in the user seeing a message or a prompt.
44    /// There are several message styles available:
45    ///
46    /// - PAM_PROMPT_ECHO_OFF
47    /// - PAM_PROMPT_ECHO_ON
48    /// - PAM_ERROR_MSG
49    /// - PAM_TEXT_INFO
50    /// - PAM_RADIO_TYPE
51    /// - PAM_BINARY_PROMPT
52    ///
53    /// Note that the user experience will depend on how the client implements
54    /// these message styles - and not all applications implement all message
55    /// styles.
56    pub fn send(&self, style: PamMessageStyle, msg: &str) -> PamResult<Option<String>> {
57        let mut resp_ptr: *const PamResponse = ptr::null();
58        let msg_cstr = CString::new(msg).map_err(|_| PamResultCode::PAM_CONV_ERR)?;
59        let msg = PamMessage {
60            msg_style: style,
61            msg: msg_cstr.as_ptr(),
62        };
63
64        let ret = (self.conv)(1, &&msg, &mut resp_ptr, self.appdata_ptr);
65
66        if PamResultCode::PAM_SUCCESS == ret {
67            // PamResponse.resp is null for styles that don't return user input like PAM_TEXT_INFO
68            let response = unsafe { (*resp_ptr).resp };
69            if response.is_null() {
70                Ok(None)
71            } else {
72                let bytes = unsafe { CStr::from_ptr(response).to_bytes() };
73                Ok(String::from_utf8(bytes.to_vec()).ok())
74            }
75        } else {
76            Err(ret)
77        }
78    }
79}
80
81impl PamItem for PamConv {
82    fn item_type() -> PamItemType {
83        PAM_CONV
84    }
85}