morpheus_bootloader/boot/
iso_boot.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
//! ISO Boot Support
//!
//! Boots Linux kernels from chunked ISO storage using iso9660 parsing.
//!
//! # Boot Flow
//!
//! ```text
//! 1. Get IsoReadContext from IsoStorageManager
//! 2. Create IsoBlockIoAdapter wrapping disk block I/O
//! 3. Mount ISO via iso9660::mount()
//! 4. Find boot image via iso9660::find_boot_image()
//! 5. Extract kernel (vmlinuz) and initrd from ISO
//! 6. Call boot_linux_kernel() with extracted files
//! ```

use crate::boot::loader::{boot_linux_kernel, BootError};
use crate::tui::renderer::Screen;
use crate::BootServices;
use gpt_disk_io::BlockIo;
use morpheus_core::iso::{IsoBlockIoAdapter, IsoError, IsoReadContext};

extern crate alloc;
use alloc::vec::Vec;

/// Error during ISO boot process
#[derive(Debug)]
pub enum IsoBootError {
    /// ISO storage error
    Storage(IsoError),
    /// Failed to mount ISO filesystem
    MountFailed,
    /// No bootable image in ISO
    NoBootImage,
    /// Failed to find kernel
    KernelNotFound,
    /// Failed to read kernel
    KernelReadFailed,
    /// Failed to find initrd
    InitrdNotFound,
    /// Failed to read initrd
    InitrdReadFailed,
    /// Boot process failed
    BootFailed(BootError),
}

/// Boot from a chunked ISO
///
/// # Arguments
/// * `boot_services` - UEFI boot services
/// * `system_table` - UEFI system table
/// * `image_handle` - Current image handle
/// * `ctx` - ISO read context from storage manager
/// * `block_io` - Underlying disk block I/O
/// * `cmdline` - Kernel command line
/// * `screen` - Screen for progress display
///
/// # Safety
/// This function never returns on success - it transfers control to the kernel.
pub unsafe fn boot_from_iso<B: BlockIo>(
    boot_services: &BootServices,
    system_table: *mut (),
    image_handle: *mut (),
    ctx: IsoReadContext,
    block_io: &mut B,
    cmdline: &str,
    screen: &mut Screen,
) -> Result<core::convert::Infallible, IsoBootError> {
    use crate::tui::renderer::{EFI_BLACK, EFI_LIGHTGREEN, EFI_YELLOW};

    let mut log_y = 5;

    // Create adapter
    screen.put_str_at(
        5,
        log_y,
        "Mounting ISO filesystem...",
        EFI_LIGHTGREEN,
        EFI_BLACK,
    );
    log_y += 1;

    let mut adapter = IsoBlockIoAdapter::new(ctx, block_io);

    // Mount ISO
    let volume = iso9660::mount(&mut adapter, 0).map_err(|_| IsoBootError::MountFailed)?;

    screen.put_str_at(5, log_y, "Finding boot image...", EFI_LIGHTGREEN, EFI_BLACK);
    log_y += 1;

    // Try to find El Torito boot image first
    let boot_image = iso9660::find_boot_image(&mut adapter, &volume);

    // Determine kernel and initrd paths
    let (kernel_path, initrd_path) = if boot_image.is_ok() {
        // Standard live ISO layout - try common paths
        // Order matters: more specific first
        let kernel_paths = [
            "/live/vmlinuz",             // Tails, Debian Live
            "/casper/vmlinuz",           // Ubuntu
            "/isolinux/vmlinuz",         // Generic syslinux
            "/boot/vmlinuz",             // Alpine
            "/images/pxeboot/vmlinuz",   // Fedora
            "/boot/x86_64/loader/linux", // openSUSE
        ];

        let initrd_paths = [
            "/live/initrd.img",           // Tails, Debian Live
            "/casper/initrd",             // Ubuntu (no extension)
            "/casper/initrd.lz",          // Ubuntu compressed
            "/isolinux/initrd.img",       // Generic syslinux
            "/boot/initramfs",            // Alpine
            "/images/pxeboot/initrd.img", // Fedora
            "/boot/x86_64/loader/initrd", // openSUSE
        ];

        let mut found_kernel = None;
        let mut found_initrd = None;

        for path in kernel_paths.iter() {
            if iso9660::find_file(&mut adapter, &volume, path).is_ok() {
                found_kernel = Some(*path);
                break;
            }
        }

        for path in initrd_paths.iter() {
            if iso9660::find_file(&mut adapter, &volume, path).is_ok() {
                found_initrd = Some(*path);
                break;
            }
        }

        (found_kernel, found_initrd)
    } else {
        // Fallback to standard paths
        (Some("/boot/vmlinuz"), Some("/boot/initrd.img"))
    };

    let kernel_path = kernel_path.ok_or(IsoBootError::KernelNotFound)?;

    screen.put_str_at(
        5,
        log_y,
        "Loading kernel from ISO...",
        EFI_LIGHTGREEN,
        EFI_BLACK,
    );
    screen.put_str_at(7, log_y + 1, kernel_path, EFI_YELLOW, EFI_BLACK);
    log_y += 2;

    // Read kernel
    let kernel_file = iso9660::find_file(&mut adapter, &volume, kernel_path)
        .map_err(|_| IsoBootError::KernelNotFound)?;
    let kernel_data = iso9660::read_file_vec(&mut adapter, &kernel_file)
        .map_err(|_| IsoBootError::KernelReadFailed)?;

    // Read initrd if available
    let initrd_data: Option<Vec<u8>> = if let Some(path) = initrd_path {
        screen.put_str_at(
            5,
            log_y,
            "Loading initrd from ISO...",
            EFI_LIGHTGREEN,
            EFI_BLACK,
        );
        screen.put_str_at(7, log_y + 1, path, EFI_YELLOW, EFI_BLACK);
        log_y += 2;

        match iso9660::find_file(&mut adapter, &volume, path) {
            Ok(file) => match iso9660::read_file_vec(&mut adapter, &file) {
                Ok(data) => Some(data),
                Err(_) => None,
            },
            Err(_) => None,
        }
    } else {
        None
    };

    screen.put_str_at(5, log_y, "Booting kernel...", EFI_LIGHTGREEN, EFI_BLACK);
    log_y += 1;

    // Boot the kernel
    let result = boot_linux_kernel(
        boot_services,
        system_table,
        image_handle,
        &kernel_data,
        initrd_data.as_deref(),
        cmdline,
        screen,
    );

    result.map_err(IsoBootError::BootFailed)
}

/// Get default command line for a distro
///
/// Returns appropriate boot parameters based on ISO name.
pub fn default_cmdline_for_iso(iso_name: &str) -> &'static str {
    let name_lower = iso_name.as_bytes();

    // Check for common distros
    if contains_ignore_case(name_lower, b"tails") {
        return "boot=live noautologin";
    }
    if contains_ignore_case(name_lower, b"ubuntu") {
        return "boot=casper quiet splash";
    }
    if contains_ignore_case(name_lower, b"debian") {
        return "boot=live quiet";
    }
    if contains_ignore_case(name_lower, b"kali") {
        return "boot=live noconfig=sudo username=kali";
    }
    if contains_ignore_case(name_lower, b"fedora") {
        return "rd.live.image quiet";
    }
    if contains_ignore_case(name_lower, b"arch") {
        return "archisolabel=ARCH";
    }
    if contains_ignore_case(name_lower, b"alpine") {
        return "modules=loop,squashfs quiet";
    }

    // Generic fallback
    "boot=live quiet"
}

/// Case-insensitive substring check (no_std friendly)
fn contains_ignore_case(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.len() > haystack.len() {
        return false;
    }

    for i in 0..=(haystack.len() - needle.len()) {
        let mut matches = true;
        for j in 0..needle.len() {
            let h = haystack[i + j].to_ascii_lowercase();
            let n = needle[j].to_ascii_lowercase();
            if h != n {
                matches = false;
                break;
            }
        }
        if matches {
            return true;
        }
    }
    false
}