Skip to main content

crabshell_services/
polkit.rs

1//! A polkit authentication agent, as Quickshell's `PolkitAgent`: when a
2//! program asks polkit for something only some users may do, polkit asks
3//! the shell, and a config shows the "authenticate to do X" dialog.
4//!
5//! The shell registers with polkit on the system bus the first time a
6//! config asks for the agent. zbus has no object server here, so polkit's
7//! calls are answered by hand on the main thread. Each try runs polkit's
8//! setuid helper, which asks PAM: its prompts go into the request's state
9//! and the config's answers into its input. Nothing polls: the shell
10//! wakes when polkit calls or the helper prints.
11
12mod 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";
43/// Where the agent answers polkit: any path of the shell's own.
44const AGENT_PATH: &str = "/org/crabshell/PolkitAgent";
45
46/// Where distributions keep polkit's helper, in the order tried: most of
47/// them, Fedora's and Debian's, older ones', and NixOS's setuid wrapper.
48pub(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
55/// The first of `helpers` that exists, else the first, so the error names
56/// where it was looked for.
57fn 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
64/// Where polkit 127 and later listen for agents, and systemd starts the
65/// helper as root for each connection, so the helper needn't be setuid.
66pub(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
74/// The most bytes kept of a string from polkit or its helper.
75const MAX_TEXT: usize = 4 * 1024;
76/// The most wrong answers to one request before polkit is told it failed.
77const MAX_TRIES: u32 = 3;
78/// The most identities kept of a request.
79const MAX_IDENTITIES: usize = 64;
80/// The most requests waiting behind the one answered.
81const MAX_QUEUED: usize = 8;
82/// How long a request waits for its users' names, as NSS may ask a
83/// server that doesn't answer.
84pub(crate) const USERS_LIMIT: Duration = Duration::from_secs(3);
85
86/// The most user lookups' threads alive at once. Past it a request
87/// fails rather than leave another thread stuck in a hung NSS.
88const MAX_LOOKUPS: usize = 4;
89
90/// A name a user lookup's thread found: the identity's place, and its
91/// name, or `None` for no such user.
92pub(crate) type Found = (usize, Option<String>);
93
94/// The most info and error lines a request keeps, the newest.
95const MAX_LINES: usize = 16;
96
97/// A request from polkit: a program asked to do `action_id`, and polkit
98/// wants a user to prove they may.
99#[derive(Clone, Debug, PartialEq)]
100pub struct AuthRequest {
101  /// Which request this is, so two alike still differ. polkit's cookie
102  /// stays in the agent.
103  id: u64,
104  /// What was asked for, such as `org.freedesktop.login1.reboot`.
105  pub action_id: String,
106  /// What to tell the user, in the shell's language, at most 4 KiB.
107  pub message: String,
108  /// A themed icon for the action, or empty.
109  pub icon_name: String,
110  /// The users who may answer, by name. The first is the one asked now;
111  /// [`PolkitAgent::pick_identity`] puts another first.
112  pub identities: Vec<String>,
113  /// Where the conversation is.
114  pub state: AuthState,
115  /// What PAM told the user this try, such as to touch a key, oldest
116  /// first. At most 16 lines of 4 KiB.
117  pub info: Vec<String>,
118  /// What PAM said went wrong this try, oldest first, kept as `info` is.
119  pub errors: Vec<String>,
120}
121
122/// Where a request's conversation is.
123#[derive(Clone, Debug, PartialEq)]
124pub enum AuthState {
125  /// polkit's helper is starting, or has only told the user something.
126  Waiting,
127  /// PAM asks `message`, such as `Password: `, for
128  /// [`PolkitAgent::respond`]. `visible` is whether the answer may show
129  /// as it is typed.
130  Asking {
131    /// The question, at most 4 KiB.
132    message: String,
133    /// `false` for a password.
134    visible: bool,
135  },
136  /// The answer is being checked.
137  Busy,
138  /// The answer was wrong. [`PolkitAgent::respond`] tries again; after
139  /// the third failure polkit is told, and the request goes.
140  Failed {
141    /// What PAM said, or a plain "Authentication failed".
142    message: String,
143  },
144}
145
146/// The shell's polkit agent, from `cx.polkit_agent()`. A clone is cheap
147/// and shares the one agent.
148#[derive(Clone)]
149pub struct PolkitAgent {
150  /// `None` when the shell provided no services.
151  service: Option<Rc<Service>>,
152  request: ReadSignal<Option<AuthRequest>>,
153}
154
155impl PolkitAgent {
156  /// The request being answered now, or `None`. One shows at a time; up
157  /// to 8 more wait their turn, and polkit is told any past that failed.
158  pub fn request(&self) -> ReadSignal<Option<AuthRequest>> {
159    self.request
160  }
161
162  /// Answers the request's question, as the user typed it. After a
163  /// failure, it tries again and answers the new try's first question.
164  /// At any other time, or with a line break in it, it is dropped. It is
165  /// never logged, and its bytes are zeroed once sent.
166  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  /// Gives up on the request, as the user's cancel button does, and tells
174  /// polkit so.
175  pub fn cancel(&self) {
176    if let Some(service) = &self.service {
177      service.finish(Some((CANCELLED, "the user cancelled")));
178    }
179  }
180
181  /// Asks `name`, one of the request's identities, instead: it moves to
182  /// the front, and the conversation starts again as that user. An
183  /// unknown name is logged.
184  pub fn pick_identity(&self, name: &str) {
185    if let Some(service) = &self.service {
186      service.pick(name);
187    }
188  }
189}
190
191/// `cx.polkit_agent()`.
192pub(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
210/// The polkit agent of one shell, started on first use.
211pub(crate) struct Service {
212  shared: Rc<Shared>,
213  state: RefCell<Option<State>>,
214  /// The number the next helper run and request get.
215  next: Cell<u64>,
216  /// The user lookups' threads still running, which a hung NSS can hold
217  /// for good, counted by the threads themselves.
218  lookups: Arc<AtomicUsize>,
219}
220
221/// Counts a lookup's thread down when it ends, even by a panic.
222struct 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  /// The system bus, once connected.
233  connection: Option<Connection>,
234  /// polkit's unique name, once it took the registration: the only
235  /// caller the agent answers.
236  authority: Option<String>,
237  current: Option<Current>,
238  /// Requests that came while one was answered, oldest first.
239  queue: VecDeque<Begin>,
240  /// Requests whose users are being named, oldest first.
241  resolving: Vec<Resolving>,
242}
243
244/// A request whose users are named on a thread of their own, since NSS
245/// may block. It goes on once they are, or once [`USERS_LIMIT`] passed.
246struct Resolving {
247  begin: Begin,
248  uids: Vec<u32>,
249  names: Vec<Option<String>>,
250  /// The thread's channel and the limit's timer, while it runs.
251  sources: Vec<RegistrationToken>,
252  done: bool,
253}
254
255/// Stops the helper and forgets the requests when the root goes. The
256/// agent's connection closes at the next message on it, or with the shell.
257struct StopOnDrop(Rc<Service>);
258
259impl Drop for StopOnDrop {
260  fn drop(&mut self) {
261    self.0.forget();
262  }
263}
264
265/// A `BeginAuthentication` call, kept until it is answered.
266struct Begin {
267  call: Message,
268  cookie: String,
269  shown: AuthRequest,
270}
271
272/// The request being answered.
273struct Current {
274  begin: Begin,
275  failures: u32,
276  helper: Option<Helper>,
277  /// An answer given after a failure, for the next try's first question.
278  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  /// The request, registering with polkit if this is the first ask.
309  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  /// Drops the connection and every request unanswered, as when the root
331  /// or the bus goes. Touches no signal, since the root may be going.
332  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  /// Drops every request unanswered, stopping the helper, as when polkit
340  /// goes and nobody could answer. Touches no signal.
341  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  /// Whether the request is still there: its owner, the root, isn't
361  /// disposed.
362  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  /// Runs `f` on the request being answered, if there is one.
371  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  /// Shows the request as it is now.
377  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  /// One method call from the bus.
391  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  /// polkit asks the user to authenticate. Its users are named first.
422  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  /// Names `uids` on a thread of their own, so NSS never holds up the
452  /// loop, which hears from it only until it is done or the limit passed.
453  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            // Refused once the request went on without it.
468            if sender.send((at, lookup(uid))).is_err() {
469              return;
470            }
471          }
472        });
473      // Its channel closed with it, which ends the lookup.
474      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  /// Request `id`'s identity `at` is named `name`.
506  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  /// Request `id`'s users are named, or the limit passed.
518  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  /// Moves the requests whose users are named on, in the order they
540  /// came: to be answered, to wait, or, with no user found, to polkit as
541  /// failed.
542  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  /// polkit takes back the request `cookie` names.
585  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  /// The config picks identity `name`.
619  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  /// Starts a try: polkit's helper, for the first identity.
637  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  /// What the helper of run `run` printed.
679  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        // A try after a failure answers its first question at once.
734        Some(secret) => self.send(secret),
735        None => self.publish(),
736      },
737    }
738  }
739
740  /// A wrong answer, or a helper that ended without saying: shows it, or
741  /// after the third tells polkit.
742  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  /// The config's answer.
766  fn respond(self: &Rc<Self>, secret: Secret) {
767    // A line break would end the line early, and the helper, in C, would
768    // read a NUL as the end.
769    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  /// Sends `secret` to the helper, which then checks it. It goes when
784  /// this returns.
785  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  /// Ends the request being answered and tells polkit: `None` for
804  /// authenticated, else the error's name and why. The next waiting
805  /// request starts.
806  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      // After a success it is telling polkit, so it is left to end.
817      helper.stop(&self.shared, error.is_some());
818    }
819    self.reply(&current.begin.call, error);
820    match self.with_current(|_| ()) {
821      Some(()) => self.run_helper(),
822      None => self.publish(),
823    }
824  }
825
826  /// Answers `call`: with an empty return for `None`, else with the error
827  /// and why.
828  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
857/// Whether `line` ends the try: `true` for a success, `false` for a
858/// failure.
859fn line_verdict(line: &Line) -> Option<bool> {
860  match line {
861    Line::Success => Some(true),
862    Line::Failure => Some(false),
863    _ => None,
864  }
865}
866
867/// `BeginAuthentication`'s arguments: the action, the message, the icon,
868/// details, the cookie and the identities.
869type 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
878/// The request `call` asks for, numbered `id`, with no identities yet,
879/// and the uids of the users who may answer, the session's first; or the
880/// error to answer.
881fn 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  // It is the helper's first line of input, so it can't hold another.
889  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  // The session's user is asked first: polkit may list root first, as for
899  // an admin group.
900  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
924/// `text`'s first `max` bytes at most, cut at a char boundary.
925fn cut(text: &str, max: usize) -> String {
926  text[..text.floor_char_boundary(max)].to_owned()
927}
928
929/// Who the agent answers for: this login session when `session` names
930/// one, as `XDG_SESSION_ID` does, else this process.
931fn 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
947/// When this process started, in clock ticks after boot, as polkit names
948/// a process: the 22nd field of `/proc/self/stat`.
949fn start_time() -> Option<u64> {
950  let stat = std::fs::read_to_string("/proc/self/stat").ok()?;
951  // Fields after the name in parentheses start at the 3rd.
952  stat
953    .rsplit_once(')')?
954    .1
955    .split_whitespace()
956    .nth(19)?
957    .parse()
958    .ok()
959}
960
961/// Joins the system bus at `address`, registers the agent with polkit,
962/// again whenever polkit starts again, and answers polkit's calls, until
963/// the bus closes or the request is disposed.
964async 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  // Made before polkit can call, so no call is missed.
972  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  if service.shared.alone.get() {
980    register(&service, &connection).await;
981  } else {
982    // polkit takes one agent per session, which the old shell of a
983    // reload holds until it exits.
984    let (weak, connection) = (Rc::downgrade(&service), connection.clone());
985    service.shared.when_alone(move || {
986      if let Some(service) = weak.upgrade() {
987        let shared = Rc::clone(&service.shared);
988        shared.spawn(async move {
989          if !register(&service, &connection).await {
990            register_again(&service, connection);
991          }
992        });
993      }
994    });
995  }
996  loop {
997    let next = poll_fn(|cx| Pin::new(&mut messages).poll_next(cx)).await;
998    if !service.alive() {
999      return;
1000    }
1001    match next {
1002      Some(Ok(message)) if message.header().message_type() == Kind::MethodCall => {
1003        service.on_call(message);
1004      }
1005      Some(Ok(message)) => {
1006        // The bus daemon sends this, so nobody else can fake it.
1007        if let Some((name, owner)) = owner_changed(&message)
1008          && name == AUTHORITY
1009        {
1010          // Its requests went with it.
1011          service.drop_requests();
1012          service.publish();
1013          if !owner.is_empty() {
1014            tracing::info!("polkit started again; registering the agent with it");
1015            register(&service, &connection).await;
1016          }
1017        }
1018      }
1019      Some(Err(error)) => tracing::warn!(%error, "a bad message on the system bus"),
1020      None => break,
1021    }
1022  }
1023  tracing::warn!("the system bus closed, so no more polkit requests arrive");
1024  service.forget();
1025  service.publish();
1026}
1027
1028/// How long after a refusal, just as the shell went alone, the agent
1029/// registers once more.
1030const RETRY_AFTER: Duration = Duration::from_millis(500);
1031
1032/// Registers the agent once more [`RETRY_AFTER`] from now, since polkit
1033/// may refuse it while it hasn't yet seen the old shell of a reload go.
1034fn register_again(service: &Rc<Service>, connection: Connection) {
1035  let Some(event_loop) = service.shared.event_loop() else {
1036    return;
1037  };
1038  tracing::info!("trying the polkit agent once more, as the old shell may just have gone");
1039  let (weak, mut connection) = (Rc::downgrade(service), Some(connection));
1040  let tick = Box::new(move || {
1041    if let (Some(service), Some(connection)) = (weak.upgrade(), connection.take()) {
1042      let shared = Rc::clone(&service.shared);
1043      shared.spawn(async move {
1044        register(&service, &connection).await;
1045      });
1046    }
1047    TimeoutAction::Drop
1048  });
1049  event_loop.insert_timer(Instant::now() + RETRY_AFTER, tick);
1050}
1051
1052/// Registers the agent with the polkit on `connection`, which takes its
1053/// calls only from the unique name that answered. A refusal is logged.
1054/// Returns whether polkit took it.
1055async fn register(service: &Rc<Service>, connection: &Connection) -> bool {
1056  let session = std::env::var("XDG_SESSION_ID")
1057    .ok()
1058    .filter(|id| !id.is_empty());
1059  // The locale desktop entries are read in, so polkit's message matches.
1060  let locale = service.shared.config.desktop_entries.locale.as_str();
1061  let body = (subject(session), locale, AGENT_PATH);
1062  let call = connection.call_method(
1063    Some(AUTHORITY),
1064    AUTHORITY_PATH,
1065    Some(AUTHORITY_INTERFACE),
1066    "RegisterAuthenticationAgent",
1067    &body,
1068  );
1069  let authority = match service.shared.timeout(CALL_TIMEOUT, call).await {
1070    Ok(reply) => reply.header().sender().map(|sender| sender.to_string()),
1071    Err(error) => {
1072      tracing::warn!(%error, "polkit refused the agent, so no requests arrive");
1073      return false;
1074    }
1075  };
1076  tracing::info!("registered as the polkit agent");
1077  if let Some(state) = service.state.borrow_mut().as_mut() {
1078    state.authority = authority;
1079  }
1080  true
1081}