Password dialog: Chandra is its own polkit agent, drawn in the shell layer
CI / test (push) Failing after 18s
CI / test (push) Failing after 18s
run0, pkexec and other polkit prompts used whatever third-party agent was
installed: a plain toolkit window saying "start transient unit
'run-p15802-i1990.service'". The compositor now registers as the session's
polkit authentication agent and asks in its own dialog:
- a centered card over a dimmed screen, above all windows and client menus,
themed (dark/light follow the Dark mode switch), keyboard-first: Enter,
Esc, Tab order, Alt+R show/hide, Alt+D details, Ctrl+U clear
- for run0 it shows the command it will run ("gparted /dev/sda", as root)
from run0's command line (pid from polkit's details or the unit name),
pkexec's command from its details, polkit's message otherwise; Details
lists the requester, target user, unit and action id
- account picker when several admins can answer (group members expanded)
- the PAM conversation through polkit-agent-helper-1: polkit 126's socket
first, else the setuid helper on a socket pair (new sys spawn-socket on the
native, Rust and MoonBit hosts); password, echo-on prompts, info (fingerprint)
and errors (faillock) shown as they come; wrong password shakes and retries;
spinner while PAM checks; Caps Lock warning
- typing through the clients' xkb keymap (groups, Shift, AltGr, Caps Lock),
US layout when there is none
- no client has keyboard focus or input while it is up; the password is
wiped after sending and never logged
Settings > Session > "Chandra password dialog" (state.edn :auth-agent
:system when off) switches back to the third-party agent, which
chandra-session now finds and the compositor starts (also when polkit
refuses our agent). Tests: polkit_test (keymaps, helper protocol, run0
parsing, dialog states, the socket-pair route) and auth_test (mock polkit
Authority on a private dbus-daemon, mock helper; CHANDRA_AUTH_SHOTS writes
a PNG per state). Docs: docs/auth-dialog.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgkRPrAzXECBUGmNEE
This commit is contained in:
32 files changed
+3930
-43
No files matched your search
@@ -0,0 +1,331 @@
|
||||
///| Chandra's polkit authentication agent: registers with polkitd on the system bus for this
|
||||
/// login session and queues the BeginAuthentication calls it gets, which the compositor answers
|
||||
/// with its own dialog.
|
||||
///
|
||||
/// polkitd calls org.freedesktop.PolicyKit1.AuthenticationAgent.BeginAuthentication on the
|
||||
/// agent registered for the session of whoever needs authorizing (run0, pkexec, udisks, ...).
|
||||
/// The call stays unanswered until the user is done: an empty reply once the helper said
|
||||
/// SUCCESS (the helper itself told polkitd who authenticated), or the error
|
||||
/// org.freedesktop.PolicyKit1.Error.Cancelled when they dismissed it. polkitd can withdraw a
|
||||
/// request with CancelAuthentication(cookie) (the asking process went away).
|
||||
|
||||
///|
|
||||
pub let agent_path : String = "/org/chandra/PolicyKit1/AuthenticationAgent"
|
||||
|
||||
///|
|
||||
pub let agent_iface : String = "org.freedesktop.PolicyKit1.AuthenticationAgent"
|
||||
|
||||
///|
|
||||
pub let authority_name : String = "org.freedesktop.PolicyKit1"
|
||||
|
||||
///|
|
||||
pub let authority_path : String = "/org/freedesktop/PolicyKit1/Authority"
|
||||
|
||||
///|
|
||||
pub let authority_iface : String = "org.freedesktop.PolicyKit1.Authority"
|
||||
|
||||
///|
|
||||
pub let err_cancelled : String = "org.freedesktop.PolicyKit1.Error.Cancelled"
|
||||
|
||||
///|
|
||||
pub let err_failed : String = "org.freedesktop.PolicyKit1.Error.Failed"
|
||||
|
||||
///|
|
||||
let agent_introspection : String =
|
||||
#|<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
|
||||
#| "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
|
||||
#|<node>
|
||||
#| <interface name="org.freedesktop.PolicyKit1.AuthenticationAgent">
|
||||
#| <method name="BeginAuthentication">
|
||||
#| <arg type="s" name="action_id" direction="in"/>
|
||||
#| <arg type="s" name="message" direction="in"/>
|
||||
#| <arg type="s" name="icon_name" direction="in"/>
|
||||
#| <arg type="a{ss}" name="details" direction="in"/>
|
||||
#| <arg type="s" name="cookie" direction="in"/>
|
||||
#| <arg type="a(sa{sv})" name="identities" direction="in"/>
|
||||
#| </method>
|
||||
#| <method name="CancelAuthentication"><arg type="s" name="cookie" direction="in"/></method>
|
||||
#| </interface>
|
||||
#| <interface name="org.freedesktop.DBus.Introspectable">
|
||||
#| <method name="Introspect"><arg type="s" direction="out"/></method>
|
||||
#| </interface>
|
||||
#| <interface name="org.freedesktop.DBus.Peer"><method name="Ping"/></interface>
|
||||
#|</node>
|
||||
|
||||
///| A request waiting for the user, with the call to answer.
|
||||
pub(all) struct Pending {
|
||||
req : AuthRequest
|
||||
call : @network.DMessage
|
||||
}
|
||||
|
||||
///| The agent.
|
||||
pub struct PolkitAgent {
|
||||
mut bus : @network.DBus?
|
||||
/// The system bus socket to use; "" finds it from the environment.
|
||||
bus_path : String
|
||||
mut registered : Bool
|
||||
/// RegisterAuthenticationAgent was sent and not answered yet.
|
||||
mut registering : Bool
|
||||
/// Why registering failed (or the bus went away), "" when it didn't.
|
||||
mut error : String
|
||||
/// The subject to register for; None: this login session.
|
||||
subject : @network.DValue?
|
||||
/// Requests in the order they came; the dialog shows the first.
|
||||
queue : Array[Pending]
|
||||
/// Turns BeginAuthentication's arguments into a request (tests swap the passwd lookup).
|
||||
make_request : (Array[@network.DValue]) -> AuthRequest?
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn PolkitAgent::new(
|
||||
bus_path? : String = "",
|
||||
subject? : @network.DValue,
|
||||
make_request? : (Array[@network.DValue]) -> AuthRequest? = AuthRequest::from_args,
|
||||
) -> PolkitAgent {
|
||||
{ bus: None, bus_path, registered: false, registering: false, error: "", subject, queue: [], make_request }
|
||||
}
|
||||
|
||||
///| The subject the agent registers for: this login session (XDG_SESSION_ID, else logind's
|
||||
/// session of our pid).
|
||||
fn session_subject(bus : @network.DBus) -> @network.DValue? {
|
||||
let mut id = @sys.getenv("XDG_SESSION_ID")
|
||||
if id == "" {
|
||||
let r = bus.call_sync(
|
||||
@network.DMessage::call(
|
||||
"org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetSessionByPID",
|
||||
[U32(@sys.getpid().reinterpret_as_uint())],
|
||||
),
|
||||
1000,
|
||||
)
|
||||
match r {
|
||||
Some({ mtype: 2, body: [Path(p)], .. }) => {
|
||||
let g = bus.call_sync(
|
||||
@network.DMessage::call(
|
||||
"org.freedesktop.login1", p, "org.freedesktop.DBus.Properties", "Get",
|
||||
[Str("org.freedesktop.login1.Session"), Str("Id")],
|
||||
),
|
||||
1000,
|
||||
)
|
||||
match g {
|
||||
Some({ mtype: 2, body: [Variant(Str(s))], .. }) => id = s
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
if id == "" {
|
||||
None
|
||||
} else {
|
||||
Some(Struct([Str("unix-session"), @network.dict("v", [("session-id", Variant(Str(id)))])]))
|
||||
}
|
||||
}
|
||||
|
||||
///| Connect to the system bus and ask polkitd to make us this session's agent. The answer
|
||||
/// comes later (`tick`): `registered`, or `failed` with `error` (no polkit, or another agent
|
||||
/// already has the session). False (with `error`) when there is no bus or session to ask for.
|
||||
pub fn PolkitAgent::start(self : PolkitAgent) -> Bool {
|
||||
if self.registered || self.registering {
|
||||
return true
|
||||
}
|
||||
let path = if self.bus_path != "" { self.bus_path } else { @network.system_bus_path() }
|
||||
let bus = match @network.DBus::open(path) {
|
||||
Some(b) => b
|
||||
None => {
|
||||
self.error = "no system bus at " + path
|
||||
return false
|
||||
}
|
||||
}
|
||||
let subject = match self.subject {
|
||||
Some(s) => s
|
||||
None =>
|
||||
match session_subject(bus) {
|
||||
Some(s) => s
|
||||
None => {
|
||||
self.error = "no login session (XDG_SESSION_ID unset and logind doesn't know us)"
|
||||
bus.close()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
bus.set_on_call(fn(m) { self.on_call(bus, m) })
|
||||
let lang = if @sys.getenv("LANG") != "" { @sys.getenv("LANG") } else { "en_US.UTF-8" }
|
||||
self.bus = Some(bus)
|
||||
self.registering = true
|
||||
self.error = ""
|
||||
let serial = bus.call(
|
||||
@network.DMessage::call(authority_name, authority_path, authority_iface, "RegisterAuthenticationAgent", [
|
||||
subject,
|
||||
Str(lang),
|
||||
Str(agent_path),
|
||||
]),
|
||||
on_reply=fn(m) {
|
||||
self.registering = false
|
||||
if m.mtype == @network.method_return {
|
||||
self.registered = true
|
||||
} else {
|
||||
self.error = m.error_text()
|
||||
bus.close()
|
||||
}
|
||||
},
|
||||
)
|
||||
if serial == 0 {
|
||||
self.registering = false
|
||||
self.error = "could not reach polkit"
|
||||
self.bus = None
|
||||
return false
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
///| Registering failed or the agent lost the bus (see `error`).
|
||||
pub fn PolkitAgent::failed(self : PolkitAgent) -> Bool {
|
||||
!self.registered && !self.registering
|
||||
}
|
||||
|
||||
///| Answer a call to the agent object.
|
||||
fn PolkitAgent::on_call(self : PolkitAgent, bus : @network.DBus, m : @network.DMessage) -> Unit {
|
||||
match (m.iface, m.meth) {
|
||||
("org.freedesktop.DBus.Peer", "Ping") => bus.reply(m, [])
|
||||
("org.freedesktop.DBus.Introspectable", "Introspect") =>
|
||||
bus.reply(m, [Str(if m.path == agent_path { agent_introspection } else { "<node/>" })])
|
||||
(i, "BeginAuthentication") if i == agent_iface || i == "" =>
|
||||
if m.path != agent_path {
|
||||
bus.reply_error(m, "org.freedesktop.DBus.Error.UnknownObject", "no object " + m.path)
|
||||
} else {
|
||||
match (self.make_request)(m.body) {
|
||||
Some(req) =>
|
||||
if req.users.length() == 0 {
|
||||
bus.reply_error(m, err_failed, "No user to authenticate as")
|
||||
} else {
|
||||
self.queue.push({ req, call: m })
|
||||
}
|
||||
None => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad arguments")
|
||||
}
|
||||
}
|
||||
(i, "CancelAuthentication") if i == agent_iface || i == "" =>
|
||||
match m.body {
|
||||
[Str(cookie)] => {
|
||||
self.finish(cookie, Err("Authentication was cancelled"))
|
||||
bus.reply(m, [])
|
||||
}
|
||||
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.InvalidArgs", "bad arguments")
|
||||
}
|
||||
_ => bus.reply_error(m, "org.freedesktop.DBus.Error.UnknownMethod", "unknown method " + m.iface + "." + m.meth)
|
||||
}
|
||||
}
|
||||
|
||||
///| Serve calls that arrived. False once the bus went away (polkitd forgets the agent then).
|
||||
pub fn PolkitAgent::tick(self : PolkitAgent) -> Bool {
|
||||
match self.bus {
|
||||
Some(b) => {
|
||||
b.pump()
|
||||
if !b.alive {
|
||||
self.bus = None
|
||||
self.registered = false
|
||||
self.registering = false
|
||||
self.queue.clear()
|
||||
if self.error == "" {
|
||||
self.error = "the system bus went away"
|
||||
}
|
||||
return false
|
||||
}
|
||||
true
|
||||
}
|
||||
None => false
|
||||
}
|
||||
}
|
||||
|
||||
///| The request to show, if any.
|
||||
pub fn PolkitAgent::current(self : PolkitAgent) -> AuthRequest? {
|
||||
self.queue.get(0).map(p => p.req)
|
||||
}
|
||||
|
||||
///| Whether request `cookie` is still waiting (polkitd may have cancelled it).
|
||||
pub fn PolkitAgent::waiting(self : PolkitAgent, cookie : String) -> Bool {
|
||||
self.queue.iter().any(p => p.req.cookie == cookie)
|
||||
}
|
||||
|
||||
///| Answer request `cookie`: Ok once authorized, Err(message) when it was dismissed.
|
||||
pub fn PolkitAgent::finish(self : PolkitAgent, cookie : String, result : Result[Unit, String]) -> Unit {
|
||||
match self.queue.search_by(p => p.req.cookie == cookie) {
|
||||
Some(i) => {
|
||||
let p = self.queue.remove(i)
|
||||
match self.bus {
|
||||
Some(b) =>
|
||||
match result {
|
||||
Ok(_) => b.reply(p.call, [])
|
||||
Err(text) => b.reply_error(p.call, err_cancelled, text)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
|
||||
///| The bus socket, for the main loop to wake on (-1 when not connected).
|
||||
pub fn PolkitAgent::fd(self : PolkitAgent) -> Int {
|
||||
match self.bus {
|
||||
Some(b) => b.fd()
|
||||
None => -1
|
||||
}
|
||||
}
|
||||
|
||||
///| Whether polkitd has us as the session's agent.
|
||||
pub fn PolkitAgent::registered(self : PolkitAgent) -> Bool {
|
||||
self.registered
|
||||
}
|
||||
|
||||
///| Why the last start failed ("" when it didn't).
|
||||
pub fn PolkitAgent::error(self : PolkitAgent) -> String {
|
||||
self.error
|
||||
}
|
||||
|
||||
///| Stop being the agent: dismiss what waits, unregister, leave the bus.
|
||||
pub fn PolkitAgent::stop(self : PolkitAgent) -> Unit {
|
||||
let cookies = self.queue.map(p => p.req.cookie)
|
||||
for c in cookies {
|
||||
self.finish(c, Err("The authentication agent stopped"))
|
||||
}
|
||||
match self.bus {
|
||||
Some(b) => {
|
||||
match (match self.subject { Some(s) => Some(s); None => session_subject(b) }) {
|
||||
Some(subject) =>
|
||||
ignore(
|
||||
b.call_sync(
|
||||
@network.DMessage::call(authority_name, authority_path, authority_iface, "UnregisterAuthenticationAgent", [
|
||||
subject,
|
||||
Str(agent_path),
|
||||
]),
|
||||
1000,
|
||||
),
|
||||
)
|
||||
None => ()
|
||||
}
|
||||
b.close()
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
self.bus = None
|
||||
self.registered = false
|
||||
self.registering = false
|
||||
}
|
||||
|
||||
///| Ways to reach the helper, to try in order: polkit 126's socket (when
|
||||
/// polkit-agent-helper.socket is enabled; connecting fails otherwise), then the setuid program.
|
||||
/// CHANDRA_POLKIT_HELPER names one instead (`socket:/path` or a program path).
|
||||
pub fn helper_routes() -> Array[HelperRoute] {
|
||||
let h = @sys.getenv("CHANDRA_POLKIT_HELPER")
|
||||
if h != "" {
|
||||
return [if h.has_prefix("socket:") { Socket(h[7:].to_string()) } else { Program(h) }]
|
||||
}
|
||||
let out : Array[HelperRoute] = [Socket(helper_socket)]
|
||||
for p in helper_paths {
|
||||
if @sys.has_exe(p) {
|
||||
out.push(Program(p))
|
||||
break
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
///| Turning a request into words: what is asked, for which command, by whom.
|
||||
///
|
||||
/// polkit's own message for run0 is "Authentication is required to start transient unit
|
||||
/// 'run-p15802-i1990.service'.": true, but it says nothing a person can judge. run0 asks
|
||||
/// systemd for a transient unit, systemd asks polkit, and polkit tells us run0's pid (the
|
||||
/// subject, `polkit.subject-pid`; the unit name `run-p<pid>-i<n>.service` carries it too). From
|
||||
/// run0's command line we can show what it will run. pkexec puts the command in the details.
|
||||
|
||||
///| A process's command line (NUL-separated /proc/<pid>/cmdline), empty when it is gone.
|
||||
pub fn proc_cmdline(pid : Int) -> Array[String] {
|
||||
if pid <= 0 {
|
||||
return []
|
||||
}
|
||||
split_cmdline(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/cmdline"))
|
||||
}
|
||||
|
||||
///| Split NUL-separated arguments.
|
||||
pub fn split_cmdline(b : Bytes) -> Array[String] {
|
||||
let out : Array[String] = []
|
||||
let cur : Array[Byte] = []
|
||||
for i = 0; i < b.length(); i = i + 1 {
|
||||
if b[i] == b'\x00' {
|
||||
out.push(@utf8.decode_lossy(Bytes::from_array(cur)))
|
||||
cur.clear()
|
||||
} else {
|
||||
cur.push(b[i])
|
||||
}
|
||||
}
|
||||
if cur.length() > 0 {
|
||||
out.push(@utf8.decode_lossy(Bytes::from_array(cur)))
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| A process's name (/proc/<pid>/comm) and parent pid (/proc/<pid>/stat field 4).
|
||||
pub fn proc_name_parent(pid : Int) -> (String, Int) {
|
||||
if pid <= 0 {
|
||||
return ("", 0)
|
||||
}
|
||||
let comm = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/comm")).trim(chars="\n ").to_string()
|
||||
let stat = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/stat"))
|
||||
// "pid (comm) S ppid ...": the name can hold spaces and parentheses, so read after the last ')'.
|
||||
let ppid = match stat.rev_find(")") {
|
||||
Some(i) => {
|
||||
let rest = stat[i + 1:].to_string().trim(chars=" ").to_string().split(" ").to_array()
|
||||
if rest.length() >= 2 {
|
||||
parse_uint(rest[1].to_string()).unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
None => 0
|
||||
}
|
||||
(comm, ppid)
|
||||
}
|
||||
|
||||
///| The last part of a path.
|
||||
pub fn basename(p : String) -> String {
|
||||
match p.rev_find("/") {
|
||||
Some(i) => p[i + 1:].to_string()
|
||||
None => p
|
||||
}
|
||||
}
|
||||
|
||||
///| `run0`'s options that take a separate value (`-u root`, `--setenv FOO=1`).
|
||||
let run0_value_opts : Array[String] = [
|
||||
"-u", "--user", "-g", "--group", "-D", "--chdir", "--setenv", "-p", "--property", "--description",
|
||||
"--slice", "--unit", "--nice", "--machine", "--background", "--shell-prompt-prefix", "--area",
|
||||
]
|
||||
|
||||
///| What a `run0` (or `systemd-run`) command line runs: (target user, the command's arguments).
|
||||
/// The user is "root" unless -u/--user says otherwise; no arguments means a login shell.
|
||||
pub fn parse_run0(argv : Array[String]) -> (String, Array[String]) {
|
||||
let mut user = "root"
|
||||
let mut i = 1
|
||||
while i < argv.length() {
|
||||
let a = argv[i]
|
||||
if a == "--" {
|
||||
i = i + 1
|
||||
break
|
||||
}
|
||||
if !a.has_prefix("-") || a == "-" {
|
||||
break
|
||||
}
|
||||
if a.has_prefix("--user=") {
|
||||
user = a[7:].to_string()
|
||||
} else if a.has_prefix("-u") && a.length() > 2 {
|
||||
user = a[2:].to_string()
|
||||
} else if run0_value_opts.contains(a) {
|
||||
if (a == "-u" || a == "--user") && i + 1 < argv.length() {
|
||||
user = argv[i + 1]
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
let cmd : Array[String] = []
|
||||
while i < argv.length() {
|
||||
cmd.push(argv[i])
|
||||
i = i + 1
|
||||
}
|
||||
(user, cmd)
|
||||
}
|
||||
|
||||
///| An argument as a shell would need it written: bare when safe, else in single quotes.
|
||||
pub fn shell_quote(a : String) -> String {
|
||||
if a == "" {
|
||||
return "''"
|
||||
}
|
||||
let mut safe = true
|
||||
for c in a {
|
||||
if !(c.is_ascii_alphabetic() || c.is_ascii_digit() || "-_./=:,+@%".contains_char(c)) {
|
||||
safe = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if safe {
|
||||
a
|
||||
} else {
|
||||
"'" + a.replace_all(old="'", new="'\\''") + "'"
|
||||
}
|
||||
}
|
||||
|
||||
///| A command line for display.
|
||||
pub fn command_text(argv : Array[String]) -> String {
|
||||
argv.map(shell_quote).join(" ")
|
||||
}
|
||||
|
||||
///| The pid in a run0 unit name `run-p<pid>-i<n>.service` (or `run-u<n>.service`: none).
|
||||
pub fn run0_unit_pid(unit : String) -> Int? {
|
||||
if !unit.has_prefix("run-p") {
|
||||
return None
|
||||
}
|
||||
let rest = unit[5:].to_string()
|
||||
match rest.find("-") {
|
||||
Some(i) => parse_uint(rest[:i].to_string())
|
||||
None => None
|
||||
}
|
||||
}
|
||||
|
||||
///| The quoted name in a message like "... transient unit 'run-p15802-i1990.service'.".
|
||||
pub fn quoted_in(message : String) -> String {
|
||||
match message.find("'") {
|
||||
Some(a) => {
|
||||
let rest = message[a + 1:].to_string()
|
||||
match rest.find("'") {
|
||||
Some(b) => rest[:b].to_string()
|
||||
None => ""
|
||||
}
|
||||
}
|
||||
None => ""
|
||||
}
|
||||
}
|
||||
|
||||
///| How the dialog presents a request.
|
||||
pub(all) struct Description {
|
||||
/// The headline ("Run a command as root", or polkit's message for other actions).
|
||||
title : String
|
||||
/// One line under it: what allowing does.
|
||||
subtitle : String
|
||||
/// The command that will run, written as a shell would ("" when it isn't a command).
|
||||
command : String
|
||||
/// The command's program name (for its app icon), "" when none.
|
||||
program : String
|
||||
/// Label/value rows for the Details section.
|
||||
details : Array[(String, String)]
|
||||
}
|
||||
|
||||
///| Who asked: the subject process, then its parent ("run0 (pid 15802) from bash").
|
||||
fn requester(pid : Int) -> String {
|
||||
if pid <= 0 {
|
||||
return ""
|
||||
}
|
||||
let (name, ppid) = proc_name_parent(pid)
|
||||
if name == "" {
|
||||
return "pid " + pid.to_string()
|
||||
}
|
||||
let (pname, _) = proc_name_parent(ppid)
|
||||
name + " (pid " + pid.to_string() + ")" + (if pname != "" && ppid > 1 { ", started from " + pname } else { "" })
|
||||
}
|
||||
|
||||
///| Words for `req`. `cmdline` reads a process's arguments (tests pass their own).
|
||||
pub fn describe(req : AuthRequest, cmdline? : (Int) -> Array[String] = proc_cmdline, who? : (Int) -> String = requester) -> Description {
|
||||
let subject = parse_uint(req.detail("polkit.subject-pid")).unwrap_or(0)
|
||||
let caller = parse_uint(req.detail("polkit.caller-pid")).unwrap_or(0)
|
||||
let unit = if req.detail("unit") != "" { req.detail("unit") } else { quoted_in(req.message) }
|
||||
let details : Array[(String, String)] = []
|
||||
let add = fn(k : String, v : String) { if v != "" { details.push((k, v)) } }
|
||||
// run0 / systemd-run: a transient unit for a process we can read.
|
||||
let run0_pid = if req.action_id == "org.freedesktop.systemd1.manage-units" {
|
||||
match run0_unit_pid(unit) {
|
||||
Some(p) => p
|
||||
None => if unit.has_prefix("run-") { subject } else { 0 }
|
||||
}
|
||||
} else {
|
||||
0
|
||||
}
|
||||
let run0_argv = if run0_pid > 0 {
|
||||
let a = cmdline(if subject > 0 { subject } else { run0_pid })
|
||||
if a.length() > 0 { a } else { cmdline(run0_pid) }
|
||||
} else {
|
||||
[]
|
||||
}
|
||||
let tool = if run0_argv.length() > 0 { basename(run0_argv[0]) } else { "" }
|
||||
if tool == "run0" || tool == "systemd-run" {
|
||||
let (user, cmd) = parse_run0(run0_argv)
|
||||
let target = if user == "root" { "root" } else { user }
|
||||
let shell = cmd.length() == 0
|
||||
add("Requested by", who(if subject > 0 { subject } else { run0_pid }))
|
||||
add("Runs as", target)
|
||||
add("Unit", unit)
|
||||
add("Action", req.action_id)
|
||||
return {
|
||||
title: if shell { "Open a shell as " + target } else { "Run a command as " + target },
|
||||
subtitle: tool + " needs your password to " + (if shell { "start a " + target + " shell." } else { "run this as " + target + ":" }),
|
||||
command: command_text(cmd),
|
||||
program: if shell { "" } else { basename(cmd[0]) },
|
||||
details,
|
||||
}
|
||||
}
|
||||
// pkexec: the details carry the command.
|
||||
if req.action_id == "org.freedesktop.policykit.exec" || req.detail("command_line") != "" {
|
||||
let user = if req.detail("user") != "" { req.detail("user") } else { "root" }
|
||||
let line = req.detail("command_line")
|
||||
let program = basename(if req.detail("program") != "" { req.detail("program") } else { line.split(" ").to_array().get(0).map(v => v.to_string()).unwrap_or("") })
|
||||
add("Requested by", who(if subject > 0 { subject } else { caller }))
|
||||
add("Runs as", user)
|
||||
add("Action", req.action_id)
|
||||
return {
|
||||
title: "Run a program as " + user,
|
||||
subtitle: "pkexec needs your password to run this as " + user + ":",
|
||||
command: line,
|
||||
program,
|
||||
details,
|
||||
}
|
||||
}
|
||||
// Anything else: polkit's message is the best we have.
|
||||
add("Requested by", who(if subject > 0 { subject } else { caller }))
|
||||
add("Unit", req.detail("unit"))
|
||||
add("Action", req.action_id)
|
||||
{
|
||||
title: if req.message != "" { req.message } else { "Authentication required" },
|
||||
subtitle: "An app wants permission for a system action. Enter your password to allow it.",
|
||||
command: "",
|
||||
program: "",
|
||||
details,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
///| 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)
|
||||
|
||||
///| 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
|
||||
}
|
||||
|
||||
///|
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
///| 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 {
|
||||
PromptEchoOff(p) | PromptEchoOn(p) => {
|
||||
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.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.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
|
||||
}
|
||||
|
||||
///| 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()
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
///| The PAM conversation, through polkit's helper.
|
||||
///
|
||||
/// polkit authenticates with `polkit-agent-helper-1` (part of polkit, run as root). An agent
|
||||
/// talks to it one line at a time: the helper writes what PAM asks or says,
|
||||
/// PAM_PROMPT_ECHO_OFF <prompt> (a password: answer with one line)
|
||||
/// PAM_PROMPT_ECHO_ON <prompt> (a visible answer, say a user name or a one-time code)
|
||||
/// PAM_ERROR_MSG <text> / PAM_TEXT_INFO <text> (messages, no answer)
|
||||
/// SUCCESS / FAILURE (the end; on success the helper has told polkitd itself)
|
||||
/// with the text escaped as g_strescape does. There are two ways to start it:
|
||||
/// - polkit 126+ (systemd): connect to /run/polkit/agent-helper.socket and send the user name and
|
||||
/// the cookie, one line each (socket activation; no setuid binary).
|
||||
/// - otherwise run the setuid helper with the user name as its argument and send the cookie.
|
||||
|
||||
///| What the helper said.
|
||||
pub(all) enum HelperEvent {
|
||||
PromptEchoOff(String)
|
||||
PromptEchoOn(String)
|
||||
ErrorMsg(String)
|
||||
TextInfo(String)
|
||||
Success
|
||||
Failure
|
||||
} derive(Eq, Debug)
|
||||
|
||||
///| Undo g_strescape: \n \t \r \b \f \v \\ \" and octal \NNN (bytes, re-read as UTF-8).
|
||||
pub fn unescape(s : String) -> String {
|
||||
let out : Array[Byte] = []
|
||||
let cs = chars_of(s)
|
||||
let push_char = fn(c : Char) {
|
||||
let b = @utf8.encode(c.to_string())
|
||||
for i = 0; i < b.length(); i = i + 1 {
|
||||
out.push(b[i])
|
||||
}
|
||||
}
|
||||
let mut i = 0
|
||||
while i < cs.length() {
|
||||
let c = cs[i]
|
||||
if c != '\\' || i + 1 >= cs.length() {
|
||||
push_char(c)
|
||||
i = i + 1
|
||||
continue
|
||||
}
|
||||
let d = cs[i + 1]
|
||||
if d >= '0' && d <= '7' {
|
||||
let mut v = 0
|
||||
let mut k = 0
|
||||
while k < 3 && i + 1 + k < cs.length() && cs[i + 1 + k] >= '0' && cs[i + 1 + k] <= '7' {
|
||||
v = v * 8 + (cs[i + 1 + k].to_int() - '0'.to_int())
|
||||
k = k + 1
|
||||
}
|
||||
out.push((v & 0xff).to_byte())
|
||||
i = i + 1 + k
|
||||
continue
|
||||
}
|
||||
let r = match d {
|
||||
'n' => '\n'
|
||||
't' => '\t'
|
||||
'r' => '\r'
|
||||
'b' => '\b'
|
||||
'f' => '\u{0c}'
|
||||
'v' => '\u{0b}'
|
||||
_ => d
|
||||
}
|
||||
push_char(r)
|
||||
i = i + 2
|
||||
}
|
||||
@utf8.decode_lossy(Bytes::from_array(out))
|
||||
}
|
||||
|
||||
///| Parse one line from the helper (without its newline). None for lines we don't know.
|
||||
pub fn parse_helper_line(line : String) -> HelperEvent? {
|
||||
let after = fn(p : String) { unescape(line[p.length():].to_string()) }
|
||||
if line.has_prefix("PAM_PROMPT_ECHO_OFF ") {
|
||||
Some(PromptEchoOff(after("PAM_PROMPT_ECHO_OFF ")))
|
||||
} else if line.has_prefix("PAM_PROMPT_ECHO_ON ") {
|
||||
Some(PromptEchoOn(after("PAM_PROMPT_ECHO_ON ")))
|
||||
} else if line.has_prefix("PAM_ERROR_MSG ") {
|
||||
Some(ErrorMsg(after("PAM_ERROR_MSG ")))
|
||||
} else if line.has_prefix("PAM_TEXT_INFO ") {
|
||||
Some(TextInfo(after("PAM_TEXT_INFO ")))
|
||||
} else if line.has_prefix("SUCCESS") {
|
||||
Some(Success)
|
||||
} else if line.has_prefix("FAILURE") {
|
||||
Some(Failure)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
///| Where polkit installs the setuid helper, by distribution.
|
||||
pub let helper_paths : Array[String] = [
|
||||
"/usr/lib/polkit-1/polkit-agent-helper-1", "/usr/libexec/polkit-agent-helper-1", "/usr/libexec/polkit-1/polkit-agent-helper-1",
|
||||
"/usr/lib/policykit-1/polkit-agent-helper-1",
|
||||
]
|
||||
|
||||
///| The socket-activated helper (polkit 126+).
|
||||
pub let helper_socket : String = "/run/polkit/agent-helper.socket"
|
||||
|
||||
///| How to reach the helper: a socket to connect to, or a program to run on a socket pair.
|
||||
pub(all) enum HelperRoute {
|
||||
Socket(String)
|
||||
Program(String)
|
||||
} derive(Eq, Debug)
|
||||
|
||||
///| One run of the helper: the connection and the bytes read but not yet a whole line.
|
||||
pub struct HelperSession {
|
||||
mut fd : Int
|
||||
inbuf : Array[Byte]
|
||||
/// Set once SUCCESS or FAILURE came, or the helper went away.
|
||||
mut ended : Bool
|
||||
}
|
||||
|
||||
///| Start the helper to authenticate `user` for `cookie` by the first route that works. None
|
||||
/// when none does.
|
||||
pub fn HelperSession::start_any(routes : Array[HelperRoute], user : String, cookie : String) -> HelperSession? {
|
||||
for r in routes {
|
||||
match HelperSession::start(r, user, cookie) {
|
||||
Some(s) => return Some(s)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///| Start the helper to authenticate `user` for `cookie`. None when it can't be started.
|
||||
pub fn HelperSession::start(route : HelperRoute, user : String, cookie : String) -> HelperSession? {
|
||||
let (fd, first) = match route {
|
||||
Socket(path) => (@sys.unix_connect(path), user + "\n" + cookie + "\n")
|
||||
Program(path) => (@sys.spawn_socket([path, user]), cookie + "\n")
|
||||
}
|
||||
if fd < 0 {
|
||||
return None
|
||||
}
|
||||
let b = @utf8.encode(first)
|
||||
if @sys.sendmsg_fd(fd, b, -1) != b.length() {
|
||||
@sys.close_fd(fd)
|
||||
return None
|
||||
}
|
||||
Some({ fd, inbuf: [], ended: false })
|
||||
}
|
||||
|
||||
///| A session over an already-connected fd (tests).
|
||||
pub fn HelperSession::over(fd : Int) -> HelperSession {
|
||||
{ fd, inbuf: [], ended: false }
|
||||
}
|
||||
|
||||
///| What arrived since the last call (non-blocking). The helper going away without an answer
|
||||
/// reads as Failure.
|
||||
pub fn HelperSession::read(self : HelperSession) -> Array[HelperEvent] {
|
||||
let out : Array[HelperEvent] = []
|
||||
if self.fd < 0 {
|
||||
return out
|
||||
}
|
||||
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
|
||||
let mut eof = false
|
||||
while @sys.poll_read(self.fd, 0) > 0 {
|
||||
let (n, extra) = @sys.recvmsg_fd(self.fd, buf, buf.length())
|
||||
if extra >= 0 {
|
||||
@sys.close_fd(extra)
|
||||
}
|
||||
if n == -1 {
|
||||
break
|
||||
}
|
||||
if n <= 0 {
|
||||
eof = true
|
||||
break
|
||||
}
|
||||
for i = 0; i < n; i = i + 1 {
|
||||
self.inbuf.push(buf[i])
|
||||
}
|
||||
}
|
||||
while true {
|
||||
let mut nl = -1
|
||||
for i, b in self.inbuf {
|
||||
if b == b'\n' {
|
||||
nl = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if nl < 0 {
|
||||
break
|
||||
}
|
||||
let line = @utf8.decode_lossy(Bytes::from_array(self.inbuf[:nl].to_array()))
|
||||
let rest = self.inbuf[nl + 1:].to_array()
|
||||
self.inbuf.clear()
|
||||
self.inbuf.append(rest)
|
||||
match parse_helper_line(line) {
|
||||
Some(ev) => {
|
||||
out.push(ev)
|
||||
if ev == Success || ev == Failure {
|
||||
self.ended = true
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
if eof {
|
||||
if !self.ended {
|
||||
out.push(Failure)
|
||||
self.ended = true
|
||||
}
|
||||
self.close()
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| Answer the prompt with `answer` (its bytes then a newline); the caller zeroes its copy.
|
||||
pub fn HelperSession::respond(self : HelperSession, answer : FixedArray[Byte]) -> Bool {
|
||||
if self.fd < 0 {
|
||||
return false
|
||||
}
|
||||
let n = answer.length()
|
||||
let b = Bytes::makei(n + 1, i => if i < n { answer[i] } else { b'\n' })
|
||||
@sys.sendmsg_fd(self.fd, b, -1) == b.length()
|
||||
}
|
||||
|
||||
///| The connection, for the main loop to wait on (-1 once closed).
|
||||
pub fn HelperSession::fd(self : HelperSession) -> Int {
|
||||
self.fd
|
||||
}
|
||||
|
||||
///| Stop: closing the connection ends the helper's PAM conversation.
|
||||
pub fn HelperSession::close(self : HelperSession) -> Unit {
|
||||
if self.fd >= 0 {
|
||||
@sys.close_fd(self.fd)
|
||||
self.fd = -1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,634 @@
|
||||
///| Characters for the password field, from the keymap clients are sent.
|
||||
///
|
||||
/// The compositor sees keys as evdev codes; the characters they type depend on the keyboard
|
||||
/// layout, and a password typed on the wrong layout is the wrong password. So the auth dialog reads
|
||||
/// the xkb keymap (text format v1, what the host hands `WaylandServer::set_keymap`): the keycode
|
||||
/// names (`<AE01> = 10;`) and each key's symbols per group and level (`key <AE01> { [ 1, exclam ] };`),
|
||||
/// and maps keysym names to characters (ASCII and Latin-1 names, `Uxxxx`, `0x100xxxxx`). Without a
|
||||
/// keymap (nested windows, tests) a built-in US layout is used.
|
||||
|
||||
///| One key's keysym names: groups, then levels.
|
||||
struct KeySyms {
|
||||
groups : Array[Array[String]]
|
||||
}
|
||||
|
||||
///| Characters per keycode (evdev code + 8), parsed from an xkb keymap.
|
||||
pub struct Keymap {
|
||||
keys : Map[Int, KeySyms]
|
||||
}
|
||||
|
||||
///|
|
||||
fn chars_of(s : String) -> Array[Char] {
|
||||
let out : Array[Char] = []
|
||||
for c in s {
|
||||
out.push(c)
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
fn str_of(cs : Array[Char], from : Int, to : Int) -> String {
|
||||
let sb = StringBuilder::new()
|
||||
for i = from; i < to && i < cs.length(); i = i + 1 {
|
||||
sb.write_char(cs[i])
|
||||
}
|
||||
sb.to_string()
|
||||
}
|
||||
|
||||
///|
|
||||
fn is_space(c : Char) -> Bool {
|
||||
c == ' ' || c == '\t' || c == '\n' || c == '\r'
|
||||
}
|
||||
|
||||
///| The text of section `name` (say "xkb_symbols"): from its opening brace to the matching close.
|
||||
fn section(cs : Array[Char], name : String) -> (Int, Int)? {
|
||||
let n = chars_of(name)
|
||||
let mut i = 0
|
||||
while i + n.length() <= cs.length() {
|
||||
let mut hit = true
|
||||
for k = 0; k < n.length(); k = k + 1 {
|
||||
if cs[i + k] != n[k] {
|
||||
hit = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if hit {
|
||||
let mut j = i + n.length()
|
||||
while j < cs.length() && cs[j] != '{' {
|
||||
j = j + 1
|
||||
}
|
||||
let start = j + 1
|
||||
let mut depth = 1
|
||||
j = start
|
||||
while j < cs.length() && depth > 0 {
|
||||
if cs[j] == '{' {
|
||||
depth = depth + 1
|
||||
} else if cs[j] == '}' {
|
||||
depth = depth - 1
|
||||
}
|
||||
j = j + 1
|
||||
}
|
||||
return Some((start, j - 1))
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///| Statements of a section body split on top-level ';' (braces nest).
|
||||
fn statements(cs : Array[Char], from : Int, to : Int) -> Array[String] {
|
||||
let out : Array[String] = []
|
||||
let mut depth = 0
|
||||
let mut start = from
|
||||
let mut in_str = false
|
||||
for i = from; i < to; i = i + 1 {
|
||||
let c = cs[i]
|
||||
if c == '"' {
|
||||
in_str = !in_str
|
||||
} else if !in_str {
|
||||
if c == '{' {
|
||||
depth = depth + 1
|
||||
} else if c == '}' {
|
||||
depth = depth - 1
|
||||
} else if c == ';' && depth == 0 {
|
||||
out.push(str_of(cs, start, i).trim(chars=" \t\r\n").to_string())
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| `<NAME> = 10` -> ("NAME", 10); `alias <A> = <B>` handled by the caller.
|
||||
fn parse_keycode(st : String) -> (String, Int)? {
|
||||
if !st.has_prefix("<") {
|
||||
return None
|
||||
}
|
||||
let cs = chars_of(st)
|
||||
let mut close = -1
|
||||
for i, c in cs {
|
||||
if c == '>' {
|
||||
close = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if close < 0 {
|
||||
return None
|
||||
}
|
||||
let name = str_of(cs, 1, close)
|
||||
let rest = str_of(cs, close + 1, cs.length()).trim(chars=" \t=").to_string()
|
||||
let mut v = 0
|
||||
let mut any = false
|
||||
for c in rest {
|
||||
if c >= '0' && c <= '9' {
|
||||
v = v * 10 + (c.to_int() - '0'.to_int())
|
||||
any = true
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if any {
|
||||
Some((name, v))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
///| The keysym lists in a key body: `[ a, A ]` (group 1) or `symbols[1]= [ a, A ], symbols[2]= [...]`.
|
||||
fn key_groups(body : Array[Char]) -> Array[Array[String]] {
|
||||
let groups : Array[Array[String]] = []
|
||||
let mut i = 0
|
||||
let n = body.length()
|
||||
// Whether the next '[' opens a keysym list: after '{', ',' or '=' preceded by symbols[..].
|
||||
let mut prev_word = ""
|
||||
let word = StringBuilder::new()
|
||||
let mut last_sig = '{'
|
||||
while i < n {
|
||||
let c = body[i]
|
||||
if c == '"' {
|
||||
i = i + 1
|
||||
while i < n && body[i] != '"' {
|
||||
i = i + 1
|
||||
}
|
||||
i = i + 1
|
||||
last_sig = '"'
|
||||
continue
|
||||
}
|
||||
if c.is_ascii_alphabetic() || c.is_ascii_digit() || c == '_' {
|
||||
word.write_char(c)
|
||||
i = i + 1
|
||||
continue
|
||||
}
|
||||
if word.to_string() != "" {
|
||||
prev_word = word.to_string()
|
||||
word.reset()
|
||||
last_sig = 'w'
|
||||
}
|
||||
if is_space(c) {
|
||||
i = i + 1
|
||||
continue
|
||||
}
|
||||
if c == '[' {
|
||||
if last_sig == 'w' {
|
||||
// An index like symbols[1] or actions[Group2]: skip it, remember what it indexes.
|
||||
let kind = prev_word
|
||||
while i < n && body[i] != ']' {
|
||||
i = i + 1
|
||||
}
|
||||
i = i + 1
|
||||
last_sig = if kind == "symbols" { 's' } else { 'x' }
|
||||
continue
|
||||
}
|
||||
let take = last_sig == '{' || last_sig == ',' || last_sig == 'S'
|
||||
let start = i + 1
|
||||
while i < n && body[i] != ']' {
|
||||
i = i + 1
|
||||
}
|
||||
if take {
|
||||
let syms : Array[String] = []
|
||||
for p in str_of(body, start, i).split(",") {
|
||||
syms.push(p.trim(chars=" \t\r\n").to_string())
|
||||
}
|
||||
groups.push(syms)
|
||||
}
|
||||
i = i + 1
|
||||
last_sig = ']'
|
||||
continue
|
||||
}
|
||||
if c == '=' {
|
||||
last_sig = if last_sig == 's' { 'S' } else { '=' }
|
||||
} else if c == ',' {
|
||||
last_sig = if last_sig == ']' { ',' } else { ',' }
|
||||
} else {
|
||||
last_sig = c
|
||||
}
|
||||
i = i + 1
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
///| Parse an xkb text keymap. None when it has no symbols we can use.
|
||||
pub fn Keymap::parse(text : String) -> Keymap? {
|
||||
let cs = chars_of(text)
|
||||
let codes : Map[String, Int] = {}
|
||||
match section(cs, "xkb_keycodes") {
|
||||
Some((a, b)) => {
|
||||
let aliases : Array[(String, String)] = []
|
||||
for st in statements(cs, a, b) {
|
||||
if st.has_prefix("alias") {
|
||||
let parts = st.split("=").to_array()
|
||||
if parts.length() == 2 {
|
||||
let al = parts[0].trim(chars=" \taliasAL").to_string()
|
||||
let tg = parts[1].trim(chars=" \t").to_string()
|
||||
aliases.push((al.trim(chars="<>").to_string(), tg.trim(chars="<>").to_string()))
|
||||
}
|
||||
} else {
|
||||
match parse_keycode(st) {
|
||||
Some((name, v)) => codes.set(name, v)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
for a in aliases {
|
||||
match codes.get(a.1) {
|
||||
Some(v) => if !codes.contains(a.0) { codes.set(a.0, v) }
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
let keys : Map[Int, KeySyms] = {}
|
||||
match section(cs, "xkb_symbols") {
|
||||
Some((a, b)) =>
|
||||
for st in statements(cs, a, b) {
|
||||
if !st.has_prefix("key ") && !st.has_prefix("key\t") {
|
||||
continue
|
||||
}
|
||||
let sc = chars_of(st)
|
||||
let mut lt = -1
|
||||
let mut gt = -1
|
||||
for i, c in sc {
|
||||
if c == '<' && lt < 0 {
|
||||
lt = i
|
||||
} else if c == '>' && lt >= 0 {
|
||||
gt = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if lt < 0 || gt < 0 {
|
||||
continue
|
||||
}
|
||||
let name = str_of(sc, lt + 1, gt)
|
||||
let mut ob = -1
|
||||
for i = gt; i < sc.length(); i = i + 1 {
|
||||
if sc[i] == '{' {
|
||||
ob = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if ob < 0 {
|
||||
continue
|
||||
}
|
||||
let body = sc[ob:].to_array()
|
||||
let groups = key_groups(body)
|
||||
if groups.length() == 0 {
|
||||
continue
|
||||
}
|
||||
let code = match codes.get(name) {
|
||||
Some(v) => v
|
||||
None => match us_codes().get(name) {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
}
|
||||
keys.set(code, { groups, })
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
if keys.length() == 0 {
|
||||
None
|
||||
} else {
|
||||
Some({ keys, })
|
||||
}
|
||||
}
|
||||
|
||||
///| Names of keysyms 0x20..0x7e (ASCII), in order.
|
||||
let ascii_names : Array[String] = [
|
||||
"space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "apostrophe",
|
||||
"parenleft", "parenright", "asterisk", "plus", "comma", "minus", "period", "slash", "0", "1",
|
||||
"2", "3", "4", "5", "6", "7", "8", "9", "colon", "semicolon", "less", "equal", "greater",
|
||||
"question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
|
||||
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash",
|
||||
"bracketright", "asciicircum", "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h",
|
||||
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
|
||||
"braceleft", "bar", "braceright", "asciitilde",
|
||||
]
|
||||
|
||||
///| Names of keysyms 0xa0..0xff (Latin-1, keysym = code point), in order.
|
||||
let latin1_names : Array[String] = [
|
||||
"nobreakspace", "exclamdown", "cent", "sterling", "currency", "yen", "brokenbar", "section",
|
||||
"diaeresis", "copyright", "ordfeminine", "guillemotleft", "notsign", "hyphen", "registered",
|
||||
"macron", "degree", "plusminus", "twosuperior", "threesuperior", "acute", "mu", "paragraph",
|
||||
"periodcentered", "cedilla", "onesuperior", "masculine", "guillemotright", "onequarter",
|
||||
"onehalf", "threequarters", "questiondown", "Agrave", "Aacute", "Acircumflex", "Atilde",
|
||||
"Adiaeresis", "Aring", "AE", "Ccedilla", "Egrave", "Eacute", "Ecircumflex", "Ediaeresis",
|
||||
"Igrave", "Iacute", "Icircumflex", "Idiaeresis", "ETH", "Ntilde", "Ograve", "Oacute",
|
||||
"Ocircumflex", "Otilde", "Odiaeresis", "multiply", "Oslash", "Ugrave", "Uacute",
|
||||
"Ucircumflex", "Udiaeresis", "Yacute", "THORN", "ssharp", "agrave", "aacute", "acircumflex",
|
||||
"atilde", "adiaeresis", "aring", "ae", "ccedilla", "egrave", "eacute", "ecircumflex",
|
||||
"ediaeresis", "igrave", "iacute", "icircumflex", "idiaeresis", "eth", "ntilde", "ograve",
|
||||
"oacute", "ocircumflex", "otilde", "odiaeresis", "division", "oslash", "ugrave", "uacute",
|
||||
"ucircumflex", "udiaeresis", "yacute", "thorn", "ydiaeresis",
|
||||
]
|
||||
|
||||
///| Other names that type a character.
|
||||
let extra_names : Array[(String, Int)] = [
|
||||
("EuroSign", 0x20ac),
|
||||
("guillemetleft", 0xab),
|
||||
("guillemetright", 0xbb),
|
||||
("Ooblique", 0xd8),
|
||||
("ooblique", 0xf8),
|
||||
("masculine", 0xba),
|
||||
("ordmasculine", 0xba),
|
||||
("KP_0", 0x30),
|
||||
("KP_1", 0x31),
|
||||
("KP_2", 0x32),
|
||||
("KP_3", 0x33),
|
||||
("KP_4", 0x34),
|
||||
("KP_5", 0x35),
|
||||
("KP_6", 0x36),
|
||||
("KP_7", 0x37),
|
||||
("KP_8", 0x38),
|
||||
("KP_9", 0x39),
|
||||
("KP_Decimal", 0x2e),
|
||||
("KP_Add", 0x2b),
|
||||
("KP_Subtract", 0x2d),
|
||||
("KP_Multiply", 0x2a),
|
||||
("KP_Divide", 0x2f),
|
||||
("KP_Space", 0x20),
|
||||
("KP_Separator", 0x2c),
|
||||
]
|
||||
|
||||
///|
|
||||
let name_table : Ref[Map[String, Int]?] = { val: None }
|
||||
|
||||
///|
|
||||
fn names() -> Map[String, Int] {
|
||||
match name_table.val {
|
||||
Some(m) => m
|
||||
None => {
|
||||
let m : Map[String, Int] = {}
|
||||
for i, n in ascii_names {
|
||||
m.set(n, 0x20 + i)
|
||||
}
|
||||
for i, n in latin1_names {
|
||||
m.set(n, 0xa0 + i)
|
||||
}
|
||||
for e in extra_names {
|
||||
m.set(e.0, e.1)
|
||||
}
|
||||
name_table.val = Some(m)
|
||||
m
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn hex_value(s : String) -> Int? {
|
||||
let mut v = 0
|
||||
if s.length() == 0 || s.length() > 8 {
|
||||
return None
|
||||
}
|
||||
for c in s {
|
||||
let d = if c >= '0' && c <= '9' {
|
||||
c.to_int() - '0'.to_int()
|
||||
} else if c >= 'a' && c <= 'f' {
|
||||
c.to_int() - 'a'.to_int() + 10
|
||||
} else if c >= 'A' && c <= 'F' {
|
||||
c.to_int() - 'A'.to_int() + 10
|
||||
} else {
|
||||
return None
|
||||
}
|
||||
v = v * 16 + d
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
|
||||
///| The character keysym `name` types, if any (dead keys, modifiers and unknown names: None).
|
||||
pub fn keysym_char(name : String) -> Char? {
|
||||
match names().get(name) {
|
||||
Some(cp) => return Some(Int::unsafe_to_char(cp))
|
||||
None => ()
|
||||
}
|
||||
let cp = if name.length() >= 5 && name.has_prefix("U") {
|
||||
hex_value(name[1:].to_string())
|
||||
} else if (name.length() == 9 || name.length() == 10) && name.has_prefix("0x100") {
|
||||
hex_value(name[5:].to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
match cp {
|
||||
Some(v) if v >= 0x20 && v < 0x110000 && !(v >= 0xd800 && v < 0xe000) && v != 0x7f =>
|
||||
Some(Int::unsafe_to_char(v))
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
|
||||
///| Modifier bits of an xkb state (wl_keyboard.modifiers): Shift, Lock (Caps), Mod5 (AltGr).
|
||||
pub let mask_shift : UInt = 1
|
||||
|
||||
///|
|
||||
pub let mask_lock : UInt = 2
|
||||
|
||||
///|
|
||||
pub let mask_ctrl : UInt = 4
|
||||
|
||||
///|
|
||||
pub let mask_alt : UInt = 8
|
||||
|
||||
///|
|
||||
pub let mask_altgr : UInt = 0x80
|
||||
|
||||
///| Whether `c` is a letter Caps Lock applies to: ASCII and Latin-1 letters, and anything past
|
||||
/// Latin-1 (Cyrillic, Greek, ...), as long as its two levels differ (checked by the caller).
|
||||
fn letter(c : Char) -> Bool {
|
||||
let v = c.to_int()
|
||||
c.is_ascii_alphabetic() || (v >= 0xc0 && v <= 0xff && v != 0xd7 && v != 0xf7) || v > 0x24f
|
||||
}
|
||||
|
||||
///| The character evdev key `code` types with modifier `mods` (depressed | latched | locked)
|
||||
/// in layout group `group`; None for keys that type nothing.
|
||||
pub fn Keymap::char_for(self : Keymap, code : UInt, mods : UInt, group : UInt) -> Char? {
|
||||
let ks = match self.keys.get(code.reinterpret_as_int() + 8) {
|
||||
Some(k) => k
|
||||
None => return None
|
||||
}
|
||||
let g = if group.reinterpret_as_int() < ks.groups.length() {
|
||||
ks.groups[group.reinterpret_as_int()]
|
||||
} else {
|
||||
ks.groups[0]
|
||||
}
|
||||
if g.length() == 0 {
|
||||
return None
|
||||
}
|
||||
let shift = (mods & mask_shift) != 0U
|
||||
let altgr = (mods & mask_altgr) != 0U && g.length() > 2
|
||||
let base = if altgr { 2 } else { 0 }
|
||||
let at = fn(l : Int) -> Char? {
|
||||
if l < g.length() {
|
||||
keysym_char(g[l])
|
||||
} else if l > 0 {
|
||||
keysym_char(g[l - 1])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
let mut level = base + (if shift { 1 } else { 0 })
|
||||
// Caps Lock flips the case of letters (the ALPHABETIC key type), not digits or punctuation.
|
||||
if (mods & mask_lock) != 0U {
|
||||
match (at(base), at(base + 1)) {
|
||||
(Some(lo), Some(up)) if lo != up && letter(lo) && letter(up) =>
|
||||
level = base + (if shift { 0 } else { 1 })
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
at(level)
|
||||
}
|
||||
|
||||
///| xkb keycode names of the US layout's keys (evdev + 8), for keymaps whose keycodes section
|
||||
/// is missing.
|
||||
fn us_codes() -> Map[String, Int] {
|
||||
let m : Map[String, Int] = {}
|
||||
let rows = [
|
||||
("TLDE", 49),
|
||||
("AE01", 10),
|
||||
("AE02", 11),
|
||||
("AE03", 12),
|
||||
("AE04", 13),
|
||||
("AE05", 14),
|
||||
("AE06", 15),
|
||||
("AE07", 16),
|
||||
("AE08", 17),
|
||||
("AE09", 18),
|
||||
("AE10", 19),
|
||||
("AE11", 20),
|
||||
("AE12", 21),
|
||||
("AD01", 24),
|
||||
("AD02", 25),
|
||||
("AD03", 26),
|
||||
("AD04", 27),
|
||||
("AD05", 28),
|
||||
("AD06", 29),
|
||||
("AD07", 30),
|
||||
("AD08", 31),
|
||||
("AD09", 32),
|
||||
("AD10", 33),
|
||||
("AD11", 34),
|
||||
("AD12", 35),
|
||||
("AC01", 38),
|
||||
("AC02", 39),
|
||||
("AC03", 40),
|
||||
("AC04", 41),
|
||||
("AC05", 42),
|
||||
("AC06", 43),
|
||||
("AC07", 44),
|
||||
("AC08", 45),
|
||||
("AC09", 46),
|
||||
("AC10", 47),
|
||||
("AC11", 48),
|
||||
("BKSL", 51),
|
||||
("AB01", 52),
|
||||
("AB02", 53),
|
||||
("AB03", 54),
|
||||
("AB04", 55),
|
||||
("AB05", 56),
|
||||
("AB06", 57),
|
||||
("AB07", 58),
|
||||
("AB08", 59),
|
||||
("AB09", 60),
|
||||
("AB10", 61),
|
||||
("SPCE", 65),
|
||||
("LSGT", 94),
|
||||
("KP7", 79),
|
||||
("KP8", 80),
|
||||
("KP9", 81),
|
||||
("KPSU", 82),
|
||||
("KP4", 83),
|
||||
("KP5", 84),
|
||||
("KP6", 85),
|
||||
("KPAD", 86),
|
||||
("KP1", 87),
|
||||
("KP2", 88),
|
||||
("KP3", 89),
|
||||
("KP0", 90),
|
||||
("KPDL", 91),
|
||||
("KPDV", 106),
|
||||
("KPMU", 63),
|
||||
]
|
||||
for r in rows {
|
||||
m.set(r.0, r.1)
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
///| The US layout, used when there is no keymap.
|
||||
let us_symbols : String =
|
||||
#|xkb_symbols "us" {
|
||||
#| key <TLDE> { [ grave, asciitilde ] };
|
||||
#| key <AE01> { [ 1, exclam ] };
|
||||
#| key <AE02> { [ 2, at ] };
|
||||
#| key <AE03> { [ 3, numbersign ] };
|
||||
#| key <AE04> { [ 4, dollar ] };
|
||||
#| key <AE05> { [ 5, percent ] };
|
||||
#| key <AE06> { [ 6, asciicircum ] };
|
||||
#| key <AE07> { [ 7, ampersand ] };
|
||||
#| key <AE08> { [ 8, asterisk ] };
|
||||
#| key <AE09> { [ 9, parenleft ] };
|
||||
#| key <AE10> { [ 0, parenright ] };
|
||||
#| key <AE11> { [ minus, underscore ] };
|
||||
#| key <AE12> { [ equal, plus ] };
|
||||
#| key <AD01> { [ q, Q ] };
|
||||
#| key <AD02> { [ w, W ] };
|
||||
#| key <AD03> { [ e, E ] };
|
||||
#| key <AD04> { [ r, R ] };
|
||||
#| key <AD05> { [ t, T ] };
|
||||
#| key <AD06> { [ y, Y ] };
|
||||
#| key <AD07> { [ u, U ] };
|
||||
#| key <AD08> { [ i, I ] };
|
||||
#| key <AD09> { [ o, O ] };
|
||||
#| key <AD10> { [ p, P ] };
|
||||
#| key <AD11> { [ bracketleft, braceleft ] };
|
||||
#| key <AD12> { [ bracketright, braceright ] };
|
||||
#| key <AC01> { [ a, A ] };
|
||||
#| key <AC02> { [ s, S ] };
|
||||
#| key <AC03> { [ d, D ] };
|
||||
#| key <AC04> { [ f, F ] };
|
||||
#| key <AC05> { [ g, G ] };
|
||||
#| key <AC06> { [ h, H ] };
|
||||
#| key <AC07> { [ j, J ] };
|
||||
#| key <AC08> { [ k, K ] };
|
||||
#| key <AC09> { [ l, L ] };
|
||||
#| key <AC10> { [ semicolon, colon ] };
|
||||
#| key <AC11> { [ apostrophe, quotedbl ] };
|
||||
#| key <BKSL> { [ backslash, bar ] };
|
||||
#| key <AB01> { [ z, Z ] };
|
||||
#| key <AB02> { [ x, X ] };
|
||||
#| key <AB03> { [ c, C ] };
|
||||
#| key <AB04> { [ v, V ] };
|
||||
#| key <AB05> { [ b, B ] };
|
||||
#| key <AB06> { [ n, N ] };
|
||||
#| key <AB07> { [ m, M ] };
|
||||
#| key <AB08> { [ comma, less ] };
|
||||
#| key <AB09> { [ period, greater ] };
|
||||
#| key <AB10> { [ slash, question ] };
|
||||
#| key <SPCE> { [ space ] };
|
||||
#| key <KP7> { [ KP_7 ] };
|
||||
#| key <KP8> { [ KP_8 ] };
|
||||
#| key <KP9> { [ KP_9 ] };
|
||||
#| key <KP4> { [ KP_4 ] };
|
||||
#| key <KP5> { [ KP_5 ] };
|
||||
#| key <KP6> { [ KP_6 ] };
|
||||
#| key <KP1> { [ KP_1 ] };
|
||||
#| key <KP2> { [ KP_2 ] };
|
||||
#| key <KP3> { [ KP_3 ] };
|
||||
#| key <KP0> { [ KP_0 ] };
|
||||
#| key <KPDL> { [ KP_Decimal ] };
|
||||
#| key <KPAD> { [ KP_Add ] };
|
||||
#| key <KPSU> { [ KP_Subtract ] };
|
||||
#| key <KPMU> { [ KP_Multiply ] };
|
||||
#| key <KPDV> { [ KP_Divide ] };
|
||||
#|};
|
||||
|
||||
///| The keymap `text` describes, or the US layout when it is empty or unusable.
|
||||
pub fn Keymap::from_text(text : String) -> Keymap {
|
||||
match Keymap::parse(text) {
|
||||
Some(k) => k
|
||||
None => Keymap::us()
|
||||
}
|
||||
}
|
||||
|
||||
///| The built-in US layout.
|
||||
pub fn Keymap::us() -> Keymap {
|
||||
Keymap::parse(us_symbols).unwrap()
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import {
|
||||
"moonbitlang/core/builtin",
|
||||
"moonbitlang/core/encoding/utf8" @utf8,
|
||||
"chandra/desktop/compositor/network" @network,
|
||||
"chandra/desktop/compositor/sys" @sys,
|
||||
}
|
||||
|
||||
supported_targets = "+native+wasm"
|
||||
|
||||
warnings = "-44"
|
||||
|
||||
import {
|
||||
"chandra/desktop/compositor/polkit" @polkit,
|
||||
"chandra/desktop/compositor/network" @network,
|
||||
"chandra/desktop/compositor/sys" @sys,
|
||||
"moonbitlang/core/encoding/utf8" @utf8,
|
||||
} for "test"
|
||||
@@ -0,0 +1,327 @@
|
||||
///| Keymaps, the helper protocol, request descriptions and the dialog's states.
|
||||
|
||||
///|
|
||||
fn type_keys(km : @polkit.Keymap, keys : Array[(UInt, UInt)]) -> String {
|
||||
let sb = StringBuilder::new()
|
||||
for k in keys {
|
||||
match km.char_for(k.0, k.1, 0U) {
|
||||
Some(c) => sb.write_char(c)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
sb.to_string()
|
||||
}
|
||||
|
||||
///|
|
||||
test "the built-in US layout types letters, shifted symbols and Caps Lock letters" {
|
||||
let km = @polkit.Keymap::us()
|
||||
// h i ! with shift on 1, then 'a' with Caps Lock, '1' with Caps Lock stays a digit.
|
||||
assert_eq(type_keys(km, [(35U, 0U), (23U, 0U), (2U, 1U), (30U, 2U), (2U, 2U), (30U, 3U)]), "hi!A1a")
|
||||
assert_eq(km.char_for(57U, 0U, 0U), Some(' '))
|
||||
assert_eq(km.char_for(1U, 0U, 0U), None) // Escape types nothing
|
||||
}
|
||||
|
||||
///| What xkbcommon's xkb_keymap_get_as_string writes (abridged), German layout in group 2.
|
||||
let xkb_text : String =
|
||||
#|xkb_keymap {
|
||||
#|xkb_keycodes "evdev+aliases(qwertz)" {
|
||||
#| minimum = 8;
|
||||
#| maximum = 255;
|
||||
#| <AE01> = 10;
|
||||
#| <AD06> = 29;
|
||||
#| <AB01> = 52;
|
||||
#| <AC11> = 48;
|
||||
#| alias <ALT1> = <AE01>;
|
||||
#|};
|
||||
#|xkb_types "complete" {
|
||||
#| type "ALPHABETIC" { modifiers= Shift+Lock; };
|
||||
#|};
|
||||
#|xkb_symbols "pc+us+de:2" {
|
||||
#| name[Group1]="English (US)";
|
||||
#| key <AE01> { [ 1, exclam ], [ 1, exclam, onesuperior, exclamdown ] };
|
||||
#| key <AD06> {
|
||||
#| type= "ALPHABETIC",
|
||||
#| symbols[1]= [ y, Y ],
|
||||
#| symbols[2]= [ z, Z ]
|
||||
#| };
|
||||
#| key <AB01> {
|
||||
#| type[Group1]= "ALPHABETIC",
|
||||
#| symbols[Group1]= [ z, Z ],
|
||||
#| symbols[Group2]= [ y, Y, guillemotright, U203A ]
|
||||
#| };
|
||||
#| key <AC11> { [ apostrophe, quotedbl ], [ adiaeresis, Adiaeresis, dead_circumflex, dead_caron ] };
|
||||
#| modifier_map Shift { <LFSH> };
|
||||
#|};
|
||||
#|};
|
||||
|
||||
///|
|
||||
test "an xkbcommon keymap: groups, levels, AltGr and Latin-1 keysyms" {
|
||||
let km = @polkit.Keymap::from_text(xkb_text)
|
||||
assert_eq(km.char_for(21U, 0U, 0U), Some('y')) // AD06, group 1
|
||||
assert_eq(km.char_for(21U, 0U, 1U), Some('z')) // group 2 (German)
|
||||
assert_eq(km.char_for(21U, 1U, 1U), Some('Z'))
|
||||
assert_eq(km.char_for(44U, 0U, 1U), Some('y')) // AB01 in group 2
|
||||
assert_eq(km.char_for(44U, 0x80U, 1U), Some('»')) // AltGr: level 3
|
||||
assert_eq(km.char_for(44U, 0x81U, 1U), Some('›')) // AltGr+Shift: level 4, U203A
|
||||
assert_eq(km.char_for(40U, 0U, 1U), Some('ä'))
|
||||
assert_eq(km.char_for(40U, 2U, 1U), Some('Ä')) // Caps Lock
|
||||
assert_eq(km.char_for(40U, 0x80U, 1U), None) // a dead key types nothing by itself
|
||||
assert_eq(km.char_for(2U, 1U, 0U), Some('!'))
|
||||
// Keys the keymap doesn't have type nothing.
|
||||
assert_eq(km.char_for(30U, 0U, 0U), None)
|
||||
}
|
||||
|
||||
///|
|
||||
test "keysym names" {
|
||||
assert_eq(@polkit.keysym_char("at"), Some('@'))
|
||||
assert_eq(@polkit.keysym_char("EuroSign"), Some('€'))
|
||||
assert_eq(@polkit.keysym_char("U0431"), Some('б'))
|
||||
assert_eq(@polkit.keysym_char("0x10020ac"), Some('€'))
|
||||
assert_eq(@polkit.keysym_char("Shift_L"), None)
|
||||
}
|
||||
|
||||
///|
|
||||
test "helper lines are unescaped as g_strcompress does" {
|
||||
assert_eq(@polkit.parse_helper_line("PAM_PROMPT_ECHO_OFF Password: "), Some(PromptEchoOff("Password: ")))
|
||||
assert_eq(@polkit.parse_helper_line("PAM_PROMPT_ECHO_ON Verification code:"), Some(PromptEchoOn("Verification code:")))
|
||||
assert_eq(
|
||||
@polkit.parse_helper_line("PAM_ERROR_MSG The account is locked due to 3 failed logins.\\n(5 minutes left to unlock)"),
|
||||
Some(ErrorMsg("The account is locked due to 3 failed logins.\n(5 minutes left to unlock)")),
|
||||
)
|
||||
assert_eq(@polkit.parse_helper_line("PAM_TEXT_INFO Place your finger on the \\\"reader\\\""), Some(TextInfo("Place your finger on the \"reader\"")))
|
||||
// Octal escapes are bytes of UTF-8.
|
||||
assert_eq(@polkit.unescape("caf\\303\\251"), "café")
|
||||
assert_eq(@polkit.parse_helper_line("SUCCESS"), Some(Success))
|
||||
assert_eq(@polkit.parse_helper_line("FAILURE"), Some(Failure))
|
||||
assert_eq(@polkit.parse_helper_line("polkit-agent-helper-1: noise"), None)
|
||||
}
|
||||
|
||||
///|
|
||||
test "run0 command lines" {
|
||||
assert_eq(@polkit.parse_run0(["run0", "gparted"]), ("root", ["gparted"]))
|
||||
assert_eq(@polkit.parse_run0(["/usr/bin/run0", "-u", "nandi", "--setenv", "A=1", "ls", "-la", "/root"]), ("nandi", ["ls", "-la", "/root"]))
|
||||
assert_eq(@polkit.parse_run0(["run0", "--user=postgres", "--", "psql", "-c", "select 1"]), ("postgres", ["psql", "-c", "select 1"]))
|
||||
assert_eq(@polkit.parse_run0(["run0", "--background=41"]), ("root", []))
|
||||
assert_eq(@polkit.command_text(["psql", "-c", "select 1", "it's"]), "psql -c 'select 1' 'it'\\''s'")
|
||||
assert_eq(@polkit.run0_unit_pid("run-p15802-i1990.service"), Some(15802))
|
||||
assert_eq(@polkit.run0_unit_pid("run-u12.service"), None)
|
||||
assert_eq(@polkit.quoted_in("Authentication is required to start transient unit 'run-p15802-i1990.service'."), "run-p15802-i1990.service")
|
||||
}
|
||||
|
||||
///|
|
||||
fn request(action : String, message : String, details : Map[String, String]) -> @polkit.AuthRequest {
|
||||
{
|
||||
action_id: action,
|
||||
message,
|
||||
icon_name: "",
|
||||
details,
|
||||
cookie: "3-abc-1-def",
|
||||
users: [{ uid: 1000, name: "nandi", real_name: "Nandi" }],
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
test "describe: run0 shows the command it will run, not the unit name" {
|
||||
let req = request(
|
||||
"org.freedesktop.systemd1.manage-units",
|
||||
"Authentication is required to start transient unit 'run-p15802-i1990.service'.",
|
||||
{ "unit": "run-p15802-i1990.service", "verb": "start", "polkit.subject-pid": "15802", "polkit.caller-pid": "1" },
|
||||
)
|
||||
let d = @polkit.describe(req, cmdline=pid => if pid == 15802 { ["run0", "gparted", "/dev/sda"] } else { [] }, who=pid => "run0 (pid " + pid.to_string() + ")")
|
||||
assert_eq(d.title, "Run a command as root")
|
||||
assert_eq(d.subtitle, "run0 needs your password to run this as root:")
|
||||
assert_eq(d.command, "gparted /dev/sda")
|
||||
assert_eq(d.program, "gparted")
|
||||
assert_eq(d.details, [("Requested by", "run0 (pid 15802)"), ("Runs as", "root"), ("Unit", "run-p15802-i1990.service"), ("Action", "org.freedesktop.systemd1.manage-units")])
|
||||
// Without details (older systemd), the unit name in the message still finds run0.
|
||||
let bare = request("org.freedesktop.systemd1.manage-units", req.message, {})
|
||||
let d2 = @polkit.describe(bare, cmdline=pid => if pid == 15802 { ["run0"] } else { [] }, who=_ => "")
|
||||
assert_eq(d2.title, "Open a shell as root")
|
||||
assert_eq(d2.command, "")
|
||||
}
|
||||
|
||||
///|
|
||||
test "describe: pkexec and other actions" {
|
||||
let pk = request("org.freedesktop.policykit.exec", "Authentication is needed to run `/usr/bin/gparted' as the super user", {
|
||||
"program": "/usr/bin/gparted",
|
||||
"command_line": "/usr/bin/gparted",
|
||||
"user": "root",
|
||||
})
|
||||
let d = @polkit.describe(pk, cmdline=_ => [], who=_ => "")
|
||||
assert_eq(d.title, "Run a program as root")
|
||||
assert_eq(d.command, "/usr/bin/gparted")
|
||||
assert_eq(d.program, "gparted")
|
||||
let other = request("org.freedesktop.udisks2.filesystem-mount-system", "Authentication is required to mount the drive", {})
|
||||
let d3 = @polkit.describe(other, cmdline=_ => [], who=_ => "")
|
||||
assert_eq(d3.title, "Authentication is required to mount the drive")
|
||||
assert_eq(d3.command, "")
|
||||
assert_eq(d3.details, [("Action", "org.freedesktop.udisks2.filesystem-mount-system")])
|
||||
}
|
||||
|
||||
///|
|
||||
test "identities: users, group members, the user at the screen first" {
|
||||
let passwd = @polkit.parse_passwd("root:x:0:0:root:/root:/bin/bash\nnandi:x:1000:1000:Nandi Devi,,,:/home/nandi:/bin/bash\nada:x:1001:1001::/home/ada:/bin/sh\n")
|
||||
let groups = @polkit.parse_group("root:x:0:\nwheel:x:10:ada,nandi\n")
|
||||
let ids : Array[@network.DValue] = [
|
||||
Struct([Str("unix-user"), @network.dict("v", [("uid", Variant(U32(0)))])]),
|
||||
Struct([Str("unix-group"), @network.dict("v", [("gid", Variant(U32(10)))])]),
|
||||
]
|
||||
let users = @polkit.users_for_identities(ids, passwd, groups, 1000)
|
||||
assert_eq(users.map(u => u.name), ["nandi", "root", "ada"])
|
||||
assert_eq(users[0].real_name, "Nandi Devi")
|
||||
}
|
||||
|
||||
///|
|
||||
fn dialog(users : Int) -> @polkit.AuthDialog {
|
||||
let us : Array[@polkit.AuthUser] = [{ uid: 1000, name: "nandi", real_name: "Nandi" }, { uid: 0, name: "root", real_name: "root" }]
|
||||
let req = { ..request("a", "m", {}), users: us[:users].to_array() }
|
||||
@polkit.AuthDialog::new(req, @polkit.describe(req, cmdline=_ => [], who=_ => ""))
|
||||
}
|
||||
|
||||
///|
|
||||
fn answer_text(e : @polkit.DialogEffect) -> String {
|
||||
match e {
|
||||
Answer(b) => {
|
||||
let s = @utf8.decode_lossy(Bytes::makei(b.length(), i => b[i]))
|
||||
@polkit.zero(b)
|
||||
s
|
||||
}
|
||||
_ => "<none>"
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
test "dialog: type, submit, wrong password, retry, success" {
|
||||
let d = dialog(1)
|
||||
let km = @polkit.Keymap::us()
|
||||
let type_str = fn(s : String) {
|
||||
for c in s {
|
||||
ignore(d.key(0U, 0U, Some(c)))
|
||||
}
|
||||
}
|
||||
// Typing before PAM's prompt is kept; Enter waits for it.
|
||||
type_str("hunter")
|
||||
assert_true(d.key(@polkit.key_enter, 0U, None) is Nothing)
|
||||
assert_eq(answer_text(d.helper(PromptEchoOff("Password: "), 10UL)), "hunter")
|
||||
assert_eq(d.phase, Checking)
|
||||
assert_eq(d.typed(), 0) // wiped once sent
|
||||
// Typing is ignored while PAM checks.
|
||||
ignore(d.key(30U, 0U, km.char_for(30U, 0U, 0U)))
|
||||
assert_eq(d.typed(), 0)
|
||||
// Wrong: error, shake, field cleared, the helper restarts.
|
||||
assert_true(d.helper(Failure, 100UL) is Restart)
|
||||
assert_eq(d.error, "Wrong password. Try again.")
|
||||
assert_eq(d.failures, 1)
|
||||
assert_true(d.shaking(200UL))
|
||||
assert_false(d.shaking(600UL))
|
||||
assert_true(d.shake_offset(100UL + 35UL) != 0)
|
||||
assert_eq(d.phase, Starting)
|
||||
assert_true(d.helper(PromptEchoOff("Password: "), 700UL) is Nothing)
|
||||
assert_eq(d.prompt, "Password")
|
||||
type_str("hunter2")
|
||||
assert_eq(d.error, "") // typing again clears it
|
||||
assert_eq(d.field_text(), "●●●●●●●")
|
||||
ignore(d.activate(Reveal))
|
||||
d.activate(Field) |> ignore
|
||||
assert_eq(d.field_text(), "hunter2")
|
||||
// Backspace, then Enter sends.
|
||||
ignore(d.key(@polkit.key_backspace, 0U, None))
|
||||
type_str("2")
|
||||
assert_eq(answer_text(d.key(@polkit.key_enter, 0U, None)), "hunter2")
|
||||
assert_true(d.helper(Success, 900UL) is Authorized)
|
||||
}
|
||||
|
||||
///|
|
||||
test "dialog: PAM messages, lockout, echo-on prompts, fingerprint" {
|
||||
let d = dialog(1)
|
||||
// A fingerprint module only informs; the dialog waits with its message.
|
||||
ignore(d.helper(TextInfo("Place your finger on the fingerprint reader"), 1UL))
|
||||
assert_eq(d.phase, Waiting)
|
||||
assert_eq(d.info, "Place your finger on the fingerprint reader")
|
||||
// Then falls back to a password.
|
||||
ignore(d.helper(PromptEchoOff("Password: "), 2UL))
|
||||
assert_eq(d.phase, Prompt)
|
||||
assert_eq(d.info, "")
|
||||
// An error from PAM (faillock) is shown as is after the failure.
|
||||
ignore(d.helper(ErrorMsg("The account is locked due to 3 failed logins."), 3UL))
|
||||
ignore(d.helper(Failure, 4UL))
|
||||
assert_eq(d.error, "The account is locked due to 3 failed logins.")
|
||||
// A visible prompt (a one-time code): typed text is shown, even empty answers go.
|
||||
ignore(d.helper(PromptEchoOn("Verification code: "), 5UL))
|
||||
assert_true(d.echo)
|
||||
ignore(d.key(0U, 0U, Some('4')))
|
||||
assert_eq(d.field_text(), "4")
|
||||
assert_eq(answer_text(d.key(@polkit.key_kp_enter, 0U, None)), "4")
|
||||
}
|
||||
|
||||
///|
|
||||
test "dialog: keyboard focus, Escape, Space toggles, user picker" {
|
||||
let d = dialog(2)
|
||||
assert_eq(d.focus, Field)
|
||||
assert_eq(d.focus_order(), [Field, User, Reveal, Details, Cancel, Allow])
|
||||
ignore(d.key(@polkit.key_tab, 0U, None))
|
||||
assert_eq(d.focus, User)
|
||||
assert_true(d.key(@polkit.key_right, 0U, None) is Restart)
|
||||
assert_eq(d.user().map(u => u.name), Some("root"))
|
||||
ignore(d.key(@polkit.key_tab, 0U, None))
|
||||
ignore(d.key(@polkit.key_space, 0U, None))
|
||||
assert_true(d.reveal)
|
||||
ignore(d.key(@polkit.key_tab, 0U, None))
|
||||
ignore(d.key(@polkit.key_enter, 0U, None))
|
||||
assert_true(d.details_open)
|
||||
ignore(d.key(@polkit.key_tab, 1U, None)) // Shift+Tab goes back
|
||||
assert_eq(d.focus, Reveal)
|
||||
// Typing anywhere goes to the field.
|
||||
ignore(d.key(0U, 0U, Some('x')))
|
||||
assert_eq(d.focus, Field)
|
||||
// Alt+D toggles details from the field; Ctrl+U clears it.
|
||||
ignore(d.key(@polkit.key_d, 8U, Some('d')))
|
||||
assert_false(d.details_open)
|
||||
ignore(d.key(@polkit.key_u, 4U, Some('u')))
|
||||
assert_eq(d.typed(), 0)
|
||||
assert_true(d.key(@polkit.key_esc, 0U, None) is Cancelled)
|
||||
// One user: no picker in the Tab order.
|
||||
assert_eq(dialog(1).focus_order(), [Field, Reveal, Details, Cancel, Allow])
|
||||
}
|
||||
|
||||
///|
|
||||
test "the setuid route: the helper runs on a socket pair and speaks the protocol" {
|
||||
// A stand-in for polkit-agent-helper-1: user name as argv[1], cookie then answer on stdin.
|
||||
let script = "/tmp/chandra-fake-helper-" + @sys.getpid().to_string()
|
||||
ignore(
|
||||
@sys.write_file_bytes(
|
||||
script,
|
||||
@utf8.encode(
|
||||
"#!/bin/sh\nread cookie\n[ \"$1\" = nandi ] && [ \"$cookie\" = c-1 ] || { echo FAILURE; exit 1; }\necho 'PAM_TEXT_INFO hello\\\\tthere'\necho 'PAM_PROMPT_ECHO_OFF Password: '\nread pw\nif [ \"$pw\" = 'pässword' ]; then echo SUCCESS; else echo FAILURE; fi\n",
|
||||
),
|
||||
),
|
||||
)
|
||||
ignore(@sys.spawn("chmod +x " + script, ""))
|
||||
@sys.sleep_ms(200)
|
||||
let s = @polkit.HelperSession::start(Program(script), "nandi", "c-1").unwrap()
|
||||
let got : Array[@polkit.HelperEvent] = []
|
||||
for i = 0; i < 200 && got.length() < 2; i = i + 1 {
|
||||
ignore(@sys.poll_read(s.fd(), 10))
|
||||
got.append(s.read())
|
||||
}
|
||||
assert_eq(got, [TextInfo("hello\tthere"), PromptEchoOff("Password: ")])
|
||||
let answer : FixedArray[Byte] = FixedArray::make(9, b'\x00')
|
||||
let b = @utf8.encode("pässword")
|
||||
for i = 0; i < b.length(); i = i + 1 {
|
||||
answer[i] = b[i]
|
||||
}
|
||||
assert_true(s.respond(answer))
|
||||
let end : Array[@polkit.HelperEvent] = []
|
||||
for i = 0; i < 200 && end.length() < 1; i = i + 1 {
|
||||
ignore(@sys.poll_read(s.fd(), 10))
|
||||
end.append(s.read())
|
||||
}
|
||||
assert_eq(end, [Success])
|
||||
// The helper exits: the session notices without inventing a second verdict.
|
||||
for i = 0; i < 50 && s.fd() >= 0; i = i + 1 {
|
||||
ignore(@sys.poll_read(s.fd(), 10))
|
||||
assert_eq(s.read(), [])
|
||||
}
|
||||
s.close()
|
||||
@sys.unlink(script)
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
///| What polkit asks the agent to authenticate (BeginAuthentication), and who could answer.
|
||||
|
||||
///| A user who can authenticate: uid, login name and real name (from the passwd database).
|
||||
pub(all) struct AuthUser {
|
||||
uid : Int
|
||||
name : String
|
||||
real_name : String
|
||||
} derive(Eq, Debug)
|
||||
|
||||
///| One BeginAuthentication call.
|
||||
pub(all) struct AuthRequest {
|
||||
action_id : String
|
||||
/// polkit's translated message ("Authentication is required to ...").
|
||||
message : String
|
||||
icon_name : String
|
||||
details : Map[String, String]
|
||||
cookie : String
|
||||
/// The users that may answer (unix-user identities, and the members of unix-group ones).
|
||||
users : Array[AuthUser]
|
||||
}
|
||||
|
||||
///| A detail by key, "" when absent.
|
||||
pub fn AuthRequest::detail(self : AuthRequest, key : String) -> String {
|
||||
self.details.get(key).unwrap_or("")
|
||||
}
|
||||
|
||||
///| A passwd/group database line split on ':'.
|
||||
fn fields(line : String) -> Array[String] {
|
||||
line.split(":").map(v => v.to_string()).to_array()
|
||||
}
|
||||
|
||||
///| Parse /etc/passwd text: uid -> (name, real name). The real name is GECOS up to its first ','.
|
||||
pub fn parse_passwd(text : String) -> Map[Int, (String, String)] {
|
||||
let out : Map[Int, (String, String)] = {}
|
||||
for raw in text.split("\n") {
|
||||
let f = fields(raw.to_string())
|
||||
if f.length() < 5 {
|
||||
continue
|
||||
}
|
||||
let uid = match parse_uint(f[2]) {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
let gecos = match f[4].find(",") {
|
||||
Some(i) => f[4][:i].to_string()
|
||||
None => f[4]
|
||||
}
|
||||
if !out.contains(uid) {
|
||||
out.set(uid, (f[0], gecos))
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| Parse /etc/group text: gid -> member names.
|
||||
pub fn parse_group(text : String) -> Map[Int, Array[String]] {
|
||||
let out : Map[Int, Array[String]] = {}
|
||||
for raw in text.split("\n") {
|
||||
let f = fields(raw.to_string())
|
||||
if f.length() < 4 {
|
||||
continue
|
||||
}
|
||||
let gid = match parse_uint(f[2]) {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
let members = f[3].split(",").map(v => v.to_string().trim(chars=" ").to_string()).filter(v => v != "").to_array()
|
||||
out.set(gid, members)
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| A decimal number.
|
||||
fn parse_uint(s : String) -> Int? {
|
||||
if s.length() == 0 || s.length() > 10 {
|
||||
return None
|
||||
}
|
||||
let mut v = 0
|
||||
for c in s {
|
||||
if c < '0' || c > '9' {
|
||||
return None
|
||||
}
|
||||
v = v * 10 + (c.to_int() - '0'.to_int())
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
|
||||
///| The users polkit's identities (a(sa{sv}): ("unix-user", {uid}) or ("unix-group", {gid}))
|
||||
/// stand for, in order, without repeats; a group stands for its members. `self_uid` (the user
|
||||
/// at the screen) is listed first when it is among them, as other agents do.
|
||||
pub fn users_for_identities(
|
||||
identities : Array[@network.DValue],
|
||||
passwd : Map[Int, (String, String)],
|
||||
groups : Map[Int, Array[String]],
|
||||
self_uid : Int,
|
||||
) -> Array[AuthUser] {
|
||||
let out : Array[AuthUser] = []
|
||||
let by_name : Map[String, Int] = {}
|
||||
for uid, e in passwd {
|
||||
by_name.set(e.0, uid)
|
||||
}
|
||||
let add = fn(uid : Int) {
|
||||
if out.iter().any(u => u.uid == uid) {
|
||||
return
|
||||
}
|
||||
let (name, real_name) = match passwd.get(uid) {
|
||||
Some(e) => e
|
||||
None => (uid.to_string(), "")
|
||||
}
|
||||
out.push({ uid, name, real_name })
|
||||
}
|
||||
let num = fn(v : @network.DValue) -> Int? {
|
||||
match v {
|
||||
Variant(inner) =>
|
||||
match inner {
|
||||
U32(x) => Some(x.reinterpret_as_int())
|
||||
I32(x) => Some(x)
|
||||
_ => None
|
||||
}
|
||||
U32(x) => Some(x.reinterpret_as_int())
|
||||
I32(x) => Some(x)
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
for id in identities {
|
||||
match id {
|
||||
Struct([Str(kind), Arr(_, entries)]) =>
|
||||
for e in entries {
|
||||
match e {
|
||||
Entry(Str(k), v) =>
|
||||
match (kind, k, num(v)) {
|
||||
("unix-user", "uid", Some(uid)) => add(uid)
|
||||
("unix-group", "gid", Some(gid)) =>
|
||||
for m in groups.get(gid).unwrap_or([]) {
|
||||
match by_name.get(m) {
|
||||
Some(uid) => add(uid)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
// The user at the screen first.
|
||||
match out.search_by(u => u.uid == self_uid) {
|
||||
Some(i) if i > 0 => {
|
||||
let me = out.remove(i)
|
||||
out.insert(0, me)
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| A string-to-string dict (a{ss}) as a map.
|
||||
pub fn string_dict(v : @network.DValue) -> Map[String, String] {
|
||||
let out : Map[String, String] = {}
|
||||
match v {
|
||||
Arr(_, entries) =>
|
||||
for e in entries {
|
||||
match e {
|
||||
Entry(Str(k), Str(x)) => out.set(k, x)
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///| Our uid, from /proc/self/status ("Uid:\treal\teffective..."); -1 when unknown.
|
||||
pub fn own_uid() -> Int {
|
||||
let text = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/self/status"))
|
||||
for line in text.split("\n") {
|
||||
let l = line.to_string()
|
||||
if l.has_prefix("Uid:") {
|
||||
let parts = l[4:].to_string().trim(chars=" \t").to_string().split("\t").to_array()
|
||||
if parts.length() > 0 {
|
||||
return parse_uint(parts[0].to_string().trim(chars=" ").to_string()).unwrap_or(-1)
|
||||
}
|
||||
}
|
||||
}
|
||||
-1
|
||||
}
|
||||
|
||||
///| The request BeginAuthentication's arguments describe (s s s a{ss} s a(sa{sv})); None when
|
||||
/// they don't match. Users come from /etc/passwd and /etc/group.
|
||||
pub fn AuthRequest::from_args(args : Array[@network.DValue]) -> AuthRequest? {
|
||||
match args {
|
||||
[Str(action_id), Str(message), Str(icon_name), details, Str(cookie), Arr(_, ids)] => {
|
||||
let passwd = parse_passwd(@utf8.decode_lossy(@sys.read_file_bytes("/etc/passwd")))
|
||||
let groups = parse_group(@utf8.decode_lossy(@sys.read_file_bytes("/etc/group")))
|
||||
let me = own_uid()
|
||||
// Users outside /etc/passwd (systemd-homed, LDAP): the one at the screen is $USER.
|
||||
if me >= 0 && !passwd.contains(me) && @sys.getenv("USER") != "" {
|
||||
passwd.set(me, (@sys.getenv("USER"), ""))
|
||||
}
|
||||
let users = users_for_identities(ids, passwd, groups, me)
|
||||
Some({ action_id, message, icon_name, details: string_dict(details), cookie, users })
|
||||
}
|
||||
_ => None
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user