Merge remote-tracking branch 'upstream/master' into installer-0.2.42-rb1

# Conflicts:
#	Cargo.lock
#	Cargo.toml
This commit is contained in:
Red Bear OS
2026-07-11 11:33:14 +03:00
18 changed files with 8593 additions and 597 deletions
+11 -1
View File
@@ -1,4 +1,3 @@
image: "rust:latest"
stages:
- lint
@@ -10,15 +9,26 @@ workflow:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"'
fmt:
image: "rust:latest"
stage: lint
script:
- rustup component add rustfmt
- cargo fmt -- --check
- cd gui && cargo fmt -- --check
cargo-test:
image: "rust:latest"
stage: test
script:
- apt update && apt install -y fuse3 libfuse3-dev
- cargo build --locked
- cargo test
- ./target/debug/redox_installer -c res/test.toml test.bin --no-mount
gui-build:
stage: test
script:
- apt update && apt install -y fuse3 libfuse3-dev
- cd gui
- redoxer build
- cargo build
Generated
+367 -415
View File
File diff suppressed because it is too large Load Diff
+10 -7
View File
@@ -28,12 +28,12 @@ arg_parser = "0.1.0"
fatfs = { version = "0.3.0", optional = true }
fscommon = { version = "0.1.1", optional = true }
gpt = { version = "3.0.0", optional = true }
libc = "0.2.70"
pkgar = { version = "0.2", optional = true }
pkgar-core = { version = "0.2", optional = true }
pkgar-keys = { version = "0.2", optional = true }
libc = { version = "0.2.70", optional = true }
pkgar = { version = "0.2.2", optional = true }
pkgar-core = { version = "0.2.2", optional = true }
pkgar-keys = { version = "0.2.2", optional = true }
rand = { version = "0.9", optional = true }
redox-pkg = { version = "0.3", features = ["indicatif"], optional = true }
redox-pkg = { version = "0.3.1", features = ["indicatif"], optional = true }
redox_syscall = { path = "../syscall", optional = true }
redoxfs = { path = "../redoxfs", optional = true, default-features = false, features = ["std", "log"] }
rust-argon2 = { version = "3", optional = true }
@@ -44,8 +44,8 @@ toml = "0.8"
uuid = { version = "1.4", features = ["v4"], optional = true }
[target.'cfg(target_os = "redox")'.dependencies]
libredox = { path = "../libredox" }
ring = "=0.17.8"
libredox = { path = "../libredox", optional = true }
ring = { version = "=0.17.8", optional = true }
[features]
default = ["installer", "fuse"]
@@ -53,6 +53,8 @@ installer = [
"fatfs",
"fscommon",
"gpt",
"libc",
"libredox",
"pkgar",
"pkgar-core",
"pkgar-keys",
@@ -60,6 +62,7 @@ installer = [
"redox-pkg",
"redox_syscall",
"redoxfs",
"ring",
"rust-argon2",
"termion",
"uuid",
+1
View File
@@ -0,0 +1 @@
/target/
+7016
View File
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "redox_installer_gui"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1"
pkgar = "0.2"
pkgar-core = "0.2"
pkgar-keys = "0.2"
redox_installer = { path = ".." }
redox_syscall = "0.9"
toml = "0.8"
# TODO: remove after pkgutils update
futures-channel = "0.3.32"
[target.'cfg(target_os = "redox")'.dependencies]
libredox = "0.1"
[target.'cfg(target_os = "linux")'.dependencies]
libc = "0.2"
[dependencies.libcosmic]
git = "https://github.com/pop-os/libcosmic.git"
# use the same rev with other cosmic app
rev = "bb10afd849f1ad172be6b78eeec347d548aa4fd7"
default-features = false
features = ["winit"]
[patch.crates-io]
ring = { git = "https://gitlab.redox-os.org/redox-os/ring.git", branch = "redox-0.17.8" }
+92
View File
@@ -0,0 +1,92 @@
# installer_gui
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.redox-os.org/redox-os/installer_gui.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.redox-os.org/redox-os/installer_gui/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
+634
View File
@@ -0,0 +1,634 @@
use anyhow::format_err;
use cosmic::{
app::{self, Task},
iced::{
self, executor,
futures::sink::SinkExt,
widget::{row, text_input},
window, Alignment, Size, Subscription,
},
widget::{button, column, progress_bar, radio, space, text},
Application, ApplicationExt, Core, Element,
};
use futures_channel::mpsc;
use pkgar::{ext::EntryExt, PackageHead};
use pkgar_core::PackageSrc;
use pkgar_keys::PublicKeyFile;
use redox_installer::{try_fast_install, with_redoxfs_mount, with_whole_disk, Config, DiskOption};
use std::{
ffi::OsStr,
fs,
io::{self, Read, Write},
os::unix::fs::{symlink, MetadataExt, OpenOptionsExt},
path::Path,
sync::Arc,
};
mod sys;
pub use sys::*;
fn main() -> iced::Result {
let mut settings = app::Settings::default();
settings = settings.size(Size::new(608.0, 416.0));
settings = settings.exit_on_close(false);
app::run::<Window>(settings, ())
}
fn copy_file(src: &Path, dest: &Path, buf: &mut [u8]) -> anyhow::Result<()> {
if let Some(parent) = dest.parent() {
// Parent may be a symlink
if !parent.is_symlink() {
match fs::create_dir_all(&parent) {
Ok(()) => (),
Err(err) => {
return Err(format_err!(
"failed to create directory {}: {}",
parent.display(),
err
));
}
}
}
}
let metadata = match fs::symlink_metadata(&src) {
Ok(ok) => ok,
Err(err) => {
return Err(format_err!(
"failed to read metadata of {}: {}",
src.display(),
err
));
}
};
if metadata.file_type().is_symlink() {
let real_src = match fs::read_link(&src) {
Ok(ok) => ok,
Err(err) => {
return Err(format_err!(
"failed to read link {}: {}",
src.display(),
err
));
}
};
match symlink(&real_src, &dest) {
Ok(()) => (),
Err(err) => {
return Err(format_err!(
"failed to copy link {} ({}) to {}: {}",
src.display(),
real_src.display(),
dest.display(),
err
));
}
}
} else {
let mut src_file = match fs::File::open(&src) {
Ok(ok) => ok,
Err(err) => {
return Err(format_err!(
"failed to open file {}: {}",
src.display(),
err
));
}
};
let mut dest_file = match fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(metadata.mode())
.open(&dest)
{
Ok(ok) => ok,
Err(err) => {
return Err(format_err!(
"failed to create file {}: {}",
dest.display(),
err
));
}
};
loop {
let count = match src_file.read(buf) {
Ok(ok) => ok,
Err(err) => {
return Err(format_err!(
"failed to read file {}: {}",
src.display(),
err
));
}
};
if count == 0 {
break;
}
match dest_file.write_all(&buf[..count]) {
Ok(()) => (),
Err(err) => {
return Err(format_err!(
"failed to write file {}: {}",
dest.display(),
err
));
}
}
}
}
Ok(())
}
fn package_files(
root_path: &Path,
config: &mut Config,
files: &mut Vec<String>,
) -> Result<(), anyhow::Error> {
//TODO: Remove packages from config where all files are located (and have valid shasum?)
config.packages.clear();
let pkey_path = "pkg/id_ed25519.pub.toml";
let pkey = PublicKeyFile::open(&root_path.join(pkey_path))?.pkey;
files.push(pkey_path.to_string());
for item_res in fs::read_dir(&root_path.join("pkg"))? {
let item = item_res?;
let pkg_path = item.path();
if pkg_path.extension() == Some(OsStr::new("pkgar_head")) {
let mut pkg = PackageHead::new(&pkg_path, &root_path, &pkey)?;
for entry in pkg.read_entries()? {
files.push(entry.check_path()?.to_str().unwrap().to_string());
}
files.push(
pkg_path
.strip_prefix(root_path)
.unwrap()
.to_str()
.unwrap()
.to_string(),
);
}
}
Ok(())
}
fn install<F: FnMut(Message)>(disk_path: String, password_opt: Option<String>, mut f: F) {
let start = std::time::Instant::now();
let mut progress = 0;
macro_rules! message {
($($arg:tt)*) => {{
eprintln!($($arg)*);
f(Message::Install(
progress,
format!($($arg)*)
));
}}
}
let root_path = Path::new("/scheme/file/");
message!("Loading bootloader");
let bootloader_bios = {
let path = root_path.join("boot").join("bootloader.bios");
if path.exists() {
match fs::read(&path) {
Ok(ok) => ok,
Err(err) => {
f(Message::Error(format!(
"{}: failed to read: {}",
path.display(),
err
)));
return;
}
}
} else {
Vec::new()
}
};
message!("Loading bootloader.efi");
let bootloader_efi = {
let path = root_path.join("boot").join("bootloader.efi");
if path.exists() {
match fs::read(&path) {
Ok(ok) => ok,
Err(err) => {
f(Message::Error(format!(
"{}: failed to read: {}",
path.display(),
err
)));
return;
}
}
} else {
Vec::new()
}
};
message!("Formatting disk");
let disk_option = DiskOption {
bootloader_bios: &bootloader_bios,
bootloader_efi: &bootloader_efi,
password_opt: password_opt.as_ref().map(|x| x.as_bytes()),
efi_partition_size: None,
skip_partitions: false,
};
let res = with_whole_disk(&disk_path, &disk_option, |mut fs| -> anyhow::Result<()> {
// Fast install method via filesystem clone
let mut last_progress = 0;
if try_fast_install(&mut fs, |used, used_old| {
progress = ((used * 100) / used_old) as usize;
if progress != last_progress {
message!(
"{}%: {} MB/{} MB",
progress,
used / 1000 / 1000,
used_old / 1000 / 1000
);
last_progress = progress;
}
})? {
progress = 100;
message!("Finished installing using fast mode");
return Ok(());
}
with_redoxfs_mount(fs, None, |mount_path: &Path| -> anyhow::Result<()> {
message!("Loading filesystem.toml");
let mut config: Config = {
let path = root_path.join("filesystem.toml");
match fs::read_to_string(&path) {
Ok(config_data) => match toml::from_str(&config_data) {
Ok(config) => config,
Err(err) => {
return Err(format_err!(
"{}: failed to decode: {}",
path.display(),
err
));
}
},
Err(err) => {
return Err(format_err!("{}: failed to read: {}", path.display(), err));
}
}
};
// Copy filesystem.toml, which is not packaged
let mut files = vec!["filesystem.toml".to_string()];
// Copy files from locally installed packages
message!("Loading package files");
if let Err(err) = package_files(&root_path, &mut config, &mut files) {
return Err(format_err!("failed to read package files: {}", err));
}
// Sort and remove duplicates
files.sort();
files.dedup();
// Perform config install (after packages have been converted to files)
message!("Configuring system");
let cookbook: Option<&'static str> = None;
redox_installer::install_dir(config, mount_path, cookbook)
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;
// Install files
let mut buf = vec![0; 4096 * 1024];
for (i, name) in files.iter().enumerate() {
progress = (i * 100) / files.len();
message!("Copy {} [{}/{}]", name, i, files.len());
let src = root_path.join(name);
let dest = mount_path.join(name);
copy_file(&src, &dest, &mut buf)?;
}
progress = 100;
message!("Finished installing, unmounting filesystem");
Ok(())
})
});
match res {
Ok(()) => {
f(Message::Success(format!(
"Finished installing in {:?}, ready to reboot",
start.elapsed()
)));
}
Err(err) => {
f(Message::Error(format!("Failed to install: {}", err)));
}
}
}
#[derive(Debug)]
enum Page {
Sudo(String),
Disk(Option<usize>),
Install(usize, String),
Success(String),
Error(String),
}
#[derive(Clone, Debug)]
struct Worker {
command_sender: std::sync::mpsc::Sender<(String, Option<String>)>,
join_handle: Arc<std::thread::JoinHandle<()>>,
}
#[derive(Clone, Debug)]
enum Message {
None,
Worker(Worker),
SudoInput(String),
SudoSubmit,
DiskChoose(usize),
DiskConfirm(usize),
Install(usize, String),
Success(String),
Exit,
Error(String),
}
struct Window {
core: Core,
page: Page,
disk_paths: Vec<(String, bool, u64)>,
worker_opt: Option<Worker>,
}
enum State {
Ready,
Waiting(mpsc::UnboundedReceiver<Message>),
Finished,
}
impl Window {
fn worker_stream() -> impl iced::futures::Stream<Item = Message> {
iced::stream::channel(100, |mut output: mpsc::Sender<Message>| async move {
let mut state = State::Ready;
loop {
let (message, new_state) = match state {
State::Ready => {
let (command_sender, command_receiver) = std::sync::mpsc::channel();
let (message_sender, message_receiver) = mpsc::unbounded();
//TODO: kill worker thread?
let join_handle = std::thread::spawn(move || {
while let Ok((disk_path, password_opt)) = command_receiver.recv() {
println!("Installing to {:?}", disk_path);
install(disk_path, password_opt, |message| {
message_sender.unbounded_send(message).unwrap();
});
}
});
let worker = Worker {
command_sender,
join_handle: std::sync::Arc::new(join_handle),
};
(Message::Worker(worker), State::Waiting(message_receiver))
}
State::Waiting(mut message_receiver) => {
use iced::futures::StreamExt;
match message_receiver.next().await {
Some(message) => (message, State::Waiting(message_receiver)),
None => (Message::None, State::Finished),
}
}
State::Finished => iced::futures::future::pending().await,
};
output.send(message).await.unwrap();
state = new_state;
}
})
}
}
impl Application for Window {
type Executor = executor::Default;
type Flags = ();
type Message = Message;
const APP_ID: &'static str = "org.redox-os.InstallerGui";
fn init(core: Core, _flags: ()) -> (Self, Task<Message>) {
//TODO: load in background
let (page, disk_paths) = match disk_paths() {
Ok(disk_paths) => (Page::Disk(None), disk_paths),
Err(err) => (Page::Error(err), Vec::new()),
};
let mut app = Self {
core,
page,
disk_paths,
worker_opt: None,
};
let task = app.set_window_title("Redox OS Installer".to_string());
(app, task)
}
fn core(&self) -> &Core {
&self.core
}
fn core_mut(&mut self) -> &mut Core {
&mut self.core
}
fn update(&mut self, message: Message) -> Task<Message> {
match message {
Message::None => {}
Message::Worker(worker) => {
self.worker_opt = Some(worker);
}
Message::SudoInput(password) => {
self.page = Page::Sudo(password);
}
Message::SudoSubmit => {
#[cfg(target_os = "redox")]
if let Page::Sudo(password) = &self.page {
match ask_root(&password) {
Ok(()) => {
self.page = Page::Disk(None);
}
Err(err) => {
eprintln!("{err}");
}
}
}
#[cfg(target_os = "linux")]
match ask_root() {
Ok(()) => {
if let Some(window_id) = self.core.main_window_id() {
return window::close(window_id);
}
}
Err(err) => {
eprintln!("{err}");
}
}
}
Message::DiskChoose(disk_i) => {
self.page = Page::Disk(Some(disk_i));
}
Message::DiskConfirm(disk_i) => match self.disk_paths.get(disk_i) {
Some((disk_path, _is_partition, _disk_size)) => match &self.worker_opt {
Some(worker) => match worker.command_sender.send((disk_path.clone(), None)) {
Ok(()) => self.page = Page::Install(0, format!("Starting install...")),
Err(err) => {
self.page = Page::Error(format!("failed to send command: {}", err));
}
},
None => {
self.page = Page::Error(format!("command sender not found"));
}
},
None => {
self.page = Page::Error(format!("invalid disk number {} chosen", disk_i));
}
},
Message::Install(progress, description) => {
self.page = Page::Install(progress, description);
}
Message::Success(description) => {
self.page = Page::Success(description);
}
Message::Error(err) => {
self.page = Page::Error(err);
}
Message::Exit => {
if let Some(worker) = self.worker_opt.take() {
drop(worker.command_sender);
let join_handle = Arc::try_unwrap(worker.join_handle).unwrap();
join_handle.join().unwrap();
}
if let Some(window_id) = self.core.main_window_id() {
return window::close(window_id);
}
}
}
Task::none()
}
fn view(&self) -> Element<'_, Message> {
let mut widgets = Vec::new();
match &self.page {
Page::Sudo(password) => {
widgets.push(text("Enter your password:").into());
widgets.push(
text_input("", password)
.on_input(Message::SudoInput)
.secure(true)
.on_submit(Message::SudoSubmit)
.into(),
);
}
Page::Disk(disk_i_opt) => {
if !self.disk_paths.is_empty() {
if is_root() {
widgets.push(text("Choose a drive:").size(24).into());
for (disk_i, (disk_path, is_partition, disk_size)) in
self.disk_paths.iter().enumerate()
{
if !is_partition {
widgets.push(
row![
radio(
text(disk_path),
disk_i,
*disk_i_opt,
Message::DiskChoose
),
space::horizontal(),
text(redox_installer::format_bytes(*disk_size)),
]
.into(),
);
}
}
if let Some(disk_i) = *disk_i_opt {
widgets.push(space::vertical().into());
widgets.push(
row![
space::horizontal(),
button::destructive("Confirm")
.on_press(Message::DiskConfirm(disk_i)),
]
.into(),
);
}
} else {
#[cfg(target_os = "linux")]
let page = Message::SudoSubmit;
#[cfg(target_os = "redox")]
let page = Message::SudoInput(String::new());
widgets.push(space::vertical().into());
widgets.push(
row![
text("Ask superuser permission to install into drives"),
space::horizontal(),
button::suggested("Ask root access").on_press(page),
]
.into(),
);
}
} else {
widgets.push(text("No drives found").into());
// TODO: expose disk.pci-*-*nvme/* */ scheme to user
widgets.push(text("(try to rerun with sudo)").into());
}
}
Page::Install(progress, description) => {
widgets.push(text("Installation progress:").size(24).into());
widgets.push(progress_bar::determinate_linear(*progress as f32 / 100.).into());
widgets.push(text(description).into());
}
Page::Success(description) => {
widgets.push(text("Installation complete!").size(24).into());
widgets.push(text(description).into());
widgets.push(space::vertical().into());
widgets.push(
row![
space::horizontal(),
button::standard("Exit").on_press(Message::Exit),
]
.into(),
);
}
Page::Error(err) => {
widgets.push(text(format!("{}", err)).into());
}
};
column::with_children(widgets)
.spacing(8)
.padding(24)
.align_x(Alignment::Start)
.into()
}
fn subscription(&self) -> Subscription<Message> {
Subscription::run(Self::worker_stream)
}
}
+12
View File
@@ -0,0 +1,12 @@
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "redox")]
mod redox;
#[cfg(target_os = "linux")]
pub use linux::*;
#[cfg(target_os = "redox")]
pub use redox::*;
#[cfg(not(any(target_os = "linux", target_os = "redox")))]
compile_error!("Platform is not ported");
+76
View File
@@ -0,0 +1,76 @@
use std::{fs, os::unix::process::CommandExt, process::Command};
pub fn ask_root() -> Result<(), String> {
let Ok(exe_path) = std::env::current_exe() else {
return Err(format!("Could not determine current_exe"));
};
let mut cmd = Command::new("pkexec");
cmd.arg("env");
for (key, value) in std::env::vars() {
if [
"DISPLAY",
"WAYLAND_DISPLAY",
"XAUTHORITY",
"XDG_RUNTIME_DIR",
"DBUS_SESSION_BUS_ADDRESS",
]
.contains(&key.as_str())
{
cmd.arg(format!("{}={}", key, value));
}
}
cmd.arg(exe_path);
// will never return unless fail
let e = cmd.exec();
return Err(format!("Failed to escalate: {e}"));
}
pub fn is_root() -> bool {
let euid = unsafe { libc::geteuid() };
euid == 0
}
pub fn disk_paths() -> Result<Vec<(String, bool, u64)>, String> {
let mut paths = Vec::new();
let entries = match fs::read_dir("/sys/class/block") {
Ok(entries) => entries,
Err(err) => return Err(format!("failed to read /sys/class/block: {}", err)),
};
for entry_res in entries {
if let Ok(entry) = entry_res {
let file_name = entry.file_name();
let name = file_name.to_string_lossy();
if name.starts_with("loop")
|| name.starts_with("ram")
|| name.starts_with("sr")
|| name.starts_with("zram")
{
continue;
}
let path = entry.path();
let is_partition = path.join("partition").exists();
let size_path = path.join("size");
let Ok(size_str) = fs::read_to_string(&size_path) else {
continue;
};
let Ok(sectors) = size_str.trim().parse::<u64>() else {
continue;
};
// /sys/class/block/*/size is 512 (cmiiw)
let size_bytes = sectors * 512;
if size_bytes == 0 {
continue;
}
paths.push((format!("/dev/{}", name), is_partition, size_bytes));
continue;
}
}
paths.sort_by(|a, b| a.0.cmp(&b.0));
Ok(paths)
}
+95
View File
@@ -0,0 +1,95 @@
use std::fs;
pub fn ask_root(password: &str) -> Result<(), String> {
let file = libredox::Fd::open("/scheme/sudo", libredox::flag::O_CLOEXEC, 0)
.map_err(|err| err.to_string())?;
file.write(password.as_bytes())
.map_err(|err| err.to_string())?;
// FIXME move to libredox
unsafe extern "C" {
safe fn redox_cur_procfd_v0() -> usize;
}
// Elevate privileges of our own process with help from the sudo daemon
file.call_wo(
&libredox::call::dup(redox_cur_procfd_v0(), &[])
.map_err(|err| err.to_string())?
.to_ne_bytes(),
syscall::CallFlags::FD,
&[],
)
.map_err(|err| err.to_string())?;
Ok(())
}
pub fn is_root() -> bool {
let euid = libredox::call::geteuid().unwrap();
euid == 0
}
pub fn disk_paths() -> Result<Vec<(String, bool, u64)>, String> {
let mut schemes = Vec::new();
match fs::read_dir("/scheme/") {
Ok(entries) => {
for entry_res in entries {
if let Ok(entry) = entry_res {
let path = entry.path();
if let Ok(path_str) = path.into_os_string().into_string() {
let scheme = path_str.trim_start_matches("/scheme/").trim_matches('/');
if scheme.starts_with("disk") {
if scheme == "disk/live" {
// Skip live disks
continue;
}
schemes.push(format!("/scheme/{}", scheme));
}
}
}
}
}
Err(err) => {
return Err(format!("failed to list schemes: {}", err));
}
}
let mut paths = Vec::new();
for scheme in schemes {
let is_dir = fs::metadata(&scheme).map(|x| x.is_dir()).unwrap_or(false);
if !is_dir {
continue;
}
match fs::read_dir(&scheme) {
Ok(entries) => {
for entry_res in entries {
let Ok(entry) = entry_res else {
continue;
};
let Ok(file_name) = entry.file_name().into_string() else {
continue;
};
let Ok(path) = entry.path().into_os_string().into_string() else {
continue;
};
let Ok(metadata) = entry.metadata() else {
continue;
};
let is_partition = file_name.contains('p');
let size = metadata.len();
if size == 0 {
continue;
}
paths.push((path, is_partition, size));
}
}
Err(err) => {
return Err(format!("failed to list {:?}: {}", scheme, err));
}
}
}
Ok(paths)
}
+103 -142
View File
@@ -4,12 +4,10 @@ include = []
[general]
prompt = false
filesystem_size = 256
filesystem_size = 196
[packages.base]
[packages.base-initfs]
[packages.bootloader]
[packages.ca-certificates]
@@ -18,8 +16,6 @@ filesystem_size = 256
[packages.extrautils]
[packages.findutils]
[packages.ion]
[packages.kernel]
@@ -42,26 +38,51 @@ filesystem_size = 256
[packages.uutils]
[[files]]
path = "/usr/lib/init.d/00_base"
data = """
# clear and recreate tmpdir with 0o1777 permission
rm -rf /tmp
mkdir -m a=rwxt /tmp
ipcd
ptyd
nowait sudo --daemon
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[packages.uutils-procps]
[[files]]
path = "/usr/lib/init.d/00_drivers"
path = "/etc/login_schemes.toml"
data = """
pcid-spawner /etc/pcid.d/
[user_schemes.root]
schemes = ["*"]
[user_schemes.user]
schemes = [
# Kernel schemes
"debug",
"event",
"memory",
"pipe",
"serio",
"irq",
"time",
"sys",
# Base schemes
"rand",
"null",
"zero",
"log",
# Network schemes
"ip",
"icmp",
"tcp",
"udp",
# IPC schemes
"shm",
"chan",
"uds_stream",
"uds_dgram",
# File schemes
"file",
# Display schemes
"display.vesa",
"display*",
# Other schemes
"proc",
"pty",
"sudo",
"audio",
"orbital",
]
"""
symlink = false
directory = false
@@ -76,6 +97,46 @@ directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/etc/net/dns"
data = """
9.9.9.9
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/etc/net/ip"
data = """
10.0.2.15
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/etc/net/ip_router"
data = """
10.0.2.2
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/etc/net/ip_subnet"
data = """
255.255.255.0
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/usr/lib/os-release"
data = """
@@ -197,8 +258,24 @@ recursive_chown = false
postinstall = false
[[files]]
path = "/usr/share/fonts"
data = "../../ui/fonts"
path = "/ui"
data = "usr/share/ui"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/usr/share/ui/fonts"
data = "/usr/share/fonts"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/usr/share/ui/icons"
data = "/usr/share/icons"
symlink = true
directory = false
recursive_chown = false
@@ -267,127 +344,13 @@ mode = 1023
recursive_chown = false
postinstall = false
[[files]]
path = "/dev/null"
data = "/scheme/null"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/dev/random"
data = "/scheme/rand"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/dev/urandom"
data = "/scheme/rand"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/dev/zero"
data = "/scheme/zero"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/dev/tty"
data = "libc:tty"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/dev/stdin"
data = "libc:stdin"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/dev/stdout"
data = "libc:stdout"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/dev/stderr"
data = "libc:stderr"
symlink = true
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/usr/lib/init.d/10_net"
data = """
smolnetd
nowait dhcpd
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/etc/net/dns"
data = """
9.9.9.9
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/etc/net/ip"
data = """
10.0.2.15
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/etc/net/ip_router"
data = """
10.0.2.2
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/etc/net/ip_subnet"
data = """
255.255.255.0
"""
symlink = false
directory = false
recursive_chown = false
postinstall = false
[[files]]
path = "/usr/lib/init.d/30_console"
data = """
requires_weak 10_net.target
inputd -A 2
nowait getty 2
nowait getty /scheme/debug -J
nowait getty /scheme/debug/no-preserve -J
"""
symlink = false
directory = false
@@ -398,8 +361,6 @@ postinstall = false
password = "password"
uid = 0
gid = 0
name = "root"
home = "/root"
shell = "/usr/bin/ion"
[users.user]
+1 -1
View File
@@ -16,6 +16,6 @@ set -x
# Update res/test.toml from the redoxer.toml template
"${REDOX_PATH}/build/fstools/bin/redox_installer" \
--config="${REDOX_PATH}/config/x86_64/minimal-net.toml" \
--config="${REDOX_PATH}/config/minimal.toml" \
--output-config="${RES_PATH}/test.toml"
sed -i '1s/^/# Automatically generated by update.sh\n\n/' "${RES_PATH}/test.toml"
+86
View File
@@ -3,10 +3,13 @@ extern crate redox_installer;
extern crate serde;
extern crate toml;
use std::cell::RefCell;
use std::path::Path;
use std::rc::Rc;
use std::{env, fs, process};
use arg_parser::ArgParser;
use pkg::net_backend::DownloadBackend;
use redox_installer::{Config, PackageConfig};
@@ -25,6 +28,7 @@ Using redox_installer as an installer:
--live Use bootloader configured for live disk
--no-mount Use RedoxFS AR instead of FUSE to write files
--cookbook Use local Redox OS build system rather than downloading packages
--config-name Name of the filesystem configuration used for os-release VARIANT
Using redox_installer as a configuration parser:
redox_installer --config=file.toml [--list-packages|--filesystem-size|--output-config path]
@@ -33,9 +37,80 @@ Using redox_installer as a configuration parser:
--output-config Path to write the parsed config as another TOML
"#;
fn os_release_quote(value: &str) -> String {
let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
format!("\"{}\"", escaped)
}
fn build_id_from_repo_toml(repo_toml: &str) -> Option<String> {
toml::from_str::<toml::Value>(repo_toml)
.ok()?
.get("build_id")?
.as_str()
.and_then(|value| {
if value.is_empty() {
None
} else {
Some(value.to_string())
}
})
}
fn local_repo_build_id(cookbook: &str) -> Option<String> {
let repo_toml = Path::new(cookbook)
.join("repo")
.join(redox_installer::get_target())
.join("repo.toml");
let repo_toml = fs::read_to_string(repo_toml).ok()?;
build_id_from_repo_toml(&repo_toml)
}
fn remote_repo_build_id() -> Option<String> {
let callback = Rc::new(RefCell::new(pkg::callback::SilentCallback::new()));
let download_backend = pkg::net_backend::DefaultNetBackend::new().ok()?;
let mut repo = pkg::RepoManager::new(callback, Box::new(download_backend));
repo.add_remote(
"https://static.redox-os.org/pkg",
&redox_installer::get_target(),
)
.ok()?;
let package = pkg::PackageName::new("repo").ok()?;
let (repo_toml, _) = repo.get_package_toml(&package).ok()?;
build_id_from_repo_toml(&repo_toml)
}
fn append_os_release_metadata(
config: &mut Config,
config_name: Option<&str>,
build_id: Option<String>,
) {
let mut data = String::new();
if let Some(config_name) = config_name.filter(|value| !value.is_empty()) {
data.push_str("VARIANT=");
data.push_str(&os_release_quote(config_name));
data.push('\n');
}
if let Some(build_id) = build_id.filter(|value| !value.is_empty()) {
data.push_str("BUILD_ID=");
data.push_str(&os_release_quote(&build_id));
data.push('\n');
}
if !data.is_empty() {
config.files.push(redox_installer::FileConfig {
path: "/usr/lib/os-release".to_string(),
data,
append: true,
..Default::default()
});
}
}
fn main() {
let mut parser = ArgParser::new(4)
.add_opt("b", "cookbook")
.add_opt("", "config-name")
.add_opt("c", "config")
.add_opt("o", "output-config")
.add_opt("", "write-bootloader")
@@ -107,6 +182,17 @@ fn main() {
None
};
let build_id = if let Some(cookbook) = cookbook.as_deref() {
local_repo_build_id(cookbook)
} else {
remote_repo_build_id()
};
append_os_release_metadata(
&mut config,
parser.get_opt("config-name").as_deref(),
build_id,
);
if cookbook.is_some() {
config.general.cookbook = cookbook;
}
+2 -21
View File
@@ -74,25 +74,6 @@ fn disk_paths(paths: &mut Vec<(PathBuf, u64)>) {
}
}
const KIB: u64 = 1024;
const MIB: u64 = 1024 * KIB;
const GIB: u64 = 1024 * MIB;
const TIB: u64 = 1024 * GIB;
fn format_size(size: u64) -> String {
if size >= 4 * TIB {
format!("{:.1} TiB", size as f64 / TIB as f64)
} else if size >= GIB {
format!("{:.1} GiB", size as f64 / GIB as f64)
} else if size >= MIB {
format!("{:.1} MiB", size as f64 / MIB as f64)
} else if size >= KIB {
format!("{:.1} KiB", size as f64 / KIB as f64)
} else {
format!("{} B", size)
}
}
fn copy_file(src: &Path, dest: &Path, buf: &mut [u8]) -> Result<()> {
if let Some(parent) = dest.parent() {
// Parent may be a symlink
@@ -220,7 +201,7 @@ fn choose_disk() -> PathBuf {
"\x1B[1m{}\x1B[0m: {}: {}",
i + 1,
path.display(),
format_size(*size)
redox_installer::format_bytes(*size)
);
}
@@ -361,7 +342,7 @@ fn main() {
files.dedup();
// Install files
let mut buf = vec![0; 4 * MIB as usize];
let mut buf = vec![0; 4096 * 1024];
for (i, name) in files.iter().enumerate() {
eprintln!("copy {} [{}/{}]", name, i, files.len());
+10 -5
View File
@@ -1,5 +1,9 @@
use std::fmt::Display;
fn is_false(value: &bool) -> bool {
!*value
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct FileConfig {
pub path: String,
@@ -15,6 +19,8 @@ pub struct FileConfig {
pub recursive_chown: bool,
#[serde(default)]
pub postinstall: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub append: bool,
}
impl FileConfig {
@@ -60,14 +66,13 @@ impl Display for FileConfig {
write!(f, " chown=yes")?;
}
} else {
write!(
f,
" size={}B",
arg_parser::to_human_readable_string(self.data.len() as u64)
)?;
write!(f, " size={}", crate::format_bytes(self.data.len() as u64))?;
if self.postinstall {
write!(f, "!")?;
}
if self.append {
write!(f, " append=yes")?;
}
}
if let Some(uid) = self.uid {
write!(f, " uid={}", uid)?;
+13 -3
View File
@@ -60,9 +60,19 @@ impl crate::FileConfig {
})?;
Ok(())
} else {
println!("Create file {}", target_file.display());
let mut file = File::create(&target_file)
.with_context(|| format!("failed to create file {}", target_file.display()))?;
let action = if self.append { "Append" } else { "Create" };
println!("{action} file {}", target_file.display());
let mut file = if self.append {
fs::OpenOptions::new()
.create(true)
.append(true)
.open(&target_file)
.with_context(|| format!("failed to append file {}", target_file.display()))?
} else {
File::create(&target_file)
.with_context(|| format!("failed to create file {}", target_file.display()))?
};
file.write_all(self.data.as_bytes())?;
self.apply_perms(target_file)
+33 -2
View File
@@ -13,7 +13,9 @@ use crate::disk_wrapper::DiskWrapper;
use std::{
cell::RefCell,
collections::BTreeMap,
env, fs,
env,
fmt::Write as WriteFmt,
fs,
io::{self, Seek, SeekFrom, Write},
path::{Path, PathBuf},
process,
@@ -31,7 +33,7 @@ pub struct DiskOption<'a> {
pub skip_partitions: bool,
}
fn get_target() -> String {
pub fn get_target() -> String {
// TODO: Configurable from filesystem config?
env::var("TARGET").unwrap_or(
option_env!("TARGET").map_or("x86_64-unknown-redox".to_string(), |x| x.to_string()),
@@ -853,3 +855,32 @@ fn install_inner(config: Config, output: &Path) -> Result<()> {
pub fn install(config: Config, output: impl AsRef<Path>) -> Result<()> {
install_inner(config, output.as_ref())
}
/// Convert bytes into readable string
pub fn format_bytes(len: u64) -> String {
const GB: u64 = 1024 * 1024 * 1024;
const MB: u64 = 1024 * 1024;
const KB: u64 = 1024;
if len > GB {
format_bytes_inner(len, GB, "GB")
} else if len > MB {
format_bytes_inner(len, MB, "MB")
} else if len > KB {
format_bytes_inner(len, KB, "KB")
} else {
format!("{len} B")
}
}
fn format_bytes_inner(len: u64, divisor: u64, suffix: &'static str) -> String {
let mut s = format!("{}", len / divisor);
if s.len() == 1 {
let _ = write!(s, ".{:02}", (len % divisor) / (divisor / 100));
} else if s.len() == 2 {
let _ = write!(s, ".{:01}", (len % divisor) / (divisor / 10));
}
let _ = write!(s, " {suffix}");
s
}