fprint_backend_libfprint/ffi.rs
1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Rust ownership over the C libfprint objects.
6//!
7//! The shim links libfprint through `libfprint-sys` (raw bindgen) and owns the GObject lifetime
8//! itself: [`FpContext`], [`FpDevice`] and [`FpPrint`] are thin [`glib::wrapper!`] types whose
9//! ref/unref — and, for the floating [`FpPrint`], ref-sink — is handled by glib's translate
10//! traits. Every `unsafe` block below names the libfprint entry point it calls and the transfer
11//! semantics it relies on; outside this module only the same-thread callback trampolines in
12//! [`crate::progress`] touch a raw pointer.
13
14use std::os::raw::c_void;
15use std::ptr;
16
17use gio::Cancellable;
18use glib::translate::{
19 from_glib_full, from_glib_none, FromGlibContainer, FromGlibPtrContainer, FromGlibPtrFull,
20 FromGlibPtrNone, ToGlibContainerFromSlice, ToGlibPtr,
21};
22
23glib::wrapper! {
24 /// libfprint's discovery root (`FpContext`).
25 pub(crate) struct FpContext(Object<libfprint_sys::FpContext, libfprint_sys::FpContextClass>);
26
27 match fn {
28 type_ => || libfprint_sys::fp_context_get_type() as usize,
29 }
30}
31
32glib::wrapper! {
33 /// A fingerprint reader (`FpDevice`).
34 pub(crate) struct FpDevice(Object<libfprint_sys::FpDevice, libfprint_sys::FpDeviceClass>);
35
36 match fn {
37 type_ => || libfprint_sys::fp_device_get_type() as usize,
38 }
39}
40
41glib::wrapper! {
42 /// A fingerprint template (`FpPrint`). It derives from `GInitiallyUnowned`, so a fresh one
43 /// carries a floating reference that [`FpPrint::new`] sinks.
44 pub(crate) struct FpPrint(Object<libfprint_sys::FpPrint, libfprint_sys::FpPrintClass>)
45 @extends glib::object::InitiallyUnowned;
46
47 match fn {
48 type_ => || libfprint_sys::fp_print_get_type() as usize,
49 }
50}
51
52/// `gio` and `libfprint-sys` each carry their own bindgen `GCancellable`, so the glib-native
53/// pointer is cast across the two. Returns NULL for `None` (libfprint reads that as "no
54/// cancellable"). The pointer borrows `cancel`; a `GObject` `to_glib_none` allocates no temporary,
55/// so it stays valid for as long as `cancel` lives.
56fn raw_cancel(cancel: Option<&Cancellable>) -> *mut libfprint_sys::GCancellable {
57 match cancel {
58 Some(c) => {
59 let ptr: *mut gio::ffi::GCancellable = c.to_glib_none().0;
60 ptr.cast()
61 }
62 None => ptr::null_mut(),
63 }
64}
65
66/// Wrap a possibly-NULL, transfer-full `FpPrint*` out-parameter (the match/scan slots of
67/// verify/identify) as an owned [`FpPrint`].
68fn out_print(raw: *mut libfprint_sys::FpPrint) -> Option<FpPrint> {
69 if raw.is_null() {
70 None
71 } else {
72 // SAFETY: a non-NULL match/scan out-pointer written by `fp_device_verify_sync` /
73 // `fp_device_identify_sync` is transfer-full; `from_glib_full` takes its reference.
74 Some(unsafe { from_glib_full(raw) })
75 }
76}
77
78impl FpContext {
79 /// Create a fresh context.
80 pub(crate) fn new() -> FpContext {
81 // SAFETY: `fp_context_new` returns a transfer-full `FpContext`; `from_glib_full` takes
82 // that single reference.
83 unsafe { from_glib_full(libfprint_sys::fp_context_new()) }
84 }
85
86 /// The readers the context currently knows about.
87 pub(crate) fn devices(&self) -> Vec<FpDevice> {
88 // SAFETY: `fp_context_get_devices` returns a transfer-none `GPtrArray` of `FpDevice*`
89 // owned by the context; `from_glib_none` copies the Vec and refs each borrowed element.
90 unsafe {
91 let array = libfprint_sys::fp_context_get_devices(self.to_glib_none().0);
92 FromGlibPtrContainer::from_glib_none(array.cast::<glib::ffi::GPtrArray>())
93 }
94 }
95}
96
97/// libfprint's `(device, cancellable, error) -> gboolean` sync entry points, shared by the
98/// operations with no callback or return value.
99type BoolSyncFn = unsafe extern "C" fn(
100 *mut libfprint_sys::FpDevice,
101 *mut libfprint_sys::GCancellable,
102 *mut *mut libfprint_sys::GError,
103) -> libfprint_sys::gboolean;
104
105impl FpDevice {
106 /// The driver id (e.g. `virtual_device`).
107 pub(crate) fn driver(&self) -> String {
108 // SAFETY: `fp_device_get_driver` returns a device-owned (transfer-none) C string; copied.
109 unsafe {
110 let ptr = libfprint_sys::fp_device_get_driver(self.to_glib_none().0);
111 glib::GString::from_glib_none(ptr).into()
112 }
113 }
114
115 /// The device id, empty for the virtual debug devices.
116 pub(crate) fn device_id(&self) -> String {
117 // SAFETY: `fp_device_get_device_id` returns a device-owned (transfer-none) C string; copied.
118 unsafe {
119 let ptr = libfprint_sys::fp_device_get_device_id(self.to_glib_none().0);
120 glib::GString::from_glib_none(ptr).into()
121 }
122 }
123
124 /// The human-readable name, or `None` when the driver exposes none.
125 pub(crate) fn name(&self) -> Option<String> {
126 // SAFETY: `fp_device_get_name` is a pure getter returning a device-owned (transfer-none)
127 // C string or NULL; `from_glib_none` copies it without taking ownership.
128 unsafe {
129 let ptr = libfprint_sys::fp_device_get_name(self.to_glib_none().0);
130 (!ptr.is_null()).then(|| glib::GString::from_glib_none(ptr).into())
131 }
132 }
133
134 /// Whether the sensor is currently open.
135 pub(crate) fn is_open(&self) -> bool {
136 // SAFETY: `fp_device_is_open` is a pure boolean getter on the live device.
137 unsafe { libfprint_sys::fp_device_is_open(self.to_glib_none().0) != glib::ffi::GFALSE }
138 }
139
140 /// The raw `FpScanType`.
141 pub(crate) fn scan_type(&self) -> u32 {
142 // SAFETY: `fp_device_get_scan_type` is a pure getter returning an `FpScanType`.
143 unsafe { libfprint_sys::fp_device_get_scan_type(self.to_glib_none().0) }
144 }
145
146 /// The raw `FpDeviceFeature` bitmask.
147 pub(crate) fn features(&self) -> u32 {
148 // SAFETY: `fp_device_get_features` is a pure getter returning the feature bitmask.
149 unsafe { libfprint_sys::fp_device_get_features(self.to_glib_none().0) }
150 }
151
152 /// The raw `FpTemperature`.
153 pub(crate) fn temperature(&self) -> u32 {
154 // SAFETY: `fp_device_get_temperature` is a pure getter returning the thermal state.
155 unsafe { libfprint_sys::fp_device_get_temperature(self.to_glib_none().0) }
156 }
157
158 /// The raw `FpFingerStatusFlags` bitmask.
159 pub(crate) fn finger_status(&self) -> u32 {
160 // SAFETY: `fp_device_get_finger_status` is a pure getter returning the status flags.
161 unsafe { libfprint_sys::fp_device_get_finger_status(self.to_glib_none().0) }
162 }
163
164 /// The number of enroll stages (negative before the device settles it).
165 pub(crate) fn nr_enroll_stages(&self) -> i32 {
166 // SAFETY: `fp_device_get_nr_enroll_stages` is a pure getter.
167 unsafe { libfprint_sys::fp_device_get_nr_enroll_stages(self.to_glib_none().0) }
168 }
169
170 /// Drive one of the `(device, cancellable, error) -> gboolean` sync ops.
171 fn bool_sync(&self, cancel: Option<&Cancellable>, f: BoolSyncFn) -> Result<(), glib::Error> {
172 let mut error = ptr::null_mut();
173 // SAFETY: `f` is one of libfprint's `(device, cancellable, error) -> gboolean` sync entry
174 // points; it runs on the live `self` with a live-or-null cancellable and, on FALSE, sets
175 // `error` transfer-full.
176 let ok = unsafe { f(self.to_glib_none().0, raw_cancel(cancel), &mut error) };
177 if ok == glib::ffi::GFALSE {
178 // SAFETY: `error` was set transfer-full by the failing call above.
179 Err(unsafe { glib::Error::from_glib_full(error.cast()) })
180 } else {
181 Ok(())
182 }
183 }
184
185 pub(crate) fn open_sync(&self, cancel: Option<&Cancellable>) -> Result<(), glib::Error> {
186 self.bool_sync(cancel, libfprint_sys::fp_device_open_sync)
187 }
188
189 pub(crate) fn close_sync(&self, cancel: Option<&Cancellable>) -> Result<(), glib::Error> {
190 self.bool_sync(cancel, libfprint_sys::fp_device_close_sync)
191 }
192
193 pub(crate) fn suspend_sync(&self, cancel: Option<&Cancellable>) -> Result<(), glib::Error> {
194 self.bool_sync(cancel, libfprint_sys::fp_device_suspend_sync)
195 }
196
197 pub(crate) fn resume_sync(&self, cancel: Option<&Cancellable>) -> Result<(), glib::Error> {
198 self.bool_sync(cancel, libfprint_sys::fp_device_resume_sync)
199 }
200
201 pub(crate) fn clear_storage_sync(
202 &self,
203 cancel: Option<&Cancellable>,
204 ) -> Result<(), glib::Error> {
205 self.bool_sync(cancel, libfprint_sys::fp_device_clear_storage_sync)
206 }
207
208 /// Run a full enrollment. `progress`/`progress_data` are libfprint's per-stage callback and
209 /// its opaque user-data (a same-thread `&EnrollSink`), invoked synchronously during the call.
210 pub(crate) fn enroll_sync(
211 &self,
212 template: FpPrint,
213 cancel: Option<&Cancellable>,
214 progress: libfprint_sys::FpEnrollProgress,
215 progress_data: *mut c_void,
216 ) -> Result<FpPrint, glib::Error> {
217 let mut error = ptr::null_mut();
218 // SAFETY: `fp_device_enroll_sync` drives enrollment on the live `self`. `template` is
219 // `(transfer floating)`: libfprint ref-sinks it, so we pass a borrowed pointer and keep
220 // our own reference (dropped with `template` below). It returns a transfer-full `FpPrint`
221 // on success, or NULL with `error` set transfer-full.
222 let print = unsafe {
223 libfprint_sys::fp_device_enroll_sync(
224 self.to_glib_none().0,
225 template.to_glib_none().0,
226 raw_cancel(cancel),
227 progress,
228 progress_data,
229 &mut error,
230 )
231 };
232 if print.is_null() {
233 // SAFETY: `error` was set transfer-full by the failing call above.
234 Err(unsafe { glib::Error::from_glib_full(error.cast()) })
235 } else {
236 // SAFETY: `print` is the transfer-full enrolled `FpPrint`.
237 Ok(unsafe { from_glib_full(print) })
238 }
239 }
240
241 /// Verify against `enrolled`. Returns `(matched, scanned)`, where `scanned` is the live scan
242 /// when the driver surfaces one. `match_cb`/`match_data` are libfprint's same-thread callback.
243 pub(crate) fn verify_sync(
244 &self,
245 enrolled: &FpPrint,
246 cancel: Option<&Cancellable>,
247 match_cb: libfprint_sys::FpMatchCb,
248 match_data: *mut c_void,
249 ) -> Result<(bool, Option<FpPrint>), glib::Error> {
250 let mut error = ptr::null_mut();
251 let mut matched = glib::ffi::GFALSE;
252 let mut scanned: *mut libfprint_sys::FpPrint = ptr::null_mut();
253 // SAFETY: `fp_device_verify_sync` verifies the live `self` against the borrowed
254 // (transfer-none) `enrolled` print. `matched` receives the boolean result; `scanned`
255 // receives a transfer-full `FpPrint` or stays NULL. On failure it returns FALSE with
256 // `error` set transfer-full.
257 let ok = unsafe {
258 libfprint_sys::fp_device_verify_sync(
259 self.to_glib_none().0,
260 enrolled.to_glib_none().0,
261 raw_cancel(cancel),
262 match_cb,
263 match_data,
264 &mut matched,
265 &mut scanned,
266 &mut error,
267 )
268 };
269 if ok == glib::ffi::GFALSE {
270 // SAFETY: `error` was set transfer-full by the failing call above.
271 return Err(unsafe { glib::Error::from_glib_full(error.cast()) });
272 }
273 Ok((matched != glib::ffi::GFALSE, out_print(scanned)))
274 }
275
276 /// Identify `self`'s scan against `gallery`. Returns `(matched, scanned)`, where `matched` is
277 /// the gallery print libfprint hands back (not its index).
278 pub(crate) fn identify_sync(
279 &self,
280 gallery: &[FpPrint],
281 cancel: Option<&Cancellable>,
282 match_cb: libfprint_sys::FpMatchCb,
283 match_data: *mut c_void,
284 ) -> Result<(Option<FpPrint>, Option<FpPrint>), glib::Error> {
285 let mut error = ptr::null_mut();
286 let mut matched: *mut libfprint_sys::FpPrint = ptr::null_mut();
287 let mut scanned: *mut libfprint_sys::FpPrint = ptr::null_mut();
288 let (array, _elements): (*mut glib::ffi::GPtrArray, _) =
289 ToGlibContainerFromSlice::to_glib_container_from_slice(gallery);
290 // SAFETY: `fp_device_identify_sync` matches the live `self` against the borrowed
291 // (transfer-none) `array` of gallery prints. `matched`/`scanned` receive transfer-full
292 // `FpPrint`s or stay NULL. On failure it returns FALSE with `error` set transfer-full.
293 let ok = unsafe {
294 libfprint_sys::fp_device_identify_sync(
295 self.to_glib_none().0,
296 array.cast(),
297 raw_cancel(cancel),
298 match_cb,
299 match_data,
300 &mut matched,
301 &mut scanned,
302 &mut error,
303 )
304 };
305 // SAFETY: `array` came from `to_glib_container_from_slice` with no element free-func, so
306 // freeing the segment (TRUE) releases the container without touching the borrowed elements.
307 unsafe { glib::ffi::g_ptr_array_free(array, glib::ffi::GTRUE) };
308 if ok == glib::ffi::GFALSE {
309 // SAFETY: `error` was set transfer-full by the failing call above.
310 return Err(unsafe { glib::Error::from_glib_full(error.cast()) });
311 }
312 Ok((out_print(matched), out_print(scanned)))
313 }
314
315 /// List the templates stored on the sensor.
316 pub(crate) fn list_prints_sync(
317 &self,
318 cancel: Option<&Cancellable>,
319 ) -> Result<Vec<FpPrint>, glib::Error> {
320 let mut error = ptr::null_mut();
321 // SAFETY: `fp_device_list_prints_sync` returns, on success, a `(transfer container)`
322 // `GPtrArray` of `FpPrint*`: ours to free, its `g_object_unref` element free-func dropping
323 // each element's ref when we do. On failure it returns NULL with `error` set transfer-full.
324 let array = unsafe {
325 libfprint_sys::fp_device_list_prints_sync(
326 self.to_glib_none().0,
327 raw_cancel(cancel),
328 &mut error,
329 )
330 };
331 if array.is_null() {
332 // SAFETY: `error` was set transfer-full by the failing call above.
333 Err(unsafe { glib::Error::from_glib_full(error.cast()) })
334 } else {
335 // SAFETY: `array` is a `(transfer container)` `GPtrArray`; `from_glib_full` copies each
336 // element out with one ref of its own and frees the container — for these GObject
337 // elements identical to `from_glib_container`, honouring the container-only transfer.
338 Ok(unsafe {
339 FromGlibPtrContainer::from_glib_full(array.cast::<glib::ffi::GPtrArray>())
340 })
341 }
342 }
343
344 /// Delete one stored template by its device-side handle.
345 pub(crate) fn delete_print_sync(
346 &self,
347 print: &FpPrint,
348 cancel: Option<&Cancellable>,
349 ) -> Result<(), glib::Error> {
350 let mut error = ptr::null_mut();
351 // SAFETY: `fp_device_delete_print_sync` deletes the borrowed (transfer-none) `print` from
352 // the live `self`, returning FALSE with `error` set transfer-full on failure.
353 let ok = unsafe {
354 libfprint_sys::fp_device_delete_print_sync(
355 self.to_glib_none().0,
356 print.to_glib_none().0,
357 raw_cancel(cancel),
358 &mut error,
359 )
360 };
361 if ok == glib::ffi::GFALSE {
362 // SAFETY: `error` was set transfer-full by the failing call above.
363 Err(unsafe { glib::Error::from_glib_full(error.cast()) })
364 } else {
365 Ok(())
366 }
367 }
368}
369
370impl FpPrint {
371 /// A fresh template bound to `dev`, ready to be filled in and enrolled.
372 pub(crate) fn new(dev: &FpDevice) -> FpPrint {
373 // SAFETY: `fp_print_new` returns a floating `FpPrint` for the live `dev`; `from_glib_none`
374 // ref-sinks it (FpPrint `@extends InitiallyUnowned`), giving sole ownership with no leak.
375 unsafe { from_glib_none(libfprint_sys::fp_print_new(dev.to_glib_none().0)) }
376 }
377
378 /// The driver the print was made for (transfer-none getter).
379 pub(crate) fn driver(&self) -> String {
380 // SAFETY: `fp_print_get_driver` returns a print-owned (transfer-none) C string; copied.
381 unsafe {
382 let ptr = libfprint_sys::fp_print_get_driver(self.to_glib_none().0);
383 glib::GString::from_glib_none(ptr).into()
384 }
385 }
386
387 /// The device id the print was made for (transfer-none getter).
388 pub(crate) fn device_id(&self) -> String {
389 // SAFETY: `fp_print_get_device_id` returns a print-owned (transfer-none) C string; copied.
390 unsafe {
391 let ptr = libfprint_sys::fp_print_get_device_id(self.to_glib_none().0);
392 glib::GString::from_glib_none(ptr).into()
393 }
394 }
395
396 /// Whether the print is a handle to a template stored on the device.
397 pub(crate) fn device_stored(&self) -> bool {
398 // SAFETY: `fp_print_get_device_stored` is a pure boolean getter on the live print.
399 unsafe {
400 libfprint_sys::fp_print_get_device_stored(self.to_glib_none().0) != glib::ffi::GFALSE
401 }
402 }
403
404 pub(crate) fn set_finger(&self, finger: libfprint_sys::FpFinger) {
405 // SAFETY: `fp_print_set_finger` sets a plain enum field on the live print.
406 unsafe { libfprint_sys::fp_print_set_finger(self.to_glib_none().0, finger) };
407 }
408
409 pub(crate) fn set_username(&self, username: &str) {
410 // SAFETY: `fp_print_set_username` copies the passed UTF-8 C string into the live print;
411 // the `to_glib_none` temporary lives for the duration of the call.
412 unsafe {
413 libfprint_sys::fp_print_set_username(self.to_glib_none().0, username.to_glib_none().0);
414 }
415 }
416
417 pub(crate) fn set_description(&self, description: &str) {
418 // SAFETY: `fp_print_set_description` copies the passed UTF-8 C string into the live print;
419 // the `to_glib_none` temporary lives for the duration of the call.
420 unsafe {
421 libfprint_sys::fp_print_set_description(
422 self.to_glib_none().0,
423 description.to_glib_none().0,
424 );
425 }
426 }
427
428 /// Serialize to the canonical FP3 blob (`"FP3"` + GVariant).
429 pub(crate) fn serialize(&self) -> Result<Vec<u8>, glib::Error> {
430 let mut data = ptr::null_mut();
431 let mut len = 0;
432 let mut error = ptr::null_mut();
433 // SAFETY: `fp_print_serialize` writes a transfer-full `guchar*`/length pair on success, or
434 // FALSE with `error` set transfer-full. `from_glib_full_num` copies the buffer into a Vec
435 // and g_frees it; `from_glib_full` takes the error.
436 unsafe {
437 libfprint_sys::fp_print_serialize(
438 self.to_glib_none().0,
439 &mut data,
440 &mut len,
441 &mut error,
442 );
443 if error.is_null() {
444 Ok(Vec::from_glib_full_num(data, len as usize))
445 } else {
446 Err(glib::Error::from_glib_full(error.cast()))
447 }
448 }
449 }
450
451 /// Deserialize a template from its FP3 blob.
452 pub(crate) fn deserialize(bytes: &[u8]) -> Result<FpPrint, glib::Error> {
453 let mut error = ptr::null_mut();
454 // SAFETY: `fp_print_deserialize` reads `bytes` and returns a transfer-full `FpPrint`, or
455 // NULL with `error` set transfer-full.
456 let print = unsafe {
457 libfprint_sys::fp_print_deserialize(
458 bytes.as_ptr(),
459 bytes.len() as libfprint_sys::gsize,
460 &mut error,
461 )
462 };
463 if print.is_null() {
464 // SAFETY: `error` was set transfer-full by the failing call above.
465 Err(unsafe { glib::Error::from_glib_full(error.cast()) })
466 } else {
467 // SAFETY: `print` is the transfer-full deserialized `FpPrint`.
468 Ok(unsafe { from_glib_full(print) })
469 }
470 }
471}