///| The authentication dialog's state, apart from how it is drawn: what PAM asked, what was /// typed (kept as characters so it can be wiped), which control has the keyboard, the last /// error. The compositor draws it (compositor/host/auth.mbt) and runs the helper. ///| Where the conversation is. pub(all) enum Phase { /// The helper was started and hasn't asked anything yet. Starting /// PAM asked for an answer (`prompt`); the field takes typing. Prompt /// The answer went to PAM; waiting for the verdict. Checking /// PAM only said something (say "Place your finger on the reader") and waits on its own. Waiting } derive(Eq, Debug) ///| Face unlock (docs/face-unlock.md): what the face module in the PAM stack said, for the /// dialog's face row. Chandra's own pam_chandra_face.so says "Face unlock: ..."; Howdy's /// pam_howdy.so says "Attempting facial authentication", "Identified face as ...", and its /// failures as errors. pub(all) enum FaceState { /// No face module spoke in this attempt. NoFace /// Looking for the face; typing the password meanwhile still works (it goes in when PAM asks). Scanning /// Recognized: PAM is finishing. Matched /// Not this time, and why ("Face not recognized"); the password is next. FaceFailed(String) } derive(Eq, Debug) ///| What a PAM message means for face unlock, if it is about it: Some(state), else None. pub fn face_message(m : String, is_error : Bool) -> FaceState? { let t = m.trim(chars=" \n").to_string() let low = t.to_lower() let ours = low.has_prefix("face unlock:") let body = if ours { t[12:].to_string().trim(chars=" ").to_string() } else { t } let lbody = body.to_lower() if ours { if is_error { let why = if lbody.has_prefix("face not recognized") || lbody == "" { "Face not recognized" } else { upper_first(body) } return Some(FaceFailed(why)) } if lbody.has_prefix("recognized") { return Some(Matched) } return Some(Scanning) } // Howdy (pam_howdy.so). if low.has_prefix("attempting facial authentication") || low.has_prefix("attempting face detection") { return Some(Scanning) } if low.has_prefix("identified face as") { return Some(Matched) } if is_error && (low.has_prefix("failure, timeout reached") || low.has_prefix("failure, not a single face")) { return Some(FaceFailed("Face not recognized")) } if is_error && low.has_prefix("face detection image too dark") { return Some(FaceFailed("The camera picture is too dark")) } None } ///| "camera not available" -> "Camera not available". fn upper_first(s : String) -> String { if s.length() == 0 { return s } s[:1].to_string().to_upper() + s[1:].to_string() } ///| The dialog's controls, in Tab order. pub(all) enum Focus { Field User Reveal Details Cancel Allow } derive(Eq, Debug) ///| What the compositor has to do after an event. pub(all) enum DialogEffect { Nothing /// Send these bytes to the helper as the answer (then zero them). Answer(FixedArray[Byte]) /// Run the helper again (another user picked, or the last attempt failed). Restart /// The user dismissed the dialog. Cancelled /// The helper said SUCCESS. Authorized } ///| Evdev key codes the dialog knows. pub let key_esc : UInt = 1 ///| pub let key_backspace : UInt = 14 ///| pub let key_tab : UInt = 15 ///| pub let key_enter : UInt = 28 ///| pub let key_kp_enter : UInt = 96 ///| pub let key_space : UInt = 57 ///| pub let key_left : UInt = 105 ///| pub let key_right : UInt = 106 ///| pub let key_up : UInt = 103 ///| pub let key_down : UInt = 108 ///| pub let key_u : UInt = 22 ///| pub let key_d : UInt = 32 ///| pub let key_r : UInt = 19 ///| The dialog for one request. pub(all) struct AuthDialog { req : AuthRequest desc : Description mut user_sel : Int mut phase : Phase /// PAM's prompt, tidied ("Password: " -> "Password"). mut prompt : String /// The prompt's answer is shown as typed (PAM_PROMPT_ECHO_ON). mut echo : Bool input : Array[Char] /// Show the password instead of dots. mut reveal : Bool mut caps : Bool /// The last error (PAM's message, or ours after a failed attempt); "" when none. mut error : String /// PAM's last information message. mut info : String mut details_open : Bool mut failures : Int /// When the last failure shook the card (monotonic ms), 0 for never. mut shake_at : UInt64 mut focus : Focus /// Enter came before PAM's prompt: answer as soon as it does. mut submit_queued : Bool /// Face unlock in this attempt (NoFace when no face module spoke). mut face : FaceState /// When face unlock started looking (monotonic ms; the scan animation's clock). mut face_at : UInt64 } ///| pub fn AuthDialog::new(req : AuthRequest, desc : Description) -> AuthDialog { { req, desc, user_sel: 0, phase: Starting, prompt: "Password", echo: false, input: [], reveal: false, caps: false, error: if req.users.length() == 0 { "No account can approve this here." } else { "" }, info: "", details_open: false, failures: 0, shake_at: 0UL, focus: Field, submit_queued: false, face: NoFace, face_at: 0UL, } } ///| The user answering, if any. pub fn AuthDialog::user(self : AuthDialog) -> AuthUser? { self.req.users.get(self.user_sel) } ///| "Password: " -> "Password"; "Password for nandi: " stays readable. pub fn tidy_prompt(p : String) -> String { let t = p.trim(chars=" \t\n").to_string() let t = if t.has_suffix(":") { t[:t.length() - 1].to_string().trim(chars=" ").to_string() } else { t } if t == "" { "Password" } else { t } } ///| Wipe what was typed. pub fn AuthDialog::wipe(self : AuthDialog) -> Unit { for i = 0; i < self.input.length(); i = i + 1 { self.input[i] = '\u{0}' } self.input.clear() } ///| What was typed, as UTF-8 bytes in a buffer the caller zeroes after use; the field is wiped. fn AuthDialog::take_answer(self : AuthDialog) -> FixedArray[Byte] { let n = self.input.fold(init=0, fn(acc, c) { let v = c.to_int() acc + (if v < 0x80 { 1 } else if v < 0x800 { 2 } else if v < 0x10000 { 3 } else { 4 }) }) let out : FixedArray[Byte] = FixedArray::make(n, b'\x00') let mut k = 0 for c in self.input { let v = c.to_int() if v < 0x80 { out[k] = v.to_byte() k = k + 1 } else if v < 0x800 { out[k] = (0xC0 | (v >> 6)).to_byte() out[k + 1] = (0x80 | (v & 0x3F)).to_byte() k = k + 2 } else if v < 0x10000 { out[k] = (0xE0 | (v >> 12)).to_byte() out[k + 1] = (0x80 | ((v >> 6) & 0x3F)).to_byte() out[k + 2] = (0x80 | (v & 0x3F)).to_byte() k = k + 3 } else { out[k] = (0xF0 | (v >> 18)).to_byte() out[k + 1] = (0x80 | ((v >> 12) & 0x3F)).to_byte() out[k + 2] = (0x80 | ((v >> 6) & 0x3F)).to_byte() out[k + 3] = (0x80 | (v & 0x3F)).to_byte() k = k + 4 } } self.wipe() out } ///| Zero a buffer an answer was in. pub fn zero(b : FixedArray[Byte]) -> Unit { for i = 0; i < b.length(); i = i + 1 { b[i] = b'\x00' } } ///| Send what was typed, if PAM is asking; else remember to once it does. fn AuthDialog::submit(self : AuthDialog) -> DialogEffect { match self.phase { Prompt => if self.input.length() == 0 && !self.echo { Nothing } else { self.phase = Checking self.error = "" Answer(self.take_answer()) } Starting | Waiting => { self.submit_queued = self.input.length() > 0 Nothing } Checking => Nothing } } ///| Something from the helper. `now` is the monotonic clock (for the shake). pub fn AuthDialog::helper(self : AuthDialog, ev : HelperEvent, now : UInt64) -> DialogEffect { match ev { TextInfo(m) | ErrorMsg(m) => match face_message(m, ev is ErrorMsg(_)) { Some(f) => { if f == Scanning && self.face != Scanning { self.face_at = if now == 0UL { 1UL } else { now } } self.face = f if self.phase == Starting { self.phase = Waiting } return Nothing } None => () } _ => () } match ev { PromptEchoOff(p) | PromptEchoOn(p) => { // The face module gave up without saying why (a timeout, or Howdy's silent failures). if self.face == Scanning { self.face = FaceFailed("Face not recognized") } self.phase = Prompt self.prompt = tidy_prompt(p) self.echo = ev is PromptEchoOn(_) self.info = "" if self.submit_queued { self.submit_queued = false return self.submit() } Nothing } ErrorMsg(m) => { self.error = m.trim(chars=" \n").to_string() Nothing } TextInfo(m) => { self.info = m.trim(chars=" \n").to_string() if self.phase == Starting { self.phase = Waiting } Nothing } Success => Authorized Failure => { self.failures = self.failures + 1 self.shake_at = if now == 0UL { 1UL } else { now } if self.error == "" { self.error = if self.echo { "That didn't work. Try again." } else { "Wrong password. Try again." } } self.wipe() self.submit_queued = false self.phase = Starting self.info = "" self.face = NoFace self.focus = Field Restart } } } ///| The controls Tab moves through, in order (the user picker only with several users). pub fn AuthDialog::focus_order(self : AuthDialog) -> Array[Focus] { let out : Array[Focus] = [Field] if self.req.users.length() > 1 { out.push(User) } out.push(Reveal) out.push(Details) out.push(Cancel) out.push(Allow) out } ///| Move the keyboard focus by `delta` along the Tab order. fn AuthDialog::move_focus(self : AuthDialog, delta : Int) -> Unit { let order = self.focus_order() let i = order.search(self.focus).unwrap_or(0) let n = order.length() self.focus = order[((i + delta) % n + n) % n] } ///| Pick the user `delta` away (wrapping). Restart when it changed. fn AuthDialog::cycle_user(self : AuthDialog, delta : Int) -> DialogEffect { let n = self.req.users.length() if n < 2 { return Nothing } self.user_sel = ((self.user_sel + delta) % n + n) % n self.wipe() self.error = "" self.info = "" self.face = NoFace self.phase = Starting self.submit_queued = false Restart } ///| Activate control `f` (Enter or Space on it, or a click). pub fn AuthDialog::activate(self : AuthDialog, f : Focus) -> DialogEffect { match f { Field => { self.focus = Field Nothing } User => { self.focus = User self.cycle_user(1) } Reveal => { self.focus = Reveal self.reveal = !self.reveal Nothing } Details => { self.focus = Details self.details_open = !self.details_open Nothing } Cancel => Cancelled Allow => self.submit() } } ///| A key press: `code` (evdev), the modifier state (Shift, Ctrl, Alt bits), and the character it /// types on the current layout, if any. pub fn AuthDialog::key(self : AuthDialog, code : UInt, mods : UInt, ch : Char?) -> DialogEffect { let ctrl = (mods & mask_ctrl) != 0U let shift = (mods & mask_shift) != 0U let alt = (mods & mask_alt) != 0U if code == key_esc { return Cancelled } if code == key_tab { self.move_focus(if shift { -1 } else { 1 }) return Nothing } if code == key_enter || code == key_kp_enter { return match self.focus { Field | Allow => self.submit() other => self.activate(other) } } // Alt+D details, Alt+R reveal: reachable from the field without leaving it. if alt && code == key_d { self.details_open = !self.details_open return Nothing } if alt && code == key_r { self.reveal = !self.reveal return Nothing } if self.focus == User && (code == key_left || code == key_up) { return self.cycle_user(-1) } if self.focus == User && (code == key_right || code == key_down) { return self.cycle_user(1) } if code == key_space && self.focus != Field { return self.activate(self.focus) } if self.phase == Checking { return Nothing } if code == key_backspace || (ctrl && code == key_u) { if ctrl { self.wipe() } else if self.input.length() > 0 { let last = self.input.length() - 1 self.input[last] = '\u{0}' ignore(self.input.pop()) } self.focus = Field return Nothing } if ctrl || alt { return Nothing } match ch { Some(c) => { if self.input.length() < 512 { self.input.push(c) } self.focus = Field // Typing again after an error clears it. if self.failures > 0 { self.error = "" } Nothing } None => Nothing } } ///| Horizontal offset of the card while it shakes after a failure (0 when still). pub fn AuthDialog::shake_offset(self : AuthDialog, now : UInt64) -> Int { if self.shake_at == 0UL || now < self.shake_at { return 0 } let t = (now - self.shake_at).to_int() let dur = 420 if t >= dur { return 0 } // Three swings, fading out. let period = dur / 6 let phase = t % period let tri = if phase < period / 2 { phase * 4 - period } else { 3 * period - phase * 4 } let amp = 12 * (dur - t) / dur tri * amp / period } ///| What the face row says, "" when there is none. pub fn AuthDialog::face_text(self : AuthDialog) -> String { match self.face { NoFace => "" Scanning => "Looking for your face…" Matched => "Face recognized" FaceFailed(why) => why + ". Use your password." } } ///| Whether the card is still shaking. pub fn AuthDialog::shaking(self : AuthDialog, now : UInt64) -> Bool { self.shake_at != 0UL && now >= self.shake_at && now - self.shake_at < 420UL } ///| The field's text as shown: the answer (echo or revealed) or one dot per character. pub fn AuthDialog::field_text(self : AuthDialog) -> String { if self.echo || self.reveal { String::from_array(self.input) } else { let sb = StringBuilder::new() for _ in self.input { sb.write_char('●') } sb.to_string() } } ///| The number of characters typed. pub fn AuthDialog::typed(self : AuthDialog) -> Int { self.input.length() }