Skip to main content

fprint_backend_libfprint/
worker.rs

1// SPDX-FileCopyrightText: 2026 fprintd (pure-Rust) contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! The per-device worker thread.
6//!
7//! libfprint's `FpContext`/`FpDevice` are `!Send` glib objects, and its only entry points are the
8//! blocking `*_sync` calls, which park the calling thread inside `g_main_context_iteration`. This
9//! thread is that parked thread: it owns the objects and runs every `*_sync`, so the operation
10//! future on the caller thread merely waits on a `Send` reply channel. Because the device never
11//! leaves this thread, only `Send` values ([`Job`] inputs, a [`gio::Cancellable`], the domain
12//! results) cross the boundary — and a dropped future fires the cancellable from the caller thread
13//! to wake the parked `*_sync` here (core principle 4).
14//!
15//! Jobs are serviced strictly one at a time, matching libfprint's single-in-flight contract.
16
17use std::os::raw::c_void;
18use std::sync::mpsc::Receiver;
19use std::sync::{Arc, Mutex};
20
21use fprint_core::{
22    DeviceId, DeviceInfo, EnrollProgress, Error, FingerStatus, IdentifyOutcome, Print, Result,
23    Temperature, VerifyOutcome,
24};
25use futures_channel::mpsc::UnboundedSender;
26use futures_channel::oneshot;
27use gio::Cancellable;
28
29use crate::ffi::{FpContext, FpDevice, FpPrint};
30use crate::progress::{on_enroll_progress, on_match_status, EnrollSink, StatusSink};
31use crate::{convert, print};
32
33/// One unit of work for the worker. Each carries its inputs, the [`Cancellable`] the caller fires
34/// on drop, a oneshot reply, and — for the streaming operations — a progress sender. Every field
35/// is `Send`; the `!Send` device stays on the worker.
36pub(crate) enum Job {
37    Open {
38        cancel: Cancellable,
39        reply: oneshot::Sender<Result<DeviceInfo>>,
40    },
41    Close {
42        cancel: Cancellable,
43        reply: oneshot::Sender<Result<()>>,
44    },
45    Enroll {
46        template: Print,
47        cancel: Cancellable,
48        progress: UnboundedSender<EnrollProgress>,
49        reply: oneshot::Sender<Result<Print>>,
50    },
51    Verify {
52        enrolled: Print,
53        cancel: Cancellable,
54        status: UnboundedSender<FingerStatus>,
55        reply: oneshot::Sender<Result<VerifyOutcome>>,
56    },
57    Identify {
58        gallery: Vec<Print>,
59        cancel: Cancellable,
60        status: UnboundedSender<FingerStatus>,
61        reply: oneshot::Sender<Result<IdentifyOutcome>>,
62    },
63    ListPrints {
64        cancel: Cancellable,
65        reply: oneshot::Sender<Result<Vec<Print>>>,
66    },
67    DeletePrint {
68        print: Print,
69        cancel: Cancellable,
70        reply: oneshot::Sender<Result<()>>,
71    },
72    ClearStorage {
73        cancel: Cancellable,
74        reply: oneshot::Sender<Result<()>>,
75    },
76    Suspend {
77        cancel: Cancellable,
78        reply: oneshot::Sender<Result<()>>,
79    },
80    Resume {
81        cancel: Cancellable,
82        reply: oneshot::Sender<Result<()>>,
83    },
84    /// Sent by the handle's `Drop`: release the sensor and end the loop.
85    Shutdown,
86}
87
88/// The worker's serial loop. It builds its own `FpContext` (the objects are thread-affine, so it
89/// cannot borrow the caller's), re-finds the device by id, then services one [`Job`] at a time
90/// until told to shut down or the handle drops its sender. The sensor is closed here, on this
91/// thread, before it returns.
92///
93/// `temperature` is the cell the handle's live [`Device::temperature`](fprint_core::Device::temperature)
94/// getter reads: after each job that has an open device, the worker samples the sensor's thermal
95/// state and publishes it here, so the `Send` handle can answer the getter without a round-trip.
96pub(crate) fn run(id: DeviceId, jobs: Receiver<Job>, temperature: Arc<Mutex<Option<Temperature>>>) {
97    let ctx = FpContext::new();
98    let device = find_device(&ctx, &id);
99    let dev = device.as_ref();
100
101    for job in jobs {
102        match job {
103            Job::Shutdown => break,
104            Job::Open { cancel, reply } => {
105                let _ = reply.send(with(dev, |d| {
106                    d.open_sync(Some(&cancel)).map_err(convert::from_gerror)?;
107                    // Features, scan type and stage count firm up only once the device is open.
108                    Ok(convert::device_info(d))
109                }));
110            }
111            Job::Close { cancel, reply } => {
112                let _ = reply.send(with(dev, |d| {
113                    d.close_sync(Some(&cancel)).map_err(convert::from_gerror)
114                }));
115            }
116            Job::Enroll {
117                template,
118                cancel,
119                progress,
120                reply,
121            } => {
122                let _ = reply.send(with(dev, |d| {
123                    let fp = print::core_to_fp(&template, d);
124                    let sink = EnrollSink {
125                        tx: progress,
126                        total: d.nr_enroll_stages().max(0) as u32,
127                        temperature: temperature.clone(),
128                    };
129                    let enrolled = d
130                        .enroll_sync(
131                            fp,
132                            Some(&cancel),
133                            Some(on_enroll_progress),
134                            std::ptr::addr_of!(sink) as *mut c_void,
135                        )
136                        .map_err(convert::from_gerror)?;
137                    print::fp_to_core(&enrolled)
138                }));
139            }
140            Job::Verify {
141                enrolled,
142                cancel,
143                status,
144                reply,
145            } => {
146                let _ = reply.send(with(dev, |d| {
147                    let fp = print::core_to_fp_for_match(&enrolled)?;
148                    let sink = StatusSink {
149                        tx: status,
150                        temperature: temperature.clone(),
151                    };
152                    let (matched, scanned) = d
153                        .verify_sync(
154                            &fp,
155                            Some(&cancel),
156                            Some(on_match_status),
157                            std::ptr::addr_of!(sink) as *mut c_void,
158                        )
159                        .map_err(convert::from_gerror)?;
160
161                    // Match-on-chip sensors do not surface the live scan; a `None` here means "no
162                    // scan surfaced" rather than a failure.
163                    Ok(VerifyOutcome::new(
164                        matched,
165                        scanned.and_then(|s| print::fp_to_core(&s).ok()),
166                    ))
167                }));
168            }
169            Job::Identify {
170                gallery,
171                cancel,
172                status,
173                reply,
174            } => {
175                let _ = reply.send(with(dev, |d| {
176                    let fps = gallery
177                        .iter()
178                        .map(print::core_to_fp_for_match)
179                        .collect::<Result<Vec<FpPrint>>>()?;
180                    let sink = StatusSink {
181                        tx: status,
182                        temperature: temperature.clone(),
183                    };
184                    let (matched, scanned) = d
185                        .identify_sync(
186                            &fps,
187                            Some(&cancel),
188                            Some(on_match_status),
189                            std::ptr::addr_of!(sink) as *mut c_void,
190                        )
191                        .map_err(convert::from_gerror)?;
192
193                    // Recover the gallery index by comparing the matched print's serialization to
194                    // each candidate's — libfprint hands back the matching `FpPrint`, not its index.
195                    let match_index = match matched {
196                        Some(m) => {
197                            let needle = m.serialize().map_err(convert::from_gerror)?;
198                            fps.iter().position(|p| {
199                                p.serialize().ok().as_deref() == Some(needle.as_slice())
200                            })
201                        }
202                        None => None,
203                    };
204                    Ok(IdentifyOutcome::new(
205                        match_index,
206                        scanned.and_then(|s| print::fp_to_core(&s).ok()),
207                    ))
208                }));
209            }
210            Job::ListPrints { cancel, reply } => {
211                let _ = reply.send(with(dev, |d| {
212                    d.list_prints_sync(Some(&cancel))
213                        .map_err(convert::from_gerror)?
214                        .iter()
215                        .map(print::fp_to_core)
216                        .collect()
217                }));
218            }
219            Job::DeletePrint {
220                print: stored,
221                cancel,
222                reply,
223            } => {
224                let _ = reply.send(with(dev, |d| {
225                    let fp = print::core_to_fp_for_match(&stored)?;
226                    d.delete_print_sync(&fp, Some(&cancel))
227                        .map_err(convert::from_gerror)
228                }));
229            }
230            Job::ClearStorage { cancel, reply } => {
231                let _ = reply.send(with(dev, |d| {
232                    d.clear_storage_sync(Some(&cancel))
233                        .map_err(convert::from_gerror)
234                }));
235            }
236            Job::Suspend { cancel, reply } => {
237                let _ = reply.send(with(dev, |d| {
238                    d.suspend_sync(Some(&cancel)).map_err(convert::from_gerror)
239                }));
240            }
241            Job::Resume { cancel, reply } => {
242                let _ = reply.send(with(dev, |d| {
243                    d.resume_sync(Some(&cancel)).map_err(convert::from_gerror)
244                }));
245            }
246        }
247
248        // Publish the sensor's live thermal state for the handle's `Device::temperature` getter.
249        // Only an open device reports it; before `open` the cell stays `None` (unknown).
250        if let Some(d) = dev {
251            if d.is_open() {
252                *temperature.lock().unwrap() = convert::temperature(d);
253            }
254        }
255    }
256
257    if let Some(d) = dev {
258        if d.is_open() {
259            // Release the sensor before the thread — and the objects — go away.
260            let _ = d.close_sync(None);
261        }
262    }
263}
264
265/// Run `f` against the worker's device, or report [`Error::NotFound`] if the device vanished
266/// between the caller-thread enumeration and this thread re-finding it.
267fn with<T>(dev: Option<&FpDevice>, f: impl FnOnce(&FpDevice) -> Result<T>) -> Result<T> {
268    match dev {
269        Some(d) => f(d),
270        None => Err(Error::NotFound),
271    }
272}
273
274/// Re-find the device by id in this thread's own context. Mirrors [`crate::LibfprintBackend`]'s
275/// open-by-id lookup: match on libfprint's `device_id`, falling back to the driver id when
276/// `device_id` is empty (as it is for the virtual debug devices).
277fn find_device(ctx: &FpContext, id: &DeviceId) -> Option<FpDevice> {
278    ctx.devices().into_iter().find(|dev| {
279        let device_id = dev.device_id();
280        if device_id.is_empty() {
281            dev.driver() == id.as_str()
282        } else {
283            device_id == id.as_str()
284        }
285    })
286}