diff src/libpam/pam_ffi.rs @ 90:f6186e41399b

Miscellaneous fixes and cleanup: - Rename `get_user` to `username` and `get_authtok` to `authtok`. - Use pam_strerror for error messages. - Add library linkage to build.rs (it was missing???).
author Paul Fisher <paul@pfish.zone>
date Sat, 14 Jun 2025 09:30:16 -0400
parents dd3e9c4bcde3
children 5ddbcada30f2
line wrap: on
line diff
--- a/src/libpam/pam_ffi.rs	Fri Jun 13 05:22:48 2025 -0400
+++ b/src/libpam/pam_ffi.rs	Sat Jun 14 09:30:16 2025 -0400
@@ -3,8 +3,9 @@
 #![allow(non_camel_case_types)]
 
 use crate::libpam::memory::Immovable;
-use std::ffi::{c_int, c_uint, c_void};
+use std::ffi::{c_int, c_uint, c_void, CStr};
 use std::marker::PhantomData;
+use std::ptr;
 
 /// An opaque structure that a PAM handle points to.
 #[repr(C)]
@@ -28,7 +29,7 @@
 #[derive(Debug)]
 pub struct Answer {
     /// Pointer to the data returned in an answer.
-    /// For most answers, this will be a [`CStr`](std::ffi::CStr),
+    /// For most answers, this will be a [`CStr`],
     /// but for [`BinaryQAndA`](crate::conv::BinaryQAndA)s (a Linux-PAM extension),
     /// this will be [`CBinaryData`](crate::libpam::memory::CBinaryData).
     ///
@@ -53,7 +54,7 @@
     pub style: c_uint,
     /// A description of the data requested.
     ///
-    /// For most requests, this will be an owned [`CStr`](std::ffi::CStr),
+    /// For most requests, this will be an owned [`CStr`],
     /// but for requests with style `PAM_BINARY_PROMPT`,
     /// this will be `CBinaryData` (a Linux-PAM extension).
     pub data: *mut c_void,
@@ -90,6 +91,18 @@
     pub _marker: Immovable,
 }
 
+/// Gets a string version of an error message.
+pub fn strerror(code: c_uint) -> Option<&'static str> {
+    // SAFETY: Every single PAM implementation I can find (Linux-PAM, OpenPAM,
+    // Solaris, etc.) returns a static string and ignores the handle value.
+    let strerror = unsafe { pam_strerror(ptr::null_mut(), code as c_int) };
+    if strerror.is_null() {
+        None
+    } else {
+        unsafe { CStr::from_ptr(strerror) }.to_str().ok()
+    }
+}
+
 type pam_handle = LibPamHandle;
 type pam_conv = LibPamConversation<'static>;