///| 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 = #| #| #| #| #| #| #| #| #| #| #| #| #| #| #| #| #| #| ///| 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 { "" })]) (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 } ///| Parse an unsigned 64-bit decimal integer (returns None if empty, >20 chars, or non-digit). fn parse_u64(s : String) -> UInt64? { if s.length() == 0 || s.length() > 20 { return None } let mut v = 0UL for c in s { if c < '0' || c > '9' { return None } v = v * 10UL + (c.to_int() - '0'.to_int()).to_uint64() } Some(v) } ///| Build a polkit `unix-process` subject from `/proc//stat` and `/proc//status` text. pub fn process_subject_for(pid : Int, stat : String, status : String) -> @network.DValue { let start_time = match stat.rev_find(")") { Some(i) => { let parts = stat[i + 1:].to_string().trim(chars=" \t\n").to_string().split(" ").map(v => v.to_string()).filter(v => v != "").to_array() if parts.length() > 19 { parse_u64(parts[19]).unwrap_or(0UL) } else { 0UL } } None => 0UL } let uid = uid_from_status(status) Struct([ Str("unix-process"), @network.dict("v", [ ("pid", Variant(U32(pid.reinterpret_as_uint()))), ("start-time", Variant(U64(start_time))), ("uid", Variant(I32(uid))), ]), ]) } ///| The polkit subject representing the current agent process (`unix-process`). fn process_subject() -> @network.DValue { let pid = @sys.getpid() let stat = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/stat")) let status = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/" + pid.to_string() + "/status")) process_subject_for(pid, stat, status) } ///| Ask polkit to authorize `action_id` for the agent process, allowing user interaction: polkit /// then drives this same agent's dialog (face via PAM, then password), and the reply says whether /// it succeeded. Used for session unlock (org.chandra.unlock). False before registration or without a bus. pub fn PolkitAgent::check_unlock( self : PolkitAgent, action_id : String, cancel_id : String, on_result : (Bool) -> Unit, ) -> Bool { if !self.registered { return false } match self.bus { Some(bus) => { let serial = bus.call( @network.DMessage::call(authority_name, authority_path, authority_iface, "CheckAuthorization", [ process_subject(), Str(action_id), @network.dict("s", []), U32(1U), // AllowUserInteraction Str(cancel_id), ]), on_reply=fn(m) { let ok = match m { { mtype: 2, body: [Struct([Bool(a), ..]), ..], .. } => a { mtype: 2, .. } => { alog("unlock: unexpected CheckAuthorization reply") false } _ => { alog("unlock: CheckAuthorization error: " + m.error_text()) false } } on_result(ok) }, ) serial != 0 } None => false } } ///| Cancel an in-flight CheckAuthorization call identified by `cancel_id`. pub fn PolkitAgent::cancel_unlock(self : PolkitAgent, cancel_id : String) -> Unit { if cancel_id == "" { return } match self.bus { Some(bus) => ignore( bus.call( @network.DMessage::call(authority_name, authority_path, authority_iface, "CancelCheckAuthorization", [ Str(cancel_id), ]), on_reply=fn(_) { () }, ), ) None => () } } ///| 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 }