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
`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.
+11 -5
View File
@@ -226,13 +226,19 @@ impl BootState {
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]
pub fn display_manager_started(&self) -> bool {
self.handoff_unit
.as_deref()
.and_then(|unit| self.units.get(unit))
.and_then(|handoff| handoff.activity.state)
.is_some_and(|state| state != ActiveState::Inactive)
self.started_display_manager().is_some()
}
#[must_use]
+26 -2
View File
@@ -5,7 +5,7 @@ use super::{
screen_render_fixtures::{boot_in_progress, render, render_prompted, screen_lines},
};
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},
screen_settings::color_scheme::Colors,
};
@@ -278,7 +278,7 @@ fn finished_stages_collapse_into_a_summary_rule() {
}
#[test]
fn completion_announces_the_handover() {
fn completion_without_a_display_manager_hands_back_the_console() {
let mut state = queued_boot(
Phase::Host,
Duration::ZERO,
@@ -286,6 +286,30 @@ fn completion_announces_the_handover() {
);
state.finish_job(1, JobResult::Done, 9000 * MS);
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!(
lines[1]
.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),
handed_to: self
.state
.handoff_unit
.as_deref()
.or(self.state.root.unit())
.started_display_manager()
.unwrap_or("the console"),
})
}
+1
View File
@@ -1,4 +1,5 @@
pub mod ask_password;
pub mod console_palette;
pub mod console_takeover;
pub mod live_desk;
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,
};
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 VT_GETSTATE: Opcode = 0x5603;
@@ -15,12 +18,14 @@ const VT_ACTIVATE: Opcode = 0x5606;
const VIRTUAL_TERMINAL_PREFIX: &str = "/dev/tty";
const KERNEL_PRINTK: &str = "/proc/sys/kernel/printk";
const ALERTS_ONLY: &str = "1";
const HIGHEST_LOW_GLYPH: u16 = 255;
pub struct Console {
quiet_kernel: Option<QuietKernelConsole>,
foreground: Option<ForegroundVt>,
for_system: bool,
own_vt: Option<u16>,
pub glyphs: Glyphs,
pub bold_is_brightness: bool,
pub palette: ConsolePalette,
}
impl Console {
@@ -29,16 +34,17 @@ impl Console {
if prompt_elsewhere {
eprintln!("bootvine: a password prompt is already showing, staying behind it");
}
let own_vt = vt_of_stdin();
let font = loaded_font();
Self {
quiet_kernel: for_system.then(QuietKernelConsole::take).flatten(),
foreground: if prompt_elsewhere {
None
} else {
ForegroundVt::take()
},
foreground: own_vt
.filter(|_| !prompt_elsewhere)
.and_then(ForegroundVt::take),
for_system,
glyphs: font_glyphs(),
bold_is_brightness: own_vt().is_some(),
own_vt,
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() {
return false;
}
self.foreground = ForegroundVt::take();
self.foreground = self.own_vt.and_then(ForegroundVt::take);
if self.foreground.is_some() {
eprintln!("bootvine: password prompt answered, taking the console back");
}
@@ -64,9 +70,12 @@ impl Console {
.as_mut()
.is_some_and(QuietKernelConsole::keep_quiet);
let terminal_was_taken = self.foreground.as_ref().is_some_and(ForegroundVt::insist);
let glyphs = font_glyphs();
let font_changed = glyphs != self.glyphs;
let font = loaded_font();
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.palette = palette;
kernel_got_loud || terminal_was_taken || font_changed
}
@@ -120,12 +129,24 @@ impl QuietKernelConsole {
}
}
fn font_glyphs() -> Glyphs {
font_characters().map_or_else(Glyphs::default, |characters| {
Glyphs::fitting(|symbol| symbol.is_ascii() || characters.contains(&symbol))
struct LoadedFont {
characters: HashSet<char>,
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 {
fn drop(&mut self) {
let _ = fs::write(KERNEL_PRINTK, &self.previous_level);
@@ -136,7 +157,7 @@ impl Drop for QuietKernelConsole {
#[derive(Clone, Copy, Default)]
struct UnicodePair {
unicode: u16,
_font_position: u16,
font_position: u16,
}
#[repr(C)]
@@ -149,7 +170,7 @@ fn read_unicode_map(map: &mut UnicodeMap) -> Result<(), Errno> {
unsafe { ioctl(stdin(), Updater::<GIO_UNIMAP, UnicodeMap>::new(map)) }
}
fn font_characters() -> Option<HashSet<char>> {
fn loaded_font() -> Option<LoadedFont> {
let mut probe = UnicodeMap {
count: 0,
pairs: ptr::null_mut(),
@@ -164,13 +185,16 @@ fn font_characters() -> Option<HashSet<char>> {
pairs: pairs.as_mut_ptr(),
};
read_unicode_map(&mut map).ok()?;
Some(
pairs
let mapped = &pairs[..usize::from(map.count).min(pairs.len())];
Some(LoadedFont {
characters: mapped
.iter()
.take(usize::from(map.count))
.filter_map(|pair| char::from_u32(u32::from(pair.unicode)))
.collect(),
)
uses_high_glyphs: mapped
.iter()
.any(|pair| pair.font_position > HIGHEST_LOW_GLYPH),
})
}
#[repr(C)]
@@ -198,7 +222,7 @@ fn active_vt() -> Option<u16> {
Some(state.active)
}
fn own_vt() -> Option<u16> {
fn vt_of_stdin() -> Option<u16> {
let name = ttyname(stdin(), Vec::new()).ok()?;
name.to_str()
.ok()?
@@ -209,8 +233,7 @@ fn own_vt() -> Option<u16> {
}
impl ForegroundVt {
fn take() -> Option<Self> {
let own = own_vt()?;
fn take(own: u16) -> Option<Self> {
let previous = active_vt()?;
if previous != own {
activate(own).ok()?;
+4 -4
View File
@@ -8,6 +8,7 @@ use crate::{
boot_view::PasswordPrompt,
console_session::{
ask_password::{PasswordEntry, RequestWatch},
console_palette::ConsolePalette,
console_takeover::Console,
passphrase_input::asks_to_quit,
stream_sources::{
@@ -19,7 +20,6 @@ use crate::{
screen_settings::font_glyphs::Glyphs,
};
const CONSOLE_UPKEEP_INTERVAL: Duration = Duration::from_secs(1);
const FULL_REPAINT_INTERVAL: Duration = Duration::from_secs(5);
pub struct LiveDesk {
@@ -58,8 +58,8 @@ impl ConsoleDesk for LiveDesk {
&self.console.glyphs
}
fn drops_bold(&self) -> bool {
self.console.bold_is_brightness
fn palette(&self) -> ConsolePalette {
self.console.palette
}
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> {
periodic_inputs(CONSOLE_UPKEEP_INTERVAL, || ScreenInput::ConsoleUpkeep)
periodic_inputs(BACKGROUND_CHECK_INTERVAL, || ScreenInput::ConsoleUpkeep)
}
pub fn full_repaint_inputs() -> impl Stream<Item = ScreenInput> {
+5 -14
View File
@@ -6,12 +6,12 @@ use ratatui::{
Terminal,
backend::Backend,
buffer::{Buffer, CellDiffOption},
style::Modifier,
};
use crate::{
boot_model::{BootChange, BootProjection, BootState, boot_origin::BootOrigin},
boot_view::{BootView, PasswordPrompt, project_boot},
console_session::console_palette::ConsolePalette,
screen_settings::{color_scheme::Colors, config_file::Timing, font_glyphs::Glyphs},
systemd_link::{link_error::Error, monotonic_clock::monotonic_now},
};
@@ -39,7 +39,7 @@ pub enum WatchEnding {
pub trait ConsoleDesk {
fn glyphs(&self) -> &Glyphs;
fn drops_bold(&self) -> bool;
fn palette(&self) -> ConsolePalette;
fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>>;
fn press_key(&mut self, event: &Event, 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(),
);
if self.desk.drops_bold() {
drop_bold(canvas.buffer_mut());
}
self.desk.palette().fit_frame(canvas.buffer_mut());
})?;
if self.full_repaint_due {
let painted = completed.buffer.clone();
@@ -259,13 +257,6 @@ fn overwrite_every_cell<B: Backend>(backend: &mut B, frame: &Buffer) -> Result<(
backend.flush()
}
fn drop_bold(frame: &mut Buffer) {
frame
.content
.iter_mut()
.for_each(|cell| cell.modifier.remove(Modifier::BOLD));
}
#[cfg(test)]
mod tests {
use super::*;
@@ -285,8 +276,8 @@ mod tests {
&self.glyphs
}
fn drops_bold(&self) -> bool {
false
fn palette(&self) -> ConsolePalette {
ConsolePalette::Terminal
}
fn prompt(&self, _now: Duration) -> Option<PasswordPrompt<'_>> {
+3 -2
View File
@@ -17,6 +17,7 @@ use crate::{
},
boot_view::PasswordPrompt,
console_session::{
console_palette::ConsolePalette,
passphrase_input,
stream_sources::{frame_inputs, key_inputs},
watch_screen::{ConsoleDesk, WatchEnding, WatchScreen, watch_until_ending},
@@ -328,8 +329,8 @@ impl ConsoleDesk for DemoDesk {
&self.glyphs
}
fn drops_bold(&self) -> bool {
false
fn palette(&self) -> ConsolePalette {
ConsolePalette::Terminal
}
fn prompt(&self, now: Duration) -> Option<PasswordPrompt<'_>> {
+27
View File
@@ -275,11 +275,35 @@ pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> {
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> {
let target = &options.target;
if target.needs_sudo() {
return rerun_with_sudo();
}
let removed_initrd_hooks = installed_initrd_hooks(target);
if target.changes_live_system() {
let installed_units: Vec<&str> = unit_names()
.filter(|unit| target.unit_path(unit).exists())
@@ -304,6 +328,9 @@ pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> {
}
if target.changes_live_system() {
systemctl(["daemon-reload"])?;
removed_initrd_hooks
.into_iter()
.for_each(print_initramfs_removal_hint);
}
Ok(())
}
+44 -18
View File
@@ -1,7 +1,7 @@
use std::{
future::ready,
io, iter, mem,
os::fd::{AsRawFd, RawFd},
os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd},
time::Duration,
};
@@ -11,6 +11,7 @@ use dbus::{
channel::{BusType, Channel},
};
use futures::{StreamExt, stream};
use rustix::event::{PollFd, PollFlags, Timespec, poll};
use tokio::{io::unix::AsyncFd, time::timeout};
use crate::{
@@ -185,10 +186,34 @@ impl Session {
pub fn boot_in_progress(&self) -> Result<bool, Error> {
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 {
readiness: AsyncFd<Session>,
session: AsyncFd<Session>,
early_signals: Vec<Signal>,
}
@@ -202,24 +227,23 @@ fn into_results(batch: Result<Vec<Message>, Error>) -> Vec<Result<Message, Error
impl BusConnection {
pub fn register(session: Session) -> io::Result<Self> {
Ok(Self {
readiness: readable_source(session)?,
session: readable_source(session)?,
early_signals: Vec::new(),
})
}
#[must_use]
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> {
let channel = &self.readiness.get_mut().channel;
if channel.read_write(Some(Duration::ZERO)).is_err() || !channel.is_connected() {
return Err(Error::Disconnected);
}
let (signals, replies): (Vec<Message>, Vec<Message>) =
iter::from_fn(|| channel.pop_message())
.partition(|message| message.msg_type() == MessageType::Signal);
let (signals, replies): (Vec<Message>, Vec<Message>) = self
.session
.get_ref()
.arrived_messages()?
.into_iter()
.partition(|message| message.msg_type() == MessageType::Signal);
self.early_signals
.extend(signals.iter().filter_map(parse_signal));
Ok(replies)
@@ -230,7 +254,7 @@ impl BusConnection {
if !drained.is_empty() {
return Ok(drained);
}
self.readiness.readable_mut().await?.clear_ready();
self.session.readable_mut().await?.clear_ready();
self.drain_replies()
}
@@ -256,11 +280,7 @@ impl BusConnection {
}
async fn call(&mut self, call: Message) -> Result<Message, Error> {
let channel = &self.readiness.get_ref().channel;
let Ok(serial) = channel.send(call) else {
return Err(Error::Disconnected);
};
channel.flush();
let serial = self.session.get_ref().send(call)?;
let Ok(reply) = timeout(CALL_TIMEOUT, self.reply_to(serial)).await else {
return Err(Error::CallTimedOut);
};
@@ -327,7 +347,7 @@ impl BusConnection {
pub async fn receive_signals(&mut self, patience: Duration) -> Result<Vec<Signal>, Error> {
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();
}
@@ -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> {
let Ok(mut ping) = Message::new_method_call(DESTINATION, MANAGER_PATH, PEER_INTERFACE, "Ping")
else {