1mod helper;
13#[cfg(test)]
14mod tests;
15
16use std::cell::{Cell, RefCell};
17use std::collections::{HashMap, VecDeque};
18use std::future::poll_fn;
19use std::path::{Path, PathBuf};
20use std::pin::Pin;
21use std::rc::Rc;
22use std::sync::atomic::{AtomicUsize, Ordering};
23use std::sync::{Arc, Once};
24use std::time::{Duration, Instant};
25
26use calloop::channel::Event as Arrived;
27use calloop::timer::TimeoutAction;
28use calloop::{Interest, RegistrationToken};
29use crabshell_reactive::{ReadSignal, Signal};
30use crabshell_ui::Cx;
31use zbus::export::futures_core::Stream;
32use zbus::message::{Flags, Type as Kind};
33use zbus::{Connection, Message, MessageStream, OwnedVariant, Variant};
34
35use self::helper::{Helper, Line, Secret};
36use crate::Shared;
37use crate::dbus::{CALL_TIMEOUT, bus_call, owner_changed, owner_rule, set_changed};
38
39const AUTHORITY: &str = "org.freedesktop.PolicyKit1";
40const AUTHORITY_PATH: &str = "/org/freedesktop/PolicyKit1/Authority";
41const AUTHORITY_INTERFACE: &str = "org.freedesktop.PolicyKit1.Authority";
42const AGENT_INTERFACE: &str = "org.freedesktop.PolicyKit1.AuthenticationAgent";
43const AGENT_PATH: &str = "/org/crabshell/PolkitAgent";
45
46pub(crate) const HELPERS: [&str; 4] = [
49 "/usr/lib/polkit-1/polkit-agent-helper-1",
50 "/usr/libexec/polkit-agent-helper-1",
51 "/usr/libexec/polkit-1/polkit-agent-helper-1",
52 "/run/wrappers/bin/polkit-agent-helper-1",
53];
54
55fn helper_path(helpers: &[PathBuf]) -> &Path {
58 let found = helpers.iter().find(|path| path.exists());
59 found
60 .or(helpers.first())
61 .map_or(Path::new(""), PathBuf::as_path)
62}
63
64pub(crate) const HELPER_SOCKET: &str = "/run/polkit/agent-helper.socket";
67
68const FAILED: &str = "org.freedesktop.PolicyKit1.Error.Failed";
69const CANCELLED: &str = "org.freedesktop.PolicyKit1.Error.Cancelled";
70const ACCESS_DENIED: &str = "org.freedesktop.DBus.Error.AccessDenied";
71const INVALID_ARGS: &str = "org.freedesktop.DBus.Error.InvalidArgs";
72const UNKNOWN_METHOD: &str = "org.freedesktop.DBus.Error.UnknownMethod";
73
74const MAX_TEXT: usize = 4 * 1024;
76const MAX_TRIES: u32 = 3;
78const MAX_IDENTITIES: usize = 64;
80const MAX_QUEUED: usize = 8;
82pub(crate) const USERS_LIMIT: Duration = Duration::from_secs(3);
85
86const MAX_LOOKUPS: usize = 4;
89
90pub(crate) type Found = (usize, Option<String>);
93
94const MAX_LINES: usize = 16;
96
97#[derive(Clone, Debug, PartialEq)]
100pub struct AuthRequest {
101 id: u64,
104 pub action_id: String,
106 pub message: String,
108 pub icon_name: String,
110 pub identities: Vec<String>,
113 pub state: AuthState,
115 pub info: Vec<String>,
118 pub errors: Vec<String>,
120}
121
122#[derive(Clone, Debug, PartialEq)]
124pub enum AuthState {
125 Waiting,
127 Asking {
131 message: String,
133 visible: bool,
135 },
136 Busy,
138 Failed {
141 message: String,
143 },
144}
145
146#[derive(Clone)]
149pub struct PolkitAgent {
150 service: Option<Rc<Service>>,
152 request: ReadSignal<Option<AuthRequest>>,
153}
154
155impl PolkitAgent {
156 pub fn request(&self) -> ReadSignal<Option<AuthRequest>> {
159 self.request
160 }
161
162 pub fn respond(&self, text: impl Into<String>) {
167 let secret = Secret(text.into().into_bytes());
168 if let Some(service) = &self.service {
169 service.respond(secret);
170 }
171 }
172
173 pub fn cancel(&self) {
176 if let Some(service) = &self.service {
177 service.finish(Some((CANCELLED, "the user cancelled")));
178 }
179 }
180
181 pub fn pick_identity(&self, name: &str) {
185 if let Some(service) = &self.service {
186 service.pick(name);
187 }
188 }
189}
190
191pub(crate) fn polkit_agent(cx: &Cx) -> PolkitAgent {
193 let Some(service) = cx.service::<Service>() else {
194 static LOGGED: Once = Once::new();
195 LOGGED.call_once(|| {
196 tracing::warn!("cx.polkit_agent() needs the services the shell provides; no requests arrive");
197 });
198 return PolkitAgent {
199 service: None,
200 request: cx.signal(None).read_only(),
201 };
202 };
203 let request = service.start();
204 PolkitAgent {
205 service: Some(service),
206 request,
207 }
208}
209
210pub(crate) struct Service {
212 shared: Rc<Shared>,
213 state: RefCell<Option<State>>,
214 next: Cell<u64>,
216 lookups: Arc<AtomicUsize>,
219}
220
221struct Lookup(Arc<AtomicUsize>);
223
224impl Drop for Lookup {
225 fn drop(&mut self) {
226 self.0.fetch_sub(1, Ordering::Relaxed);
227 }
228}
229
230struct State {
231 request: Signal<Option<AuthRequest>>,
232 connection: Option<Connection>,
234 authority: Option<String>,
237 current: Option<Current>,
238 queue: VecDeque<Begin>,
240 resolving: Vec<Resolving>,
242}
243
244struct Resolving {
247 begin: Begin,
248 uids: Vec<u32>,
249 names: Vec<Option<String>>,
250 sources: Vec<RegistrationToken>,
252 done: bool,
253}
254
255struct StopOnDrop(Rc<Service>);
258
259impl Drop for StopOnDrop {
260 fn drop(&mut self) {
261 self.0.forget();
262 }
263}
264
265struct Begin {
267 call: Message,
268 cookie: String,
269 shown: AuthRequest,
270}
271
272struct Current {
274 begin: Begin,
275 failures: u32,
276 helper: Option<Helper>,
277 answer: Option<Secret>,
279}
280
281impl Current {
282 fn new(begin: Begin) -> Current {
283 Current {
284 begin,
285 failures: 0,
286 helper: None,
287 answer: None,
288 }
289 }
290}
291
292impl Service {
293 pub(crate) fn new(shared: Rc<Shared>) -> Service {
294 Service {
295 shared,
296 state: RefCell::new(None),
297 next: Cell::new(1),
298 lookups: Arc::default(),
299 }
300 }
301
302 fn next(&self) -> u64 {
303 let next = self.next.get();
304 self.next.set(next + 1);
305 next
306 }
307
308 fn start(self: &Rc<Self>) -> ReadSignal<Option<AuthRequest>> {
310 if let Some(state) = &*self.state.borrow() {
311 return state.request.read_only();
312 }
313 let request = self.shared.root.signal(None);
314 *self.state.borrow_mut() = Some(State {
315 request,
316 connection: None,
317 authority: None,
318 current: None,
319 queue: VecDeque::new(),
320 resolving: Vec::new(),
321 });
322 self.shared.root.signal(StopOnDrop(Rc::clone(self)));
323 match self.shared.config.system_bus.clone() {
324 Some(address) => self.shared.spawn(run(Rc::clone(self), address)),
325 None => tracing::info!("no system bus, so no polkit requests arrive"),
326 }
327 request.read_only()
328 }
329
330 fn forget(&self) {
333 if let Some(state) = self.state.borrow_mut().as_mut() {
334 state.connection = None;
335 }
336 self.drop_requests();
337 }
338
339 fn drop_requests(&self) {
342 let resolving = self
343 .state
344 .borrow_mut()
345 .as_mut()
346 .map(|state| std::mem::take(&mut state.resolving));
347 for resolving in resolving.unwrap_or_default() {
348 self.remove(resolving.sources);
349 }
350 let current = self.state.borrow_mut().as_mut().and_then(|state| {
351 state.queue.clear();
352 state.authority = None;
353 state.current.take()
354 });
355 if let Some(helper) = current.and_then(|current| current.helper) {
356 helper.stop(&self.shared, true);
357 }
358 }
359
360 fn alive(&self) -> bool {
363 let state = self.state.borrow();
364 let alive = state
365 .as_ref()
366 .and_then(|state| state.request.try_with(|_| ()));
367 alive.is_some()
368 }
369
370 fn with_current<R>(&self, f: impl FnOnce(&mut Current) -> R) -> Option<R> {
372 let mut state = self.state.borrow_mut();
373 state.as_mut()?.current.as_mut().map(f)
374 }
375
376 fn publish(&self) {
378 let shown = self.state.borrow().as_ref().map(|state| {
379 let current = state.current.as_ref();
380 (
381 state.request,
382 current.map(|current| current.begin.shown.clone()),
383 )
384 });
385 if let Some((signal, shown)) = shown {
386 set_changed(signal, shown);
387 }
388 }
389
390 fn on_call(self: &Rc<Self>, call: Message) {
392 let header = call.header();
393 let sender = header.sender().map(|sender| sender.as_str());
394 let authority = self
395 .state
396 .borrow()
397 .as_ref()
398 .and_then(|state| state.authority.clone());
399 if sender.is_none() || sender != authority.as_deref() {
400 tracing::warn!(
401 ?sender,
402 "a program other than polkit called the agent; refused"
403 );
404 return self.reply(
405 &call,
406 Some((ACCESS_DENIED, "only polkit may call the agent")),
407 );
408 }
409 let path = header.path().map(|path| path.as_str());
410 let interface = header.interface().map(|interface| interface.as_str());
411 let member = header.member().map(|member| member.as_str());
412 match (path, interface, member) {
413 (Some(AGENT_PATH), Some(AGENT_INTERFACE), Some("BeginAuthentication")) => self.begin(call),
414 (Some(AGENT_PATH), Some(AGENT_INTERFACE), Some("CancelAuthentication")) => {
415 self.cancelled(call);
416 }
417 _ => self.reply(&call, Some((UNKNOWN_METHOD, "no such method"))),
418 }
419 }
420
421 fn begin(self: &Rc<Self>, call: Message) {
423 let (begin, uids) = match begin_args(&call, self.next()) {
424 Ok(begun) => begun,
425 Err((error, why)) => {
426 tracing::warn!(why, "a polkit request the agent can't answer");
427 return self.reply(&call, Some((error, why)));
428 }
429 };
430 let full = {
431 let state = self.state.borrow();
432 let Some(state) = state.as_ref() else {
433 return;
434 };
435 let held = usize::from(state.current.is_some()) + state.queue.len();
436 held + state.resolving.len() > MAX_QUEUED
437 };
438 if full {
439 tracing::warn!("{MAX_QUEUED} polkit requests wait already; refused another");
440 return self.reply(&begin.call, Some((FAILED, "too many requests wait")));
441 }
442 if self.lookups.load(Ordering::Relaxed) >= MAX_LOOKUPS {
443 tracing::warn!("{MAX_LOOKUPS} user lookups still hang in NSS; refused a polkit request");
444 return self.reply(&begin.call, Some((FAILED, "user lookups hang")));
445 }
446 let action = &begin.shown.action_id;
447 tracing::info!(action, "polkit asks to authenticate");
448 self.resolve(begin, uids);
449 }
450
451 fn resolve(self: &Rc<Self>, begin: Begin, uids: Vec<u32>) {
454 let id = begin.shown.id;
455 let mut sources = Vec::new();
456 if let Some(event_loop) = self.shared.event_loop() {
457 let (sender, channel) = calloop::channel::channel::<Found>();
458 let lookup = Arc::clone(&self.shared.config.polkit_users);
459 let looked = uids.clone();
460 self.lookups.fetch_add(1, Ordering::Relaxed);
461 let lookup_ends = Lookup(Arc::clone(&self.lookups));
462 let spawned = std::thread::Builder::new()
463 .name(String::from("crabshell-users"))
464 .spawn(move || {
465 let _ends = lookup_ends;
466 for (at, uid) in looked.into_iter().enumerate() {
467 if sender.send((at, lookup(uid))).is_err() {
469 return;
470 }
471 }
472 });
473 if let Err(error) = spawned {
475 tracing::warn!(%error, "couldn't look polkit's users up");
476 }
477 let service = Rc::clone(self);
478 let arrived = Box::new(move |event| match event {
479 Arrived::Msg((at, name)) => service.found(id, at, name),
480 Arrived::Closed => service.resolved(id),
481 });
482 sources.extend(event_loop.insert_users_channel(channel, arrived));
483 let service = Rc::clone(self);
484 let limit = Instant::now() + self.shared.config.polkit_users_limit;
485 let tick = Box::new(move || {
486 service.resolved(id);
487 TimeoutAction::Drop
488 });
489 sources.extend(event_loop.insert_timer(limit, tick));
490 }
491 let done = sources.is_empty();
492 if let Some(state) = self.state.borrow_mut().as_mut() {
493 let names = vec![None; uids.len()];
494 state.resolving.push(Resolving {
495 begin,
496 uids,
497 names,
498 sources,
499 done,
500 });
501 }
502 self.promote();
503 }
504
505 fn found(&self, id: u64, at: usize, name: Option<String>) {
507 let mut state = self.state.borrow_mut();
508 let resolving = state.as_mut().and_then(|state| {
509 let mut all = state.resolving.iter_mut();
510 all.find(|resolving| resolving.begin.shown.id == id)
511 });
512 if let Some(slot) = resolving.and_then(|resolving| resolving.names.get_mut(at)) {
513 *slot = name;
514 }
515 }
516
517 fn resolved(self: &Rc<Self>, id: u64) {
519 let sources = self.state.borrow_mut().as_mut().and_then(|state| {
520 let mut all = state.resolving.iter_mut();
521 let resolving = all.find(|resolving| resolving.begin.shown.id == id)?;
522 resolving.done = true;
523 Some(std::mem::take(&mut resolving.sources))
524 });
525 if let Some(sources) = sources {
526 self.remove(sources);
527 self.promote();
528 }
529 }
530
531 fn remove(&self, sources: Vec<RegistrationToken>) {
532 if let Some(event_loop) = self.shared.event_loop() {
533 for token in sources {
534 event_loop.remove(token);
535 }
536 }
537 }
538
539 fn promote(self: &Rc<Self>) {
543 loop {
544 let next = self.state.borrow_mut().as_mut().and_then(|state| {
545 let first = state.resolving.first()?;
546 first.done.then(|| state.resolving.remove(0))
547 });
548 let Some(Resolving {
549 mut begin,
550 uids,
551 names,
552 ..
553 }) = next
554 else {
555 return;
556 };
557 let found = uids.iter().zip(names).filter_map(|(uid, name)| {
558 name.or_else(|| {
559 tracing::info!(uid, "polkit named a user NSS didn't name in time; left out");
560 None
561 })
562 });
563 begin.shown.identities = found.collect();
564 if begin.shown.identities.is_empty() {
565 let why = "no user the agent knows may answer";
566 tracing::warn!(why, "a polkit request the agent can't answer");
567 self.reply(&begin.call, Some((FAILED, why)));
568 continue;
569 }
570 let first = self.state.borrow_mut().as_mut().is_some_and(|state| {
571 if state.current.is_some() {
572 state.queue.push_back(begin);
573 return false;
574 }
575 state.current = Some(Current::new(begin));
576 true
577 });
578 if first {
579 self.run_helper();
580 }
581 }
582 }
583
584 fn cancelled(self: &Rc<Self>, call: Message) {
586 let Ok(cookie) = call.body().deserialize::<String>() else {
587 return self.reply(&call, Some((INVALID_ARGS, "not a cookie")));
588 };
589 self.reply(&call, None);
590 let why = "polkit cancelled it";
591 let current = self.with_current(|current| current.begin.cookie == cookie);
592 if current == Some(true) {
593 tracing::info!("polkit cancelled the request");
594 return self.finish(Some((CANCELLED, why)));
595 }
596 let queued = self.state.borrow_mut().as_mut().and_then(|state| {
597 let at = state
598 .queue
599 .iter()
600 .position(|begin| begin.cookie == cookie)?;
601 state.queue.remove(at)
602 });
603 if let Some(begin) = queued {
604 return self.reply(&begin.call, Some((CANCELLED, why)));
605 }
606 let resolving = self.state.borrow_mut().as_mut().and_then(|state| {
607 let mut all = state.resolving.iter();
608 let at = all.position(|resolving| resolving.begin.cookie == cookie)?;
609 Some(state.resolving.remove(at))
610 });
611 if let Some(resolving) = resolving {
612 self.remove(resolving.sources);
613 self.reply(&resolving.begin.call, Some((CANCELLED, why)));
614 self.promote();
615 }
616 }
617
618 fn pick(self: &Rc<Self>, name: &str) {
620 let picked = self.with_current(|current| {
621 let identities = &mut current.begin.shown.identities;
622 let at = identities.iter().position(|known| known == name)?;
623 identities[..=at].rotate_right(1);
624 current.answer = None;
625 Some(current.helper.take())
626 });
627 let Some(helper) = picked.flatten() else {
628 return tracing::warn!(name, "no such identity to pick for polkit");
629 };
630 if let Some(helper) = helper {
631 helper.stop(&self.shared, true);
632 }
633 self.run_helper();
634 }
635
636 fn run_helper(self: &Rc<Self>) {
638 let Some(event_loop) = self.shared.event_loop() else {
639 return;
640 };
641 let run = self.next();
642 let started = self.with_current(|current| {
643 let shown = &mut current.begin.shown;
644 shown.state = AuthState::Waiting;
645 shown.info.clear();
646 shown.errors.clear();
647 let config = &self.shared.config;
648 let user = &shown.identities[0];
649 let program = helper_path(&config.polkit_helpers);
650 let mut helper = Helper::start(program, &config.polkit_socket, user, run)?;
651 if let Err(error) = helper.send(current.begin.cookie.as_bytes()) {
652 helper.stop(&self.shared, true);
653 return Err(error);
654 }
655 let service = Rc::clone(self);
656 let ready = Box::new(move || service.on_output(run));
657 helper.token = helper
658 .stdout_fd()
659 .and_then(|fd| event_loop.insert_fd(fd, Interest::READ, ready));
660 if helper.token.is_none() {
661 helper.stop(&self.shared, true);
662 return Err(std::io::Error::other("its output couldn't be watched"));
663 }
664 current.helper = Some(helper);
665 Ok(())
666 });
667 match started {
668 Some(Ok(())) => self.publish(),
669 Some(Err(error)) => {
670 let program = helper_path(&self.shared.config.polkit_helpers).display();
671 tracing::warn!(%error, %program, "couldn't start polkit's helper");
672 self.finish(Some((FAILED, "polkit's helper couldn't start")));
673 }
674 None => {}
675 }
676 }
677
678 fn on_output(self: &Rc<Self>, run: u64) {
680 let running = |service: &Service| {
681 let running =
682 service.with_current(|current| current.helper.as_ref().map(|helper| helper.run));
683 running.flatten() == Some(run)
684 };
685 if !running(self) {
686 return;
687 }
688 let read = self.with_current(|current| current.helper.as_mut()?.read());
689 let Some((lines, ended)) = read.flatten() else {
690 return;
691 };
692 for line in lines {
693 if !running(self) {
694 return;
695 }
696 self.on_line(helper::parse(&line));
697 }
698 if ended && running(self) {
699 tracing::warn!("polkit's helper ended without an answer");
700 self.failed();
701 }
702 }
703
704 fn on_line(self: &Rc<Self>, line: Line) {
705 let keep = |lines: &mut Vec<String>, text| {
706 if lines.len() == MAX_LINES {
707 lines.remove(0);
708 }
709 lines.push(text);
710 };
711 let verdict = line_verdict(&line);
712 let answer = self.with_current(|current| {
713 let shown = &mut current.begin.shown;
714 match line {
715 Line::Prompt { message, visible } => {
716 shown.state = AuthState::Asking { message, visible };
717 return current.answer.take();
718 }
719 Line::Info(text) => keep(&mut shown.info, text),
720 Line::Error(text) => keep(&mut shown.errors, text),
721 Line::Unknown => tracing::debug!("polkit's helper printed a line it doesn't know; skipped"),
722 Line::Success | Line::Failure => {}
723 }
724 None
725 });
726 match verdict {
727 Some(true) => {
728 tracing::info!("authenticated for polkit");
729 self.finish(None);
730 }
731 Some(false) => self.failed(),
732 None => match answer.flatten() {
733 Some(secret) => self.send(secret),
735 None => self.publish(),
736 },
737 }
738 }
739
740 fn failed(self: &Rc<Self>) {
743 let gave_up = self.with_current(|current| {
744 if let Some(helper) = current.helper.take() {
745 helper.stop(&self.shared, true);
746 }
747 current.answer = None;
748 current.failures += 1;
749 let shown = &mut current.begin.shown;
750 let message = shown.errors.last().cloned();
751 let message = message.unwrap_or_else(|| String::from("Authentication failed"));
752 shown.state = AuthState::Failed { message };
753 current.failures >= MAX_TRIES
754 });
755 match gave_up {
756 Some(true) => {
757 tracing::info!("polkit authentication failed {MAX_TRIES} times");
758 self.finish(Some((FAILED, "authentication failed")));
759 }
760 Some(false) => self.publish(),
761 None => {}
762 }
763 }
764
765 fn respond(self: &Rc<Self>, secret: Secret) {
767 if secret.0.contains(&b'\n') || secret.0.contains(&0) {
770 return tracing::warn!("a polkit answer with a line break or NUL was dropped");
771 }
772 let state = self.with_current(|current| current.begin.shown.state.clone());
773 match state {
774 Some(AuthState::Asking { .. }) => self.send(secret),
775 Some(AuthState::Failed { .. }) => {
776 self.with_current(|current| current.answer = Some(secret));
777 self.run_helper();
778 }
779 _ => tracing::debug!("no polkit question to answer; an answer was dropped"),
780 }
781 }
782
783 fn send(self: &Rc<Self>, secret: Secret) {
786 let sent = self.with_current(|current| {
787 let sent = current.helper.as_mut().map(|helper| helper.send(&secret.0));
788 if let Some(Ok(())) = sent {
789 current.begin.shown.state = AuthState::Busy;
790 }
791 sent
792 });
793 match sent.flatten() {
794 Some(Ok(())) => self.publish(),
795 Some(Err(error)) => {
796 tracing::warn!(%error, "couldn't answer polkit's helper");
797 self.failed();
798 }
799 None => {}
800 }
801 }
802
803 fn finish(self: &Rc<Self>, error: Option<(&'static str, &str)>) {
807 let current = self.state.borrow_mut().as_mut().and_then(|state| {
808 let current = state.current.take()?;
809 state.current = state.queue.pop_front().map(Current::new);
810 Some(current)
811 });
812 let Some(current) = current else {
813 return;
814 };
815 if let Some(helper) = current.helper {
816 helper.stop(&self.shared, error.is_some());
818 }
819 self.reply(¤t.begin.call, error);
820 match self.with_current(|_| ()) {
821 Some(()) => self.run_helper(),
822 None => self.publish(),
823 }
824 }
825
826 fn reply(&self, call: &Message, error: Option<(&str, &str)>) {
829 let header = call.header();
830 if header.primary().flags().contains(Flags::NO_REPLY_EXPECTED) {
831 return;
832 }
833 let reply = match error {
834 None => Message::method_return(&header).build(&()),
835 Some((name, why)) => Message::error(&header, name).build(&why),
836 };
837 let connection = self
838 .state
839 .borrow()
840 .as_ref()
841 .and_then(|state| state.connection.clone());
842 let Some(connection) = connection else {
843 return;
844 };
845 self.shared.spawn(async move {
846 let sent = match reply {
847 Ok(reply) => connection.send(&reply).await,
848 Err(error) => Err(error),
849 };
850 if let Err(error) = sent {
851 tracing::debug!(%error, "the polkit agent's answer wasn't sent");
852 }
853 });
854 }
855}
856
857fn line_verdict(line: &Line) -> Option<bool> {
860 match line {
861 Line::Success => Some(true),
862 Line::Failure => Some(false),
863 _ => None,
864 }
865}
866
867type BeginArgs<'a> = (
870 &'a str,
871 &'a str,
872 &'a str,
873 HashMap<&'a str, &'a str>,
874 &'a str,
875 Vec<(&'a str, HashMap<&'a str, OwnedVariant>)>,
876);
877
878fn begin_args(call: &Message, id: u64) -> Result<(Begin, Vec<u32>), (&'static str, &'static str)> {
882 let body = call.body();
883 let Ok((action_id, message, icon_name, _, cookie, identities)) =
884 body.deserialize::<BeginArgs<'_>>()
885 else {
886 return Err((INVALID_ARGS, "not a polkit request"));
887 };
888 if cookie.is_empty() || cookie.len() > MAX_TEXT || cookie.contains('\n') {
890 return Err((FAILED, "a bad cookie"));
891 }
892 let mut uids: Vec<u32> = identities
893 .iter()
894 .take(MAX_IDENTITIES)
895 .filter(|(kind, _)| *kind == "unix-user")
896 .filter_map(|(_, details)| u32::try_from(details.get("uid")?).ok())
897 .collect();
898 let own = rustix::process::getuid().as_raw();
901 if let Some(at) = uids.iter().position(|uid| *uid == own) {
902 uids[..=at].rotate_right(1);
903 }
904 if uids.is_empty() {
905 return Err((FAILED, "no user the agent knows may answer"));
906 }
907 let begin = Begin {
908 call: call.clone(),
909 cookie: cookie.to_owned(),
910 shown: AuthRequest {
911 id,
912 action_id: cut(action_id, MAX_TEXT),
913 message: cut(message, MAX_TEXT),
914 icon_name: cut(icon_name, MAX_TEXT),
915 identities: Vec::new(),
916 state: AuthState::Waiting,
917 info: Vec::new(),
918 errors: Vec::new(),
919 },
920 };
921 Ok((begin, uids))
922}
923
924fn cut(text: &str, max: usize) -> String {
926 text[..text.floor_char_boundary(max)].to_owned()
927}
928
929fn subject(session: Option<String>) -> (&'static str, HashMap<&'static str, Variant<'static>>) {
932 match session {
933 Some(id) => (
934 "unix-session",
935 HashMap::from([("session-id", Variant::from(id))]),
936 ),
937 None => (
938 "unix-process",
939 HashMap::from([
940 ("pid", Variant::from(std::process::id())),
941 ("start-time", Variant::from(start_time().unwrap_or(0))),
942 ]),
943 ),
944 }
945}
946
947fn start_time() -> Option<u64> {
950 let stat = std::fs::read_to_string("/proc/self/stat").ok()?;
951 stat
953 .rsplit_once(')')?
954 .1
955 .split_whitespace()
956 .nth(19)?
957 .parse()
958 .ok()
959}
960
961async fn run(service: Rc<Service>, address: zbus::Address) {
965 let connection = match zbus::connection::Builder::address(address).build().await {
966 Ok(connection) => connection,
967 Err(error) => {
968 return tracing::info!(%error, "can't reach the system bus, so no polkit requests arrive");
969 }
970 };
971 let mut messages = MessageStream::from(&connection);
973 if let Err(error) = bus_call(&connection, "AddMatch", &owner_rule(AUTHORITY)).await {
974 return tracing::warn!(%error, "can't follow polkit on the system bus, so no requests arrive");
975 }
976 if let Some(state) = service.state.borrow_mut().as_mut() {
977 state.connection = Some(connection.clone());
978 }
979 register(&service, &connection).await;
980 loop {
981 let next = poll_fn(|cx| Pin::new(&mut messages).poll_next(cx)).await;
982 if !service.alive() {
983 return;
984 }
985 match next {
986 Some(Ok(message)) if message.header().message_type() == Kind::MethodCall => {
987 service.on_call(message);
988 }
989 Some(Ok(message)) => {
990 if let Some((name, owner)) = owner_changed(&message)
992 && name == AUTHORITY
993 {
994 service.drop_requests();
996 service.publish();
997 if !owner.is_empty() {
998 tracing::info!("polkit started again; registering the agent with it");
999 register(&service, &connection).await;
1000 }
1001 }
1002 }
1003 Some(Err(error)) => tracing::warn!(%error, "a bad message on the system bus"),
1004 None => break,
1005 }
1006 }
1007 tracing::warn!("the system bus closed, so no more polkit requests arrive");
1008 service.forget();
1009 service.publish();
1010}
1011
1012async fn register(service: &Rc<Service>, connection: &Connection) {
1015 let session = std::env::var("XDG_SESSION_ID")
1016 .ok()
1017 .filter(|id| !id.is_empty());
1018 let locale = service.shared.config.desktop_entries.locale.as_str();
1020 let body = (subject(session), locale, AGENT_PATH);
1021 let call = connection.call_method(
1022 Some(AUTHORITY),
1023 AUTHORITY_PATH,
1024 Some(AUTHORITY_INTERFACE),
1025 "RegisterAuthenticationAgent",
1026 &body,
1027 );
1028 let authority = match service.shared.timeout(CALL_TIMEOUT, call).await {
1029 Ok(reply) => reply.header().sender().map(|sender| sender.to_string()),
1030 Err(error) => return tracing::warn!(%error, "polkit refused the agent, so no requests arrive"),
1031 };
1032 tracing::info!("registered as the polkit agent");
1033 if let Some(state) = service.state.borrow_mut().as_mut() {
1034 state.authority = authority;
1035 }
1036}