fix: Ubuntu bugs

This commit is contained in:
Willem Vanhulle committed 2026-10-25 12:03:39 +01:00
1 parent 3acc577aac
commit 1d098dc931
12 files changed
+267 -73

No files matched your search

+4 -1
View File
@@ -117,5 +117,8 @@ the default `/usr`.
## Uninstall ## Uninstall
`bootvine uninstall` disables and removes everything `bootvine install` put in `bootvine uninstall` disables and removes everything `bootvine install` put in
place, with the same `--prefix` and `--destdir`. On NixOS, remove place, with the same `--prefix` and `--destdir`. The current initramfs keeps
its copy of bootvine until you rebuild it, so with an initrd hook installed it
prints the command for that: `sudo dracut --force`, or for mkinitcpio, removing
`sd-bootvine` from `HOOKS` and running `sudo mkinitcpio -P`. On NixOS, remove
`services.bootvine.enable` and rebuild. `services.bootvine.enable` and rebuild.
+11 -5
View File
@@ -226,13 +226,19 @@ impl BootState {
self.units.get(root).is_some_and(|root| !root.is_pending()) self.units.get(root).is_some_and(|root| !root.is_pending())
} }
#[must_use]
pub fn started_display_manager(&self) -> Option<&str> {
self.handoff_unit.as_deref().filter(|unit| {
self.units
.get(*unit)
.and_then(|handoff| handoff.activity.state)
.is_some_and(|state| state != ActiveState::Inactive)
})
}
#[must_use] #[must_use]
pub fn display_manager_started(&self) -> bool { pub fn display_manager_started(&self) -> bool {
self.handoff_unit self.started_display_manager().is_some()
.as_deref()
.and_then(|unit| self.units.get(unit))
.and_then(|handoff| handoff.activity.state)
.is_some_and(|state| state != ActiveState::Inactive)
} }
#[must_use] #[must_use]
+26 -2
View File
@@ -5,7 +5,7 @@ use super::{
screen_render_fixtures::{boot_in_progress, render, render_prompted, screen_lines}, screen_render_fixtures::{boot_in_progress, render, render_prompted, screen_lines},
}; };
use crate::{ use crate::{
boot_model::{BootState, JobResult, Phase}, boot_model::{ActiveState, Activity, BootState, HANDOFF_UNIT, JobResult, Phase},
demo_script::boot_test_fixtures::{MS, queue_unit, queued_boot, running, waiting}, demo_script::boot_test_fixtures::{MS, queue_unit, queued_boot, running, waiting},
screen_settings::color_scheme::Colors, screen_settings::color_scheme::Colors,
}; };
@@ -278,7 +278,7 @@ fn finished_stages_collapse_into_a_summary_rule() {
} }
#[test] #[test]
fn completion_announces_the_handover() { fn completion_without_a_display_manager_hands_back_the_console() {
let mut state = queued_boot( let mut state = queued_boot(
Phase::Host, Phase::Host,
Duration::ZERO, Duration::ZERO,
@@ -286,6 +286,30 @@ fn completion_announces_the_handover() {
); );
state.finish_job(1, JobResult::Done, 9000 * MS); state.finish_job(1, JobResult::Done, 9000 * MS);
let lines = render(&state, 9500 * MS, 110, 24); let lines = render(&state, 9500 * MS, 110, 24);
assert!(
lines[1].starts_with("└─ ■ Boot finished in 9.5s · handing over to the console"),
"{}",
lines.join("\n")
);
}
#[test]
fn completion_names_the_display_manager_that_started() {
let mut state = queued_boot(
Phase::Host,
Duration::ZERO,
[waiting("graphical.target", &[])],
);
queue_unit(&mut state, 2, waiting(HANDOFF_UNIT, &[]), 500 * MS);
state.update_activity(
HANDOFF_UNIT,
Activity {
state: Some(ActiveState::Active),
..Activity::default()
},
);
state.finish_job(1, JobResult::Done, 9000 * MS);
let lines = render(&state, 9500 * MS, 110, 24);
assert!( assert!(
lines[1] lines[1]
.starts_with("└─ ■ Boot finished in 9.5s · handing over to display-manager.service"), .starts_with("└─ ■ Boot finished in 9.5s · handing over to display-manager.service"),
+1 -3
View File
@@ -48,9 +48,7 @@ impl Stages<'_> {
took: self.now.saturating_sub(self.state.origin), took: self.now.saturating_sub(self.state.origin),
handed_to: self handed_to: self
.state .state
.handoff_unit .started_display_manager()
.as_deref()
.or(self.state.root.unit())
.unwrap_or("the console"), .unwrap_or("the console"),
}) })
} }
+1
View File
@@ -1,4 +1,5 @@
pub mod ask_password; pub mod ask_password;
pub mod console_palette;
pub mod console_takeover; pub mod console_takeover;
pub mod live_desk; pub mod live_desk;
pub mod passphrase_input; pub mod passphrase_input;
+94
View File
@@ -0,0 +1,94 @@
use ratatui::{
buffer::Buffer,
style::{Color, Modifier},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConsolePalette {
Terminal,
SixteenColorVt,
EightColorVt,
}
impl ConsolePalette {
#[must_use]
pub fn of_virtual_terminal(font_uses_high_glyphs: bool) -> Self {
if font_uses_high_glyphs {
Self::EightColorVt
} else {
Self::SixteenColorVt
}
}
pub fn fit_frame(self, frame: &mut Buffer) {
if self == Self::Terminal {
return;
}
frame.content.iter_mut().for_each(|cell| {
cell.modifier.remove(Modifier::BOLD);
if self == Self::EightColorVt {
cell.fg = without_brightness(cell.fg);
cell.bg = without_brightness(cell.bg);
}
});
}
}
fn without_brightness(color: Color) -> Color {
match color {
Color::DarkGray | Color::White => Color::Gray,
Color::LightRed => Color::Red,
Color::LightGreen => Color::Green,
Color::LightYellow => Color::Yellow,
Color::LightBlue => Color::Blue,
Color::LightMagenta => Color::Magenta,
Color::LightCyan => Color::Cyan,
Color::Indexed(bright @ 8..=15) => Color::Indexed(bright - 8),
other => other,
}
}
#[cfg(test)]
mod tests {
use ratatui::{layout::Rect, style::Style};
use super::*;
fn frame_painted(style: Style) -> Buffer {
let mut frame = Buffer::empty(Rect::new(0, 0, 1, 1));
frame.set_style(frame.area, style);
frame
}
#[test]
fn eight_color_consoles_keep_dark_gray_visible() {
let mut frame = frame_painted(Style::new().fg(Color::DarkGray).bold());
ConsolePalette::EightColorVt.fit_frame(&mut frame);
assert_eq!(frame.content[0].fg, Color::Gray);
assert!(!frame.content[0].modifier.contains(Modifier::BOLD));
}
#[test]
fn eight_color_consoles_fold_bright_colors_onto_normal_ones() {
let mut frame = frame_painted(Style::new().fg(Color::LightYellow).bg(Color::Indexed(12)));
ConsolePalette::EightColorVt.fit_frame(&mut frame);
assert_eq!(frame.content[0].fg, Color::Yellow);
assert_eq!(frame.content[0].bg, Color::Indexed(4));
}
#[test]
fn sixteen_color_consoles_only_lose_bold() {
let mut frame = frame_painted(Style::new().fg(Color::DarkGray).bold());
ConsolePalette::SixteenColorVt.fit_frame(&mut frame);
assert_eq!(frame.content[0].fg, Color::DarkGray);
assert!(!frame.content[0].modifier.contains(Modifier::BOLD));
}
#[test]
fn terminals_keep_the_frame_as_drawn() {
let mut frame = frame_painted(Style::new().fg(Color::DarkGray).bold());
ConsolePalette::Terminal.fit_frame(&mut frame);
assert_eq!(frame.content[0].fg, Color::DarkGray);
assert!(frame.content[0].modifier.contains(Modifier::BOLD));
}
}
+47 -24
View File
@@ -7,7 +7,10 @@ use rustix::{
termios::ttyname, termios::ttyname,
}; };
use crate::{console_session::ask_password, screen_settings::font_glyphs::Glyphs}; use crate::{
console_session::{ask_password, console_palette::ConsolePalette},
screen_settings::font_glyphs::Glyphs,
};
const GIO_UNIMAP: Opcode = 0x4B66; const GIO_UNIMAP: Opcode = 0x4B66;
const VT_GETSTATE: Opcode = 0x5603; const VT_GETSTATE: Opcode = 0x5603;
@@ -15,12 +18,14 @@ const VT_ACTIVATE: Opcode = 0x5606;
const VIRTUAL_TERMINAL_PREFIX: &str = "/dev/tty"; const VIRTUAL_TERMINAL_PREFIX: &str = "/dev/tty";
const KERNEL_PRINTK: &str = "/proc/sys/kernel/printk"; const KERNEL_PRINTK: &str = "/proc/sys/kernel/printk";
const ALERTS_ONLY: &str = "1"; const ALERTS_ONLY: &str = "1";
const HIGHEST_LOW_GLYPH: u16 = 255;
pub struct Console { pub struct Console {
quiet_kernel: Option<QuietKernelConsole>, quiet_kernel: Option<QuietKernelConsole>,
foreground: Option<ForegroundVt>, foreground: Option<ForegroundVt>,
for_system: bool, for_system: bool,
own_vt: Option<u16>,
pub glyphs: Glyphs, pub glyphs: Glyphs,
pub bold_is_brightness: bool, pub palette: ConsolePalette,
} }
impl Console { impl Console {
@@ -29,16 +34,17 @@ impl Console {
if prompt_elsewhere { if prompt_elsewhere {
eprintln!("bootvine: a password prompt is already showing, staying behind it"); eprintln!("bootvine: a password prompt is already showing, staying behind it");
} }
let own_vt = vt_of_stdin();
let font = loaded_font();
Self { Self {
quiet_kernel: for_system.then(QuietKernelConsole::take).flatten(), quiet_kernel: for_system.then(QuietKernelConsole::take).flatten(),
foreground: if prompt_elsewhere { foreground: own_vt
None .filter(|_| !prompt_elsewhere)
} else { .and_then(ForegroundVt::take),
ForegroundVt::take()
},
for_system, for_system,
glyphs: font_glyphs(), own_vt,
bold_is_brightness: own_vt().is_some(), glyphs: font_glyphs(font.as_ref()),
palette: console_palette(own_vt, font.as_ref()),
} }
} }
@@ -51,7 +57,7 @@ impl Console {
if !self.for_system || self.foreground.is_some() || ask_password::requested() { if !self.for_system || self.foreground.is_some() || ask_password::requested() {
return false; return false;
} }
self.foreground = ForegroundVt::take(); self.foreground = self.own_vt.and_then(ForegroundVt::take);
if self.foreground.is_some() { if self.foreground.is_some() {
eprintln!("bootvine: password prompt answered, taking the console back"); eprintln!("bootvine: password prompt answered, taking the console back");
} }
@@ -64,9 +70,12 @@ impl Console {
.as_mut() .as_mut()
.is_some_and(QuietKernelConsole::keep_quiet); .is_some_and(QuietKernelConsole::keep_quiet);
let terminal_was_taken = self.foreground.as_ref().is_some_and(ForegroundVt::insist); let terminal_was_taken = self.foreground.as_ref().is_some_and(ForegroundVt::insist);
let glyphs = font_glyphs(); let font = loaded_font();
let font_changed = glyphs != self.glyphs; let glyphs = font_glyphs(font.as_ref());
let palette = console_palette(self.own_vt, font.as_ref());
let font_changed = glyphs != self.glyphs || palette != self.palette;
self.glyphs = glyphs; self.glyphs = glyphs;
self.palette = palette;
kernel_got_loud || terminal_was_taken || font_changed kernel_got_loud || terminal_was_taken || font_changed
} }
@@ -120,12 +129,24 @@ impl QuietKernelConsole {
} }
} }
fn font_glyphs() -> Glyphs { struct LoadedFont {
font_characters().map_or_else(Glyphs::default, |characters| { characters: HashSet<char>,
Glyphs::fitting(|symbol| symbol.is_ascii() || characters.contains(&symbol)) uses_high_glyphs: bool,
}
fn font_glyphs(font: Option<&LoadedFont>) -> Glyphs {
font.map_or_else(Glyphs::default, |font| {
Glyphs::fitting(|symbol| symbol.is_ascii() || font.characters.contains(&symbol))
}) })
} }
fn console_palette(own_vt: Option<u16>, font: Option<&LoadedFont>) -> ConsolePalette {
if own_vt.is_none() {
return ConsolePalette::Terminal;
}
ConsolePalette::of_virtual_terminal(font.is_some_and(|font| font.uses_high_glyphs))
}
impl Drop for QuietKernelConsole { impl Drop for QuietKernelConsole {
fn drop(&mut self) { fn drop(&mut self) {
let _ = fs::write(KERNEL_PRINTK, &self.previous_level); let _ = fs::write(KERNEL_PRINTK, &self.previous_level);
@@ -136,7 +157,7 @@ impl Drop for QuietKernelConsole {
#[derive(Clone, Copy, Default)] #[derive(Clone, Copy, Default)]
struct UnicodePair { struct UnicodePair {
unicode: u16, unicode: u16,
_font_position: u16, font_position: u16,
} }
#[repr(C)] #[repr(C)]
@@ -149,7 +170,7 @@ fn read_unicode_map(map: &mut UnicodeMap) -> Result<(), Errno> {
unsafe { ioctl(stdin(), Updater::<GIO_UNIMAP, UnicodeMap>::new(map)) } unsafe { ioctl(stdin(), Updater::<GIO_UNIMAP, UnicodeMap>::new(map)) }
} }
fn font_characters() -> Option<HashSet<char>> { fn loaded_font() -> Option<LoadedFont> {
let mut probe = UnicodeMap { let mut probe = UnicodeMap {
count: 0, count: 0,
pairs: ptr::null_mut(), pairs: ptr::null_mut(),
@@ -164,13 +185,16 @@ fn font_characters() -> Option<HashSet<char>> {
pairs: pairs.as_mut_ptr(), pairs: pairs.as_mut_ptr(),
}; };
read_unicode_map(&mut map).ok()?; read_unicode_map(&mut map).ok()?;
Some( let mapped = &pairs[..usize::from(map.count).min(pairs.len())];
pairs Some(LoadedFont {
characters: mapped
.iter() .iter()
.take(usize::from(map.count))
.filter_map(|pair| char::from_u32(u32::from(pair.unicode))) .filter_map(|pair| char::from_u32(u32::from(pair.unicode)))
.collect(), .collect(),
) uses_high_glyphs: mapped
.iter()
.any(|pair| pair.font_position > HIGHEST_LOW_GLYPH),
})
} }
#[repr(C)] #[repr(C)]
@@ -198,7 +222,7 @@ fn active_vt() -> Option<u16> {
Some(state.active) Some(state.active)
} }
fn own_vt() -> Option<u16> { fn vt_of_stdin() -> Option<u16> {
let name = ttyname(stdin(), Vec::new()).ok()?; let name = ttyname(stdin(), Vec::new()).ok()?;
name.to_str() name.to_str()
.ok()? .ok()?
@@ -209,8 +233,7 @@ fn own_vt() -> Option<u16> {
} }
impl ForegroundVt { impl ForegroundVt {
fn take() -> Option<Self> { fn take(own: u16) -> Option<Self> {
let own = own_vt()?;
let previous = active_vt()?; let previous = active_vt()?;
if previous != own { if previous != own {
activate(own).ok()?; activate(own).ok()?;
+4 -4
View File
@@ -8,6 +8,7 @@ use crate::{
boot_view::PasswordPrompt, boot_view::PasswordPrompt,
console_session::{ console_session::{
ask_password::{PasswordEntry, RequestWatch}, ask_password::{PasswordEntry, RequestWatch},
console_palette::ConsolePalette,
console_takeover::Console, console_takeover::Console,
passphrase_input::asks_to_quit, passphrase_input::asks_to_quit,
stream_sources::{ stream_sources::{
@@ -19,7 +20,6 @@ use crate::{
screen_settings::font_glyphs::Glyphs, screen_settings::font_glyphs::Glyphs,
}; };
const CONSOLE_UPKEEP_INTERVAL: Duration = Duration::from_secs(1);
const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(5); const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(5);
pub struct LiveDesk { pub struct LiveDesk {
@@ -58,8 +58,8 @@ impl ConsoleDesk for LiveDesk {
&self.console.glyphs &self.console.glyphs
} }
fn drops_bold(&self) -> bool { fn palette(&self) -> ConsolePalette {
self.console.bold_is_brightness self.console.palette
} }
fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> { fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> {
@@ -131,7 +131,7 @@ pub fn prompt_check_inputs() -> impl Stream<Item = ScreenInput> {
} }
pub fn console_upkeep_inputs() -> impl Stream<Item = ScreenInput> { pub fn console_upkeep_inputs() -> impl Stream<Item = ScreenInput> {
periodic_inputs(CONSOLE_UPKEEP_INTERVAL, || ScreenInput::ConsoleUpkeep) periodic_inputs(BACKGROUND_CHECK_INTERVAL, || ScreenInput::ConsoleUpkeep)
} }
pub fn full_repaint_inputs() -> impl Stream<Item = ScreenInput> { pub fn full_repaint_inputs() -> impl Stream<Item = ScreenInput> {
+5 -14
View File
@@ -6,12 +6,12 @@ use ratatui::{
Terminal, Terminal,
backend::Backend, backend::Backend,
buffer::{Buffer, CellDiffOption}, buffer::{Buffer, CellDiffOption},
style::Modifier,
}; };
use crate::{ use crate::{
boot_model::{BootChange, BootProjection, BootState, boot_origin::BootOrigin}, boot_model::{BootChange, BootProjection, BootState, boot_origin::BootOrigin},
boot_view::{BootView, PasswordPrompt, project_boot}, boot_view::{BootView, PasswordPrompt, project_boot},
console_session::console_palette::ConsolePalette,
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs}, screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
systemd_link::{link_error::Error, monotonic_clock::monotonic_now}, systemd_link::{link_error::Error, monotonic_clock::monotonic_now},
}; };
@@ -39,7 +39,7 @@ pub enum WatchEnding {
pub trait ConsoleDesk { pub trait ConsoleDesk {
fn glyphs(&self) -> &Glyphs; fn glyphs(&self) -> &Glyphs;
fn drops_bold(&self) -> bool; fn palette(&self) -> ConsolePalette;
fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>>; fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>>;
fn press_key(&mut self, event: &Event, now: Duration) -> ControlFlow<WatchEnding>; fn press_key(&mut self, event: &Event, now: Duration) -> ControlFlow<WatchEnding>;
fn frame_passed(&mut self, state: &mut BootState, now: Duration) -> ControlFlow<WatchEnding>; fn frame_passed(&mut self, state: &mut BootState, now: Duration) -> ControlFlow<WatchEnding>;
@@ -215,9 +215,7 @@ impl<Desk: ConsoleDesk> WatchScreen<Desk> {
}, },
canvas.area(), canvas.area(),
); );
if self.desk.drops_bold() { self.desk.palette().fit_frame(canvas.buffer_mut());
drop_bold(canvas.buffer_mut());
}
})?; })?;
if self.full_repaint_due { if self.full_repaint_due {
let painted = completed.buffer.clone(); let painted = completed.buffer.clone();
@@ -259,13 +257,6 @@ fn overwrite_every_cell<B: Backend>(backend: &mut B, frame: &Buffer) -> Result<(
backend.flush() backend.flush()
} }
fn drop_bold(frame: &mut Buffer) {
frame
.content
.iter_mut()
.for_each(|cell| cell.modifier.remove(Modifier::BOLD));
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -285,8 +276,8 @@ mod tests {
&self.glyphs &self.glyphs
} }
fn drops_bold(&self) -> bool { fn palette(&self) -> ConsolePalette {
false ConsolePalette::Terminal
} }
fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> { fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> {
+3 -2
View File
@@ -17,6 +17,7 @@ use crate::{
}, },
boot_view::PasswordPrompt, boot_view::PasswordPrompt,
console_session::{ console_session::{
console_palette::ConsolePalette,
passphrase_input, passphrase_input,
stream_sources::{frame_inputs, key_inputs}, stream_sources::{frame_inputs, key_inputs},
watch_screen::{ConsoleDesk, WatchEnding, WatchScreen, watch_until_ending}, watch_screen::{ConsoleDesk, WatchEnding, WatchScreen, watch_until_ending},
@@ -328,8 +329,8 @@ impl ConsoleDesk for DemoDesk {
&self.glyphs &self.glyphs
} }
fn drops_bold(&self) -> bool { fn palette(&self) -> ConsolePalette {
false ConsolePalette::Terminal
} }
fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>> { fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>> {
+27
View File
@@ -275,11 +275,35 @@ pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> {
Ok(()) Ok(())
} }
fn print_initramfs_removal_hint(initrd: InitrdGenerator) {
match initrd {
InitrdGenerator::None => {}
InitrdGenerator::Dracut => {
println!("rebuild the initramfs without bootvine: sudo dracut --force");
}
InitrdGenerator::Mkinitcpio => println!(
"remove sd-bootvine from HOOKS in /etc/mkinitcpio.conf, then run: sudo mkinitcpio -P"
),
}
}
fn installed_initrd_hooks(target: &InstallTarget) -> Vec<InitrdGenerator> {
[InitrdGenerator::Dracut, InitrdGenerator::Mkinitcpio]
.into_iter()
.filter(|generator| {
initrd_hook_files(*generator)
.iter()
.any(|file| target.staged(&file.destination).exists())
})
.collect()
}
pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> { pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> {
let target = &options.target; let target = &options.target;
if target.needs_sudo() { if target.needs_sudo() {
return rerun_with_sudo(); return rerun_with_sudo();
} }
let removed_initrd_hooks = installed_initrd_hooks(target);
if target.changes_live_system() { if target.changes_live_system() {
let installed_units: Vec<&str> = unit_names() let installed_units: Vec<&str> = unit_names()
.filter(|unit| target.unit_path(unit).exists()) .filter(|unit| target.unit_path(unit).exists())
@@ -304,6 +328,9 @@ pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> {
} }
if target.changes_live_system() { if target.changes_live_system() {
systemctl(["daemon-reload"])?; systemctl(["daemon-reload"])?;
removed_initrd_hooks
.into_iter()
.for_each(print_initramfs_removal_hint);
} }
Ok(()) Ok(())
} }
+44 -18
View File
@@ -1,7 +1,7 @@
use std::{ use std::{
future::ready, future::ready,
io, iter, mem, io, iter, mem,
os::fd::{AsRawFd, RawFd}, os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd},
time::Duration, time::Duration,
}; };
@@ -11,6 +11,7 @@ use dbus::{
channel::{BusType, Channel}, channel::{BusType, Channel},
}; };
use futures::{StreamExt, stream}; use futures::{StreamExt, stream};
use rustix::event::{PollFd, PollFlags, Timespec, poll};
use tokio::{io::unix::AsyncFd, time::timeout}; use tokio::{io::unix::AsyncFd, time::timeout};
use crate::{ use crate::{
@@ -185,10 +186,34 @@ impl Session {
pub fn boot_in_progress(&self) -> Result<bool, Error> { pub fn boot_in_progress(&self) -> Result<bool, Error> {
read_boot_in_progress(&self.blocking_call(boot_in_progress_call()?)?) read_boot_in_progress(&self.blocking_call(boot_in_progress_call()?)?)
} }
fn send(&self, call: Message) -> Result<u32, Error> {
let serial = self.channel.send(call).map_err(|()| Error::Disconnected)?;
self.channel.flush();
Ok(serial)
}
fn socket_has_unread_bytes(&self) -> bool {
let mut watched = [PollFd::new(self, PollFlags::IN)];
poll(&mut watched, Some(&Timespec::default())).is_ok_and(|ready| ready > 0)
}
fn read_one_chunk(&self) -> Result<(), Error> {
let still_connected =
self.channel.read_write(Some(Duration::ZERO)).is_ok() && self.channel.is_connected();
still_connected.then_some(()).ok_or(Error::Disconnected)
}
fn arrived_messages(&self) -> Result<Vec<Message>, Error> {
iter::repeat_with(|| self.read_one_chunk())
.find(|outcome| outcome.is_err() || !self.socket_has_unread_bytes())
.unwrap_or(Ok(()))?;
Ok(iter::from_fn(|| self.channel.pop_message()).collect())
}
} }
pub struct BusConnection { pub struct BusConnection {
readiness: AsyncFd<Session>, session: AsyncFd<Session>,
early_signals: Vec<Signal>, early_signals: Vec<Signal>,
} }
@@ -202,24 +227,23 @@ fn into_results(batch: Result<Vec<Message>, Error>) -> Vec<Result<Message, Error
impl BusConnection { impl BusConnection {
pub fn register(session: Session) -> io::Result<Self> { pub fn register(session: Session) -> io::Result<Self> {
Ok(Self { Ok(Self {
readiness: readable_source(session)?, session: readable_source(session)?,
early_signals: Vec::new(), early_signals: Vec::new(),
}) })
} }
#[must_use] #[must_use]
pub fn peer_to_peer(&self) -> bool { pub fn peer_to_peer(&self) -> bool {
self.readiness.get_ref().peer_to_peer self.session.get_ref().peer_to_peer
} }
fn drain_replies(&mut self) -> Result<Vec<Message>, Error> { fn drain_replies(&mut self) -> Result<Vec<Message>, Error> {
let channel = &self.readiness.get_mut().channel; let (signals, replies): (Vec<Message>, Vec<Message>) = self
if channel.read_write(Some(Duration::ZERO)).is_err() || !channel.is_connected() { .session
return Err(Error::Disconnected); .get_ref()
} .arrived_messages()?
let (signals, replies): (Vec<Message>, Vec<Message>) = .into_iter()
iter::from_fn(|| channel.pop_message()) .partition(|message| message.msg_type() == MessageType::Signal);
.partition(|message| message.msg_type() == MessageType::Signal);
self.early_signals self.early_signals
.extend(signals.iter().filter_map(parse_signal)); .extend(signals.iter().filter_map(parse_signal));
Ok(replies) Ok(replies)
@@ -230,7 +254,7 @@ impl BusConnection {
if !drained.is_empty() { if !drained.is_empty() {
return Ok(drained); return Ok(drained);
} }
self.readiness.readable_mut().await?.clear_ready(); self.session.readable_mut().await?.clear_ready();
self.drain_replies() self.drain_replies()
} }
@@ -256,11 +280,7 @@ impl BusConnection {
} }
async fn call(&mut self, call: Message) -> Result<Message, Error> { async fn call(&mut self, call: Message) -> Result<Message, Error> {
let channel = &self.readiness.get_ref().channel; let serial = self.session.get_ref().send(call)?;
let Ok(serial) = channel.send(call) else {
return Err(Error::Disconnected);
};
channel.flush();
let Ok(reply) = timeout(CALL_TIMEOUT, self.reply_to(serial)).await else { let Ok(reply) = timeout(CALL_TIMEOUT, self.reply_to(serial)).await else {
return Err(Error::CallTimedOut); return Err(Error::CallTimedOut);
}; };
@@ -327,7 +347,7 @@ impl BusConnection {
pub async fn receive_signals(&mut self, patience: Duration) -> Result<Vec<Signal>, Error> { pub async fn receive_signals(&mut self, patience: Duration) -> Result<Vec<Signal>, Error> {
if self.early_signals.is_empty() if self.early_signals.is_empty()
&& let Ok(Ok(mut guard)) = timeout(patience, self.readiness.readable_mut()).await && let Ok(Ok(mut guard)) = timeout(patience, self.session.readable_mut()).await
{ {
guard.clear_ready(); guard.clear_ready();
} }
@@ -368,6 +388,12 @@ impl AsRawFd for Session {
} }
} }
impl AsFd for Session {
fn as_fd(&self) -> BorrowedFd<'_> {
unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
}
}
fn send_authentication_carrier(channel: &Channel) -> Result<(), Error> { fn send_authentication_carrier(channel: &Channel) -> Result<(), Error> {
let Ok(mut ping) = Message::new_method_call(DESTINATION, MANAGER_PATH, PEER_INTERFACE, "Ping") let Ok(mut ping) = Message::new_method_call(DESTINATION, MANAGER_PATH, PEER_INTERFACE, "Ping")
else { else {