#!/usr/bin/env python3 """fprintd-compatible D-Bus service backed by the Wine-sandbox driver. Drop-in replacement for fprintd's daemon for the Synaptics 06cb:0081 sensor that libfprint cannot drive yet. It serves the `net.reactivated.Fprint` bus name with the same Manager/Device API, so GNOME Shell (lock-screen re-authentication), gnome-control-center and pam_fprintd work unchanged. Verification shells out to work/fp-verify.sh (vendor driver under Wine, run as the Wine-prefix owner). Enrollment and deletion drive the harness binaries built by work/artifacts/make-enroll-delete.sh: enroll.exe - default flow trimmed to enrollment (touch ~10 times) delete.exe - default flow with enroll() redirected to deleteRecord() (real sensor-side delete, ioctl 0x442034) The sensor stores a single template (identity c5698517-.../subfactor 0xF6), so the per-user finger list in state.json is a mapping onto that one template: deleting the last reported finger deletes the sensor record, deleting one of several only updates the reported list. Run with --session for a session-bus smoke test (no root needed, see selftest.py / apitest.py). """ import argparse import glob import json import logging import os import select import signal import subprocess import sys import threading import time import gi gi.require_version('Gio', '2.0') gi.require_version('GLib', '2.0') from gi.repository import Gio, GLib # noqa: E402 # ---------------------------------------------------------------- constants BUS_NAME = 'net.reactivated.Fprint' MANAGER_PATH = '/net/reactivated/Fprint/Manager' DEVICE_PATH = '/net/reactivated/Fprint/Device/0' IFACE_MANAGER = 'net.reactivated.Fprint.Manager' IFACE_DEVICE = 'net.reactivated.Fprint.Device' HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(os.path.dirname(HERE)) VERIFY_SCRIPT = os.path.join(ROOT, 'work', 'fp-verify.sh') SANDBOX = os.path.join(ROOT, 'work', 'synaWudfBioUsb-sandbox') WINE64 = os.path.join(ROOT, 'work', 'wine-build', 'install', 'bin', 'wine64') ENROLL_EXE = 'enroll.exe' DELETE_EXE = 'delete.exe' # same lock file as work/fp-verify.sh: one sensor access at a time VERIFY_LOCK = '/tmp/opencode/fp-verify.lock' RUN_USER = 'nebulon' STATE_DIR = os.environ.get('FP_SHIM_STATE_DIR', '/var/lib/fprintd-shim') STATE_FILE = os.path.join(STATE_DIR, 'state.json') DEVICE_NAME = 'Synaptics 06cb:0081' SCAN_TYPE = 'press' NUM_ENROLL_STAGES = 10 # pam_fprintd's default per-attempt timeout is 30 s; end our run slightly # earlier so a no-touch attempt is a clean pam timeout instead of a bogus # "failed to match". VERIFY_TIMEOUT = int(os.environ.get('FP_SHIM_VERIFY_TIMEOUT', '26')) ENROLL_TIMEOUT = int(os.environ.get('FP_SHIM_ENROLL_TIMEOUT', '900')) DELETE_TIMEOUT = int(os.environ.get('FP_SHIM_DELETE_TIMEOUT', '180')) FINGERS = [ 'left-thumb', 'left-index-finger', 'left-middle-finger', 'left-ring-finger', 'left-little-finger', 'right-thumb', 'right-index-finger', 'right-middle-finger', 'right-ring-finger', 'right-little-finger', ] # Bus errors E_ALREADY_IN_USE = 'net.reactivated.Fprint.Error.AlreadyInUse' E_CLAIM_DEVICE = 'net.reactivated.Fprint.Error.ClaimDevice' E_INTERNAL = 'net.reactivated.Fprint.Error.Internal' E_INVALID_FINGERNAME = 'net.reactivated.Fprint.Error.InvalidFingername' E_NO_ACTION = 'net.reactivated.Fprint.Error.NoActionInProgress' E_NO_ENROLLED_PRINTS = 'net.reactivated.Fprint.Error.NoEnrolledPrints' E_NO_SUCH_DEVICE = 'net.reactivated.Fprint.Error.NoSuchDevice' E_PERMISSION_DENIED = 'net.reactivated.Fprint.Error.PermissionDenied' E_PRINTS_NOT_DELETED = 'net.reactivated.Fprint.Error.PrintsNotDeleted' log = logging.getLogger('fprintd-shim') MANAGER_XML = """ """ DEVICE_XML = """ """ def sensor_present(): """06cb:0081 attached? Mirrors fprintd's "no devices" behaviour.""" try: for dev in glob.glob('/sys/bus/usb/devices/*'): try: with open(os.path.join(dev, 'idVendor')) as f: vid = f.read().strip() if vid != '06cb': continue with open(os.path.join(dev, 'idProduct')) as f: pid = f.read().strip() if pid == '0081': return True except OSError: continue except OSError: pass return False def default_fingers(user): """Before any enroll/delete through the shim the sensor already holds the template enrolled with run_aexe.sh; report it for the workstation user.""" return ['right-index-finger'] if user == RUN_USER else [] def load_state(): try: with open(STATE_FILE, encoding='utf-8') as f: state = json.load(f) if isinstance(state, dict) and isinstance(state.get('users'), dict): return state log.warning('%s: unexpected layout, ignoring', STATE_FILE) except FileNotFoundError: pass except (OSError, ValueError) as e: log.warning('cannot read %s: %s', STATE_FILE, e) return {'users': {}} def save_state(state): os.makedirs(STATE_DIR, mode=0o700, exist_ok=True) tmp = f'{STATE_FILE}.tmp' with open(tmp, 'w', encoding='utf-8') as f: json.dump(state, f, indent=2, sort_keys=True) f.write('\n') os.replace(tmp, STATE_FILE) class ShimDevice: def __init__(self): self.conn = None self.claimed_by = None # unique bus name of the claiming client self.claimed_user = None self.lock = threading.Lock() self.verify_proc = None self.verify_thread = None self.verify_cancel = threading.Event() self.verifying = False self.enroll_proc = None self.enroll_thread = None self.enroll_cancel = threading.Event() self.enrolling = False self._enroll_commit_started = False self.delete_proc = None self.delete_cancel = threading.Event() self.deleting = False self.finger_present = False self.finger_needed = False # ------------------------------------------------------------ state def enrolled_fingers(self, user): if not user: user = RUN_USER users = load_state().get('users', {}) if user in users: return list(users[user]) return default_fingers(user) def _set_enrolled_fingers(self, user, fingers): state = load_state() state.setdefault('users', {})[user] = sorted(set(fingers)) save_state(state) def _selected_finger(self, finger): """fprintd reports the concrete finger chosen for 'any'.""" if finger != 'any': return finger fingers = self.enrolled_fingers(self.claimed_user) return fingers[0] if fingers else 'right-index-finger' def _busy(self): return self.verifying or self.enrolling or self.deleting # ------------------------------------------------------- emission def _emit(self, name, variant): GLib.idle_add(self._emit_now, name, variant) def _emit_now(self, name, variant): if self.conn is not None: try: self.conn.emit_signal(None, DEVICE_PATH, IFACE_DEVICE, name, variant) except GLib.Error as e: log.warning('cannot emit %s: %s', name, e.message) return GLib.SOURCE_REMOVE def _notify_properties(self, changed): if self.conn is None: return try: self.conn.emit_signal( None, DEVICE_PATH, 'org.freedesktop.DBus.Properties', 'PropertiesChanged', GLib.Variant('(sa{sv}as)', (IFACE_DEVICE, changed, []))) except GLib.Error as e: log.warning('cannot emit PropertiesChanged: %s', e.message) def _set_finger_present(self, value): if self.finger_present == value: return self.finger_present = value self._notify_properties({'finger-present': GLib.Variant('b', value)}) def _set_finger_needed(self, value): if self.finger_needed == value: return self.finger_needed = value self._notify_properties({'finger-needed': GLib.Variant('b', value)}) # ------------------------------------------------------- claim ops def _release_claim(self, shutdown=False): self._stop_verify(quiet=True) self._stop_enroll(quiet=True) # A running delete is deliberately left to finish: it mutates the # device and aborting it can leave a partially written record (the # client may already be gone; the state is updated when it completes). if shutdown: self._stop_delete(quiet=True) self.claimed_by = None self.claimed_user = None self._notify_properties({'num-enroll-stages': GLib.Variant('i', -1)}) def _check_claim(self, sender, invocation): """fprintd's _fprint_device_check_claimed for STATE_CLAIMED calls.""" if self.claimed_by is None: invocation.return_dbus_error(E_CLAIM_DEVICE, 'Device was not claimed before use') return False if self.claimed_by != sender: invocation.return_dbus_error(E_ALREADY_IN_USE, 'Device already in use by another user') return False return True # ------------------------------------------------------ process ops def _kill_proc(self, proc): if proc is None or proc.poll() is not None: return try: os.killpg(os.getpgid(proc.pid), signal.SIGTERM) except (ProcessLookupError, PermissionError): return try: proc.wait(timeout=5) except subprocess.TimeoutExpired: try: os.killpg(os.getpgid(proc.pid), signal.SIGKILL) except (ProcessLookupError, PermissionError): pass def _harness_env(self, binary): env = os.environ.copy() usb_script = f'/tmp/opencode/usb-{binary}-{int(time.time())}.txt' try: os.makedirs('/tmp/opencode', exist_ok=True) # The fake winusb opens USB_SCRIPT for write ("wt") *as the Wine # user* and does not check for failure - a root-owned file makes # the harness hang in init without a single message, so create it # as RUN_USER (verified: winusb.c WinUsb_Initialize). fd = os.open(usb_script, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o666) os.close(fd) if os.geteuid() == 0: import pwd pw = pwd.getpwnam(RUN_USER) os.chown(usb_script, pw.pw_uid, pw.pw_gid) except (OSError, KeyError) as e: log.warning('cannot prepare %s: %s', usb_script, e) env.update({ 'HOME': os.path.join('/home', RUN_USER), 'WINEPREFIX': os.path.join(ROOT, 'work', 'wineprefix-48'), # keep wine quiet, but surface winusb/libfprint errors: a failed # libusb transfer makes the hacked winusb stub exit(0) silently 'WINEDEBUG': os.environ.get('FP_SHIM_WINEDEBUG', '-all,err+all'), 'USB_PLAYBACK': '', 'USB_SCRIPT': usb_script, }) return env def _harness_cmd(self, binary): cmd = [WINE64, binary] if os.geteuid() == 0: cmd = ['setpriv', f'--reuid={RUN_USER}', f'--regid={RUN_USER}', '--init-groups'] + cmd # one sensor access at a time (same lock as work/fp-verify.sh) return ['flock', '-w', '60', VERIFY_LOCK] + cmd def _run_harness(self, binary, timeout, cancel, on_line, proc_slot=None, expect_markers=None, first_timeout=120): """Run the Wine harness, feed its stdout lines to on_line(). Returns (status, returncode) with status in {'eof', 'cancelled', 'timeout', 'stalled'}; the process group is killed on cancel/timeout. 'stalled' means no line of expect_markers was seen within first_timeout (the winusb stub hangs silently when e.g. USB_SCRIPT is not writable by the Wine user). """ env = self._harness_env(binary) harness_log = open( f'/tmp/opencode/harness-{binary}-{int(time.time())}.log', 'w', encoding='utf-8', errors='replace') log.info('%s: harness log %s', binary, harness_log.name) r, w = os.pipe() proc = subprocess.Popen(self._harness_cmd(binary), cwd=SANDBOX, env=env, stdin=subprocess.DEVNULL, stdout=w, stderr=w, start_new_session=True) os.close(w) if proc_slot is not None: proc_slot(proc) started = time.monotonic() deadline = started + timeout status = 'eof' buf = '' saw_first = not expect_markers def feed(chunk): nonlocal buf, saw_first buf += chunk while '\n' in buf: line, buf = buf.split('\n', 1) line = line.rstrip('\r') harness_log.write(line + '\n') harness_log.flush() if not saw_first and any(m in line for m in expect_markers): saw_first = True if on_line is not None: on_line(line) while True: if cancel.is_set(): self._kill_proc(proc) status = 'cancelled' break if time.monotonic() > deadline: log.warning('%s: timeout after %ss', binary, timeout) self._kill_proc(proc) status = 'timeout' break if not saw_first and time.monotonic() - started > first_timeout: log.error('%s: no progress in %ss (winusb init hang?) - ' 'killing; see %s', binary, first_timeout, harness_log.name) self._kill_proc(proc) status = 'stalled' break ready, _, _ = select.select([r], [], [], 0.2) if ready: try: chunk = os.read(r, 65536) except OSError: chunk = b'' if not chunk: break feed(chunk.decode('utf-8', 'replace')) elif proc.poll() is not None: # child exited: drain whatever is left in the pipe while True: ready, _, _ = select.select([r], [], [], 0) if not ready: break try: chunk = os.read(r, 65536) except OSError: chunk = b'' if not chunk: break feed(chunk.decode('utf-8', 'replace')) break code = proc.wait() os.close(r) harness_log.close() if proc_slot is not None: proc_slot(None) return status, code # ------------------------------------------------------ verify ops def _stop_verify(self, quiet=False): with self.lock: running = self.verifying self.verifying = False self.verify_cancel.set() proc = self.verify_proc self.verify_proc = None self._kill_proc(proc) if running and not quiet: log.info('verify stopped by client') return running def _verify_cmd(self): script = ['/bin/bash', VERIFY_SCRIPT] if os.geteuid() == 0: return ['setpriv', f'--reuid={RUN_USER}', f'--regid={RUN_USER}', '--init-groups'] + script # session-bus smoke test: we are already the prefix owner return script def _verify_worker(self, finger): try: self._emit('VerifyFingerSelected', GLib.Variant('(s)', (finger,))) env = os.environ.copy() env['FP_VERIFY_TIMEOUT'] = str(VERIFY_TIMEOUT) env['FP_VERIFY_QUIET'] = '1' env['FP_VERIFY_LOCK_WAIT'] = '20' for attempt in (1, 2): # one internal retry for flaky Wine/USB if self.verify_cancel.is_set(): return started = time.monotonic() proc = subprocess.Popen( self._verify_cmd(), env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True) with self.lock: self.verify_proc = proc try: out, _ = proc.communicate(timeout=VERIFY_TIMEOUT + 20) except subprocess.TimeoutExpired: self._kill_proc(proc) out, _ = proc.communicate() rc = 124 else: rc = proc.returncode elapsed = time.monotonic() - started for line in (out or '').splitlines(): log.info('verify[%d]: %s', attempt, line) with self.lock: self.verify_proc = None if self.verify_cancel.is_set(): return if rc == 0: self._emit('VerifyStatus', GLib.Variant('(sb)', ('verify-match', True))) return if rc == 1: self._emit('VerifyStatus', GLib.Variant('(sb)', ('verify-no-match', True))) return # rc 2: timeout (no finger) or Wine/USB error. A quick exit # means the sandbox failed before the touch window; retry once. if attempt == 1 and elapsed < VERIFY_TIMEOUT - 5: log.warning('verify run failed early (%.1fs, rc=%d), retrying', elapsed, rc) continue log.info('no terminal status (rc=%d after %.1fs); ' 'pam_fprintd will time out', rc, elapsed) return finally: with self.lock: self.verify_proc = None # NOTE: keep self.verifying set after a terminal status: fprintd's # action stays ACTION_VERIFY until VerifyStop/Release (clients like # fprintd-verify call VerifyStop after the result and expect it to # succeed). def _start_verify(self, finger): with self.lock: if self._busy(): return False self.verifying = True self.verify_cancel.clear() self.verify_thread = threading.Thread( target=self._verify_worker, args=(finger,), daemon=True) self.verify_thread.start() return True # ------------------------------------------------------ enroll ops def _rotate_calibration(self): """Move saved calibration aside so the driver recalibrates. The sensor drops its enrollment record when its calibration/ownership state is reset (unexpected power loss, driver reset, firmware state change). The saved blob then no longer matches the device and the capture ioctl waits forever without ever reporting a finger, so enrollment appears to hang. With no blob present enroll.exe performs a fresh calibration and saves a new one. """ for name in ('CalibrationData.blob', 'PairingData.blob'): path = os.path.join(SANDBOX, name) if not os.path.exists(path): continue backup = f'{path}.stale-{int(time.time())}' try: os.replace(path, backup) except OSError as e: log.warning('enroll: cannot move %s aside: %s', path, e) else: log.info('enroll: moved %s aside (%s); forcing recalibration', name, os.path.basename(backup)) def _stop_enroll(self, quiet=False): with self.lock: running = self.enrolling commit_started = self._enroll_commit_started proc = self.enroll_proc if commit_started and proc is not None and proc.poll() is None: # The template write is in flight: let it finish instead of # risking a partially written record. The action stays "in # progress" until the worker completes. log.info('enroll: commit in progress, not aborting') return running with self.lock: self.enrolling = False self.enroll_cancel.set() self.enroll_proc = None self._kill_proc(proc) self._set_finger_needed(False) self._set_finger_present(False) if running and not quiet: log.info('enrollment stopped by client') return running def _enroll_worker(self, user, finger): """Drive `wine enroll.exe`; map the harness output to EnrollStatus. Markers (see hello.cc enroll()/commitEnrollment()): "about to Create Enrollment" "about to IOCTL_BIOMETRIC_CAPTURE_DATA" <- waiting for a touch "about to Update Enrollment" <- capture accepted "Got back 0x.. bytes: " <- response; hex[1:2] is the stage state (00 = done) "about to Check For Duplicate" / "about to Commit Enrollment" A capture marker that follows another capture marker (without an Update Enrollment in between) is a rejected scan (SensorStatus 2). """ st = {'capture_open': False, 'expect': None, 'stages': 0, 'complete': False, 'committed': False} def on_line(line): if line == 'about to IOCTL_BIOMETRIC_CAPTURE_DATA': if st['capture_open']: log.info('enroll: scan rejected, retry') self._emit('EnrollStatus', GLib.Variant('(sb)', ('enroll-retry-scan', False))) self._set_finger_present(False) st['capture_open'] = True st['expect'] = None self._set_finger_needed(True) elif line == 'about to Update Enrollment': st['capture_open'] = False st['expect'] = 'update' self._set_finger_needed(False) self._set_finger_present(True) elif line == 'about to Check For Duplicate': st['expect'] = 'duplicate' elif line == 'about to Commit Enrollment': st['expect'] = 'commit' self._enroll_commit_started = True elif line.startswith('Got back 0x') and st['expect']: kind, st['expect'] = st['expect'], None hexpart = line.split(':', 1)[1].strip() if ':' in line else '' first = hexpart[:2].lower() if kind == 'update': self._set_finger_present(False) if first == '00': st['complete'] = True else: st['stages'] += 1 log.info('enroll: stage %d passed', st['stages']) self._emit('EnrollStatus', GLib.Variant('(sb)', ('enroll-stage-passed', False))) self._set_finger_needed(True) elif kind == 'commit': st['committed'] = True log.info('enroll: committed') self._set_finger_present(False) self._set_finger_needed(False) def slot(proc): with self.lock: self.enroll_proc = proc try: # A commit that replaces an existing record makes the device # re-enumerate mid-write; the hacked winusb stub cannot detect # reconnects and exits with LIBUSB_ERROR_NO_DEVICE (verified # 2026-10-15 13:11-13:12, harness logs). The delete ioctl does # not reset the device, and a fresh write commits reliably, so # clear any existing record first. if self.enrolled_fingers(user): log.info('enroll: existing record for %s, deleting it first', user) del_st = {'payload': None} def on_delete_line(line): if del_st['payload'] is None and line.startswith('Got back 0x'): hexpart = line.split(':', 1)[1].strip() if ':' in line else '' del_st['payload'] = hexpart.lower() dstatus, dcode = self._run_harness( DELETE_EXE, DELETE_TIMEOUT, self.enroll_cancel, on_delete_line, slot, expect_markers=('about to 442034',)) payload = del_st['payload'] or '' d_deleted = payload.startswith('01') d_none = payload.startswith('00') d_ok = (dstatus == 'eof' and dcode == 0 and (d_deleted or d_none)) if d_deleted: d_text = 'deleted existing record' elif d_none: d_text = 'no record present' else: d_text = 'FAILED' log.info('enroll: pre-delete %s (harness %s rc=%s payload=%s)', d_text, dstatus, dcode, payload or '-') if d_none: # No template on the sensor means its calibration/ownership # state was reset: the saved blob is stale and capture would # hang forever. Force a fresh calibration during this enrol. self._rotate_calibration() if d_ok: # the device has no record now: report that honestly even if # the enrollment is aborted later on self._set_enrolled_fingers(user, []) if self.enroll_cancel.is_set(): log.info('enroll: cancelled before start') return status, code = self._run_harness( ENROLL_EXE, ENROLL_TIMEOUT, self.enroll_cancel, on_line, slot, expect_markers=('about to setMode', 'about to Create Enrollment', 'about to IOCTL_BIOMETRIC_CAPTURE_DATA')) # A committed template is on the device even if the client went # away meanwhile: always record it and report completion. if st['committed']: self._set_enrolled_fingers(user, [finger]) log.info('enroll: user %s -> %s (harness %s rc=%s)', user, finger, status, code) self._emit('EnrollStatus', GLib.Variant('(sb)', ('enroll-completed', True))) elif self.enroll_cancel.is_set(): log.info('enroll: cancelled') else: log.warning('enroll: not committed (harness %s rc=%s, ' '%d stages)', status, code, st['stages']) self._emit('EnrollStatus', GLib.Variant('(sb)', ('enroll-failed', True))) finally: with self.lock: self.enroll_proc = None if self.claimed_by is None or self.enroll_cancel.is_set(): # no client is waiting for a stop reply any more self.enrolling = False self._set_finger_needed(False) self._set_finger_present(False) # NOTE: like verify, keep self.enrolling set (pending EnrollStop) # when the client is still connected after a terminal status. def _start_enroll(self, user, finger): with self.lock: if self._busy(): return False self.enrolling = True self._enroll_commit_started = False self.enroll_cancel.clear() self.enroll_thread = threading.Thread( target=self._enroll_worker, args=(user, finger), daemon=True) self.enroll_thread.start() return True # ------------------------------------------------------ delete ops def _stop_delete(self, quiet=True): with self.lock: running = self.deleting self.deleting = False proc = self.delete_proc self.delete_proc = None self.delete_cancel.set() self._kill_proc(proc) if running and not quiet: log.info('delete cancelled') return running def _delete_worker(self, invocation, user, remove): """Remove fingers from the reported list; when the list becomes empty also delete the sensor-side template (delete.exe).""" ok, message = True, None try: fingers = self.enrolled_fingers(user) remaining = [f for f in fingers if f not in remove] if fingers and not remaining: # Optimistic state update: the client (gnome-control-center) # re-reads the list right after the call and gives up after # ~10 s - reflect the deletion immediately, restore below if # the harness fails. self._set_enrolled_fingers(user, remaining) def slot(proc): with self.lock: self.delete_proc = proc status, code = self._run_harness( DELETE_EXE, DELETE_TIMEOUT, self.delete_cancel, None, slot, expect_markers=('about to 442034',)) ok = (status == 'eof' and code == 0) log.info('delete: sensor record removal %s (harness %s rc=%s)', 'ok' if ok else 'FAILED', status, code) if not ok: message = 'Could not delete the print from the device' self._set_enrolled_fingers(user, fingers) # restore elif remaining: self._set_enrolled_fingers(user, remaining) # NOTE: the state update happens even if the client released the # claim meanwhile - the device record is gone and must not be # reported as enrolled. except Exception: log.exception('delete failed') ok, message = False, 'Internal error while deleting' finally: with self.lock: self.delete_proc = None self.deleting = False GLib.idle_add(self._finish_delete, invocation, ok, message) def _finish_delete(self, invocation, ok, message): try: if ok: invocation.return_value(None) else: invocation.return_dbus_error( E_PRINTS_NOT_DELETED, message or 'Fingerprint was not deleted') except GLib.Error as e: # client already gave up / connection closed log.info('delete reply not delivered: %s', e.message) return GLib.SOURCE_REMOVE # ------------------------------------------------ D-Bus callbacks def on_method_call(self, conn, sender, path, iface, method, params, invocation): try: self._dispatch(sender, path, iface, method, params, invocation) except Exception: # never kill the service on a bug log.exception('method %s.%s failed', iface, method) invocation.return_dbus_error(E_INTERNAL, 'shim internal error') def _dispatch(self, sender, path, iface, method, params, invocation): if iface == IFACE_MANAGER: return self._dispatch_manager(method, invocation) if iface == IFACE_DEVICE: return self._dispatch_device(sender, method, params, invocation) invocation.return_dbus_error(E_INTERNAL, f'unknown interface {iface}') def _dispatch_manager(self, method, invocation): if method == 'GetDevices': devices = [DEVICE_PATH] if sensor_present() else [] invocation.return_value(GLib.Variant('(ao)', (devices,))) elif method == 'GetDefaultDevice': if not sensor_present(): invocation.return_dbus_error(E_NO_SUCH_DEVICE, 'No fingerprint device present') else: invocation.return_value(GLib.Variant('(o)', (DEVICE_PATH,))) else: invocation.return_dbus_error(E_INTERNAL, f'unknown method {method}') def _dispatch_device(self, sender, method, params, invocation): if method == 'ListEnrolledFingers': (user,) = params.unpack() fingers = self.enrolled_fingers(user) if not fingers: invocation.return_dbus_error( E_NO_ENROLLED_PRINTS, 'No enrolled prints for user') else: invocation.return_value(GLib.Variant('(as)', (fingers,))) elif method == 'Claim': (user,) = params.unpack() if self.claimed_by is not None: invocation.return_dbus_error(E_ALREADY_IN_USE, 'Device already in use') return self.claimed_by = sender self.claimed_user = user or RUN_USER log.info('claim by %s for user %s', sender, self.claimed_user) self._notify_properties( {'num-enroll-stages': GLib.Variant('i', NUM_ENROLL_STAGES)}) invocation.return_value(None) elif method == 'Release': if not self._check_claim(sender, invocation): return self._release_claim() log.info('release by %s', sender) invocation.return_value(None) elif method == 'VerifyStart': (finger,) = params.unpack() if not self._check_claim(sender, invocation): return if finger not in FINGERS and finger != 'any': invocation.return_dbus_error(E_INVALID_FINGERNAME, f'Invalid finger name {finger}') return fingers = self.enrolled_fingers(self.claimed_user) if not fingers or (finger != 'any' and finger not in fingers): invocation.return_dbus_error( E_NO_ENROLLED_PRINTS, 'No enrolled prints for user') return if not self._start_verify(self._selected_finger(finger)): invocation.return_dbus_error(E_ALREADY_IN_USE, 'Another operation is in progress') return log.info('verify start (%s) by %s', finger, sender) invocation.return_value(None) elif method == 'VerifyStop': if not self._check_claim(sender, invocation): return if not self._stop_verify(): invocation.return_dbus_error(E_NO_ACTION, 'No verification in progress') return invocation.return_value(None) elif method == 'EnrollStart': (finger,) = params.unpack() if not self._check_claim(sender, invocation): return if finger not in FINGERS: invocation.return_dbus_error( E_INVALID_FINGERNAME, f'Invalid finger name {finger} (not "any")') return if not self._start_enroll(self.claimed_user, finger): invocation.return_dbus_error(E_ALREADY_IN_USE, 'Another operation is in progress') return log.info('enroll start (%s) by %s', finger, sender) invocation.return_value(None) elif method == 'EnrollStop': if not self._check_claim(sender, invocation): return if not self._stop_enroll(): invocation.return_dbus_error(E_NO_ACTION, 'No enrollment in progress') return invocation.return_value(None) elif method == 'DeleteEnrolledFinger': (finger,) = params.unpack() if not self._check_claim(sender, invocation): return if finger not in FINGERS: invocation.return_dbus_error(E_INVALID_FINGERNAME, f'Invalid finger name {finger}') return if self._busy(): invocation.return_dbus_error(E_ALREADY_IN_USE, 'Another operation is in progress') return fingers = self.enrolled_fingers(self.claimed_user) if finger not in fingers: invocation.return_dbus_error( E_NO_ENROLLED_PRINTS, f'Finger {finger} is not enrolled for this user') return self._start_delete(invocation, self.claimed_user, [finger]) elif method == 'DeleteEnrolledFingers2': if not self._check_claim(sender, invocation): return if self._busy(): invocation.return_dbus_error(E_ALREADY_IN_USE, 'Another operation is in progress') return fingers = self.enrolled_fingers(self.claimed_user) if not fingers: invocation.return_dbus_error( E_NO_ENROLLED_PRINTS, 'No enrolled prints for user') return self._start_delete(invocation, self.claimed_user, fingers) elif method == 'DeleteEnrolledFingers': (user,) = params.unpack() user = user or self.claimed_user or RUN_USER if user != RUN_USER: invocation.return_dbus_error( E_PERMISSION_DENIED, 'Only the local user is supported by the shim') return if self.claimed_by is not None and self.claimed_by != sender: invocation.return_dbus_error(E_ALREADY_IN_USE, 'Device already in use by another user') return if self._busy(): invocation.return_dbus_error(E_ALREADY_IN_USE, 'Another operation is in progress') return fingers = self.enrolled_fingers(user) if not fingers: invocation.return_dbus_error( E_NO_ENROLLED_PRINTS, 'No enrolled prints for user') return self._start_delete(invocation, user, fingers) else: invocation.return_dbus_error(E_INTERNAL, f'unknown method {method}') def _start_delete(self, invocation, user, remove): with self.lock: if self._busy(): invocation.return_dbus_error(E_ALREADY_IN_USE, 'Another operation is in progress') return self.deleting = True self.delete_cancel.clear() log.info('delete start: user=%s fingers=%s', user, ','.join(remove)) thread = threading.Thread(target=self._delete_worker, args=(invocation, user, remove), daemon=True) thread.start() def on_get_property(self, conn, sender, path, iface, prop): if iface != IFACE_DEVICE: return None if prop == 'name': return GLib.Variant('s', DEVICE_NAME) if prop == 'scan-type': return GLib.Variant('s', SCAN_TYPE) if prop == 'num-enroll-stages': stages = NUM_ENROLL_STAGES if self.claimed_by else -1 return GLib.Variant('i', stages) if prop == 'finger-present': return GLib.Variant('b', self.finger_present) if prop == 'finger-needed': return GLib.Variant('b', self.finger_needed) return None def on_name_owner_changed(self, conn, sender, path, iface, signal_name, params): name, _old, new = params.unpack() if new: return if name == self.claimed_by: log.info('claiming client %s vanished, releasing device', name) self._release_claim() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--session', action='store_true', help='own the name on the session bus (smoke test)') parser.add_argument('--debug', action='store_true') args = parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.debug else logging.INFO, format='fprintd-shim: %(levelname)s: %(message)s', stream=sys.stderr) bus_type = Gio.BusType.SESSION if args.session else Gio.BusType.SYSTEM device = ShimDevice() loop = GLib.MainLoop() manager_info = Gio.DBusNodeInfo.new_for_xml(MANAGER_XML).interfaces[0] device_info = Gio.DBusNodeInfo.new_for_xml(DEVICE_XML).interfaces[0] def on_bus_acquired(conn, _name): device.conn = conn conn.register_object(MANAGER_PATH, manager_info, device.on_method_call, device.on_get_property, None) conn.register_object(DEVICE_PATH, device_info, device.on_method_call, device.on_get_property, None) conn.signal_subscribe( 'org.freedesktop.DBus', 'org.freedesktop.DBus', 'NameOwnerChanged', '/org/freedesktop/DBus', None, Gio.DBusSignalFlags.NONE, device.on_name_owner_changed) log.info('serving %s (device %s, state %s, enroll/delete via %s)', BUS_NAME, DEVICE_PATH, STATE_FILE, SANDBOX) def on_name_lost(_conn, _name): log.warning('lost bus name %s', BUS_NAME) device._release_claim() loop.quit() def on_term(_signum, _frame): log.info('shutting down') device._release_claim() loop.quit() signal.signal(signal.SIGTERM, on_term) signal.signal(signal.SIGINT, on_term) Gio.bus_own_name(bus_type, BUS_NAME, Gio.BusNameOwnerFlags.NONE, on_bus_acquired, None, on_name_lost) loop.run() if __name__ == '__main__': main()