boxlite 0.9.2

Embeddable virtual machine runtime for secure, isolated code execution
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use crate::util;
use boxlite_shared::{BoxliteError, BoxliteResult};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use walkdir::WalkDir;

use super::constants::ext4::{
    BLOCK_SIZE, DEFAULT_DIR_SIZE_BYTES, INODE_SIZE, JOURNAL_OVERHEAD_BYTES, MIN_DISK_SIZE_BYTES,
    SIZE_MULTIPLIER_DEN, SIZE_MULTIPLIER_NUM,
};
use super::{Disk, DiskFormat};

/// Get the path to the mke2fs binary.
fn get_mke2fs_path() -> PathBuf {
    util::find_binary("mke2fs").expect("mke2fs binary not found")
}

/// Get the path to the debugfs binary.
fn get_debugfs_path() -> PathBuf {
    util::find_binary("debugfs").expect("debugfs binary not found")
}

/// Calculate the total size needed for a directory tree on ext4.
///
/// This accounts for:
/// - File content sizes (rounded up to 4KB blocks)
/// - Inode overhead (256 bytes per file/dir/symlink)
/// - Directory entry overhead
fn calculate_dir_size(dir: &Path) -> BoxliteResult<u64> {
    let mut total_blocks = 0u64;
    let mut entry_count = 0u64;

    for entry in WalkDir::new(dir).follow_links(false) {
        let entry = entry.map_err(|e| {
            BoxliteError::Storage(format!("Failed to walk directory {}: {}", dir.display(), e))
        })?;

        entry_count += 1;

        if let Ok(metadata) = entry.metadata() {
            if metadata.is_file() {
                // Each file needs at least one block, round up
                let file_blocks = metadata.len().div_ceil(BLOCK_SIZE);
                total_blocks += file_blocks.max(1);
            } else if metadata.is_dir() {
                // Directories need at least one block
                total_blocks += 1;
            }
        }
    }

    // Calculate total:
    // - Block storage
    // - Inode storage (entry_count * INODE_SIZE, rounded to blocks)
    let content_size = total_blocks * BLOCK_SIZE;
    let inode_size = entry_count * INODE_SIZE;

    Ok(content_size + inode_size)
}

/// Calculate appropriate disk size with ext4 overhead.
fn calculate_disk_size(source: &Path) -> u64 {
    let dir_size = calculate_dir_size(source).unwrap_or(DEFAULT_DIR_SIZE_BYTES);

    // ext4 overhead:
    // - Metadata (superblock, block groups, inode tables): ~1-5%
    // - Journal: 64MB
    // - We set reserved blocks to 0% via mke2fs
    // Use 1.1x multiplier (10% overhead) plus 64MB for journal
    // Testing showed ~0.5% overhead needed, 10% provides safety margin
    let size_with_overhead =
        dir_size * SIZE_MULTIPLIER_NUM / SIZE_MULTIPLIER_DEN + JOURNAL_OVERHEAD_BYTES;

    // Minimum 256MB for small images
    let final_size = size_with_overhead.max(MIN_DISK_SIZE_BYTES);

    tracing::debug!(
        "Calculated disk size: dir_size={}MB, with_overhead={}MB, final={}MB",
        dir_size / (1024 * 1024),
        size_with_overhead / (1024 * 1024),
        final_size / (1024 * 1024)
    );

    final_size
}

/// Create an ext4 disk image from a directory using mke2fs.
///
/// This uses the `mke2fs -d` option to populate the filesystem directly
/// from a source directory, which is much simpler than using libext2fs.
///
/// Size is automatically calculated based on directory contents with
/// appropriate overhead for ext4 metadata, journal, and reserved blocks.
///
/// Returns a non-persistent Disk (will be cleaned up on drop).
pub fn create_ext4_from_dir(source: &Path, output_path: &Path) -> BoxliteResult<Disk> {
    let size_bytes = calculate_disk_size(source);

    // With -b 4096, mke2fs expects size in 4KB blocks
    let size_blocks = size_bytes / 4096;

    let output_str = output_path.to_str().ok_or_else(|| {
        BoxliteError::Storage(format!("Invalid output path: {}", output_path.display()))
    })?;

    let source_str = source.to_str().ok_or_else(|| {
        BoxliteError::Storage(format!("Invalid source path: {}", source.display()))
    })?;

    let mke2fs = get_mke2fs_path();

    // Use mke2fs with -d to populate from directory
    // https://man7.org/linux/man-pages/man8/mke2fs.8.html
    // -t ext4: create ext4 filesystem
    // -d dir: populate from directory
    // -m 0: no reserved blocks (default 5% is wasted for containers)
    // -E root_owner=0:0: set root ownership (important for containers)
    let output = Command::new(&mke2fs)
        .args([
            "-t",
            "ext4",
            "-b",
            "4096", // 4KB block size (explicit)
            "-d",
            source_str,
            "-m",
            "0",
            "-E",
            "root_owner=0:0",
            "-F", // Force, don't ask questions
            "-q", // Quiet
            output_str,
            &size_blocks.to_string(),
        ])
        .output()
        .map_err(|e| {
            BoxliteError::Storage(format!(
                "Failed to run mke2fs ({}): {}",
                mke2fs.display(),
                e
            ))
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(BoxliteError::Storage(format!(
            "mke2fs failed with exit code {:?}: {}",
            output.status.code(),
            stderr
        )));
    }

    // Fix ownership of all files to 0:0 using debugfs
    fix_ownership_with_debugfs(output_path, source)?;

    Ok(Disk::new(
        output_path.to_path_buf(),
        DiskFormat::Ext4,
        false,
    ))
}

/// Fix ownership of all files in ext4 image to 0:0 using debugfs.
///
/// mke2fs -E root_owner=0:0 only sets the root inode.
/// This function fixes all other files/directories.
fn fix_ownership_with_debugfs(image_path: &Path, source_dir: &Path) -> BoxliteResult<()> {
    // Skip if already running as root - mke2fs creates files with current uid/gid
    let current_uid = unsafe { libc::getuid() };
    let current_gid = unsafe { libc::getgid() };
    if current_uid == 0 && current_gid == 0 {
        tracing::debug!("Running as root, skipping debugfs ownership fix");
        return Ok(());
    }

    let start = std::time::Instant::now();

    // Collect all paths relative to source_dir
    let mut paths = Vec::new();
    for entry in WalkDir::new(source_dir).follow_links(false) {
        let entry =
            entry.map_err(|e| BoxliteError::Storage(format!("Failed to walk directory: {}", e)))?;

        // Get path relative to source_dir
        let rel_path = entry
            .path()
            .strip_prefix(source_dir)
            .unwrap_or(entry.path());

        // Skip root (already handled by root_owner=0:0)
        if rel_path.as_os_str().is_empty() {
            continue;
        }

        // Convert to absolute path in ext4 (starting with /)
        let ext4_path = format!("/{}", rel_path.display());
        paths.push(ext4_path);
    }

    if paths.is_empty() {
        tracing::debug!("No files to fix ownership for");
        return Ok(());
    }

    // Build debugfs commands to set uid=0 and gid=0 for each file
    // Using sif (set inode field) command: sif <path> <field> <value>
    let mut commands = String::new();
    for path in &paths {
        // sif sets inode field by path
        commands.push_str(&format!("sif {} uid 0\n", path));
        commands.push_str(&format!("sif {} gid 0\n", path));
    }

    let debugfs = get_debugfs_path();

    // Run debugfs with commands via stdin
    let mut child = Command::new(&debugfs)
        .args(["-w", "-f", "-"])
        .arg(image_path)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| BoxliteError::Storage(format!("Failed to spawn debugfs: {}", e)))?;

    // Write commands to stdin
    if let Some(mut stdin) = child.stdin.take() {
        stdin.write_all(commands.as_bytes()).map_err(|e| {
            BoxliteError::Storage(format!("Failed to write to debugfs stdin: {}", e))
        })?;
    }

    let output = child
        .wait_with_output()
        .map_err(|e| BoxliteError::Storage(format!("Failed to wait for debugfs: {}", e)))?;

    let duration = start.elapsed();

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        tracing::warn!(
            "debugfs ownership fix had errors (took {:?}): {}",
            duration,
            stderr
        );
    } else {
        tracing::info!(
            "Fixed ownership of {} files to 0:0 in {:?}",
            paths.len(),
            duration
        );
    }

    Ok(())
}

/// Inject a host file into an ext4 disk image using debugfs.
///
/// Creates parent directories as needed within the ext4 image,
/// writes the file, and sets ownership to root (0:0) with mode 0555.
///
/// # Arguments
/// * `image_path` - Path to the ext4 disk image file
/// * `host_file` - Path to the file on the host to inject
/// * `guest_path` - Destination path inside the ext4 image (e.g. "boxlite/bin/boxlite-guest")
pub fn inject_file_into_ext4(
    image_path: &Path,
    host_file: &Path,
    guest_path: &str,
) -> BoxliteResult<()> {
    let host_file_str = host_file.to_str().ok_or_else(|| {
        BoxliteError::Storage(format!("Invalid host file path: {}", host_file.display()))
    })?;

    let commands = build_inject_commands(host_file_str, guest_path);

    let debugfs = get_debugfs_path();

    let mut child = Command::new(&debugfs)
        .args(["-w", "-f", "-"])
        .arg(image_path)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| {
            BoxliteError::Storage(format!("Failed to spawn debugfs for injection: {}", e))
        })?;

    if let Some(mut stdin) = child.stdin.take() {
        stdin.write_all(commands.as_bytes()).map_err(|e| {
            BoxliteError::Storage(format!("Failed to write to debugfs stdin: {}", e))
        })?;
    }

    let output = child
        .wait_with_output()
        .map_err(|e| BoxliteError::Storage(format!("Failed to wait for debugfs: {}", e)))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(BoxliteError::Storage(format!(
            "debugfs injection failed for {} -> {}: {}",
            host_file.display(),
            guest_path,
            stderr
        )));
    }

    tracing::debug!(
        "Injected {} into ext4 image at /{}",
        host_file.display(),
        guest_path
    );

    Ok(())
}

/// Build debugfs commands for injecting a file into an ext4 image.
///
/// Creates parent directories, writes the file, and sets ownership/mode.
/// Separated from `inject_file_into_ext4` for testability.
fn build_inject_commands(host_file_str: &str, guest_path: &str) -> String {
    let mut commands = String::new();

    // Create parent directories
    let guest_path_obj = Path::new(guest_path);
    let mut current = PathBuf::new();
    if let Some(parent) = guest_path_obj.parent() {
        for component in parent.components() {
            current.push(component);
            commands.push_str(&format!("mkdir /{}\n", current.display()));
        }
    }

    // Write host file into ext4 image (quote source path for spaces, e.g. macOS "Application Support")
    let ext4_dest = format!("/{}", guest_path);
    commands.push_str(&format!("write \"{}\" {}\n", host_file_str, ext4_dest));

    // Set ownership (uid=0, gid=0) and mode (0555 = r-xr-xr-x)
    commands.push_str(&format!("sif {} uid 0\n", ext4_dest));
    commands.push_str(&format!("sif {} gid 0\n", ext4_dest));
    commands.push_str(&format!("sif {} mode 0100555\n", ext4_dest));

    // Set ownership on parent directories too
    let mut current = PathBuf::new();
    if let Some(parent) = guest_path_obj.parent() {
        for component in parent.components() {
            current.push(component);
            let dir_path = format!("/{}", current.display());
            commands.push_str(&format!("sif {} uid 0\n", dir_path));
            commands.push_str(&format!("sif {} gid 0\n", dir_path));
        }
    }

    commands
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_inject_commands_nested_path() {
        let cmds = build_inject_commands("/host/boxlite-guest", "boxlite/bin/boxlite-guest");

        // Should create parent dirs: boxlite, boxlite/bin
        assert!(cmds.contains("mkdir /boxlite\n"));
        assert!(cmds.contains("mkdir /boxlite/bin\n"));

        // Should write the file (source path quoted for spaces)
        assert!(cmds.contains("write \"/host/boxlite-guest\" /boxlite/bin/boxlite-guest\n"));

        // Should set file permissions
        assert!(cmds.contains("sif /boxlite/bin/boxlite-guest uid 0\n"));
        assert!(cmds.contains("sif /boxlite/bin/boxlite-guest gid 0\n"));
        assert!(cmds.contains("sif /boxlite/bin/boxlite-guest mode 0100555\n"));

        // Should set parent dir ownership
        assert!(cmds.contains("sif /boxlite uid 0\n"));
        assert!(cmds.contains("sif /boxlite gid 0\n"));
        assert!(cmds.contains("sif /boxlite/bin uid 0\n"));
        assert!(cmds.contains("sif /boxlite/bin gid 0\n"));
    }

    #[test]
    fn test_build_inject_commands_single_dir() {
        let cmds = build_inject_commands("/host/file", "dir/file");

        assert!(cmds.contains("mkdir /dir\n"));
        assert!(cmds.contains("write \"/host/file\" /dir/file\n"));
        assert!(cmds.contains("sif /dir uid 0\n"));
        assert!(cmds.contains("sif /dir gid 0\n"));
    }

    #[test]
    fn test_build_inject_commands_root_level_file() {
        let cmds = build_inject_commands("/host/file", "file");

        // No mkdir commands for root-level file
        assert!(!cmds.contains("mkdir"));

        // Should still write and set permissions
        assert!(cmds.contains("write \"/host/file\" /file\n"));
        assert!(cmds.contains("sif /file uid 0\n"));
        assert!(cmds.contains("sif /file gid 0\n"));
        assert!(cmds.contains("sif /file mode 0100555\n"));
    }

    #[test]
    fn test_build_inject_commands_deeply_nested() {
        let cmds = build_inject_commands("/src/bin", "a/b/c/d/bin");

        assert!(cmds.contains("mkdir /a\n"));
        assert!(cmds.contains("mkdir /a/b\n"));
        assert!(cmds.contains("mkdir /a/b/c\n"));
        assert!(cmds.contains("mkdir /a/b/c/d\n"));
        assert!(cmds.contains("write \"/src/bin\" /a/b/c/d/bin\n"));
    }

    #[test]
    fn test_build_inject_commands_path_with_spaces() {
        let cmds = build_inject_commands(
            "/Users/user/Library/Application Support/boxlite/runtimes/v0.6.0/boxlite-guest",
            "boxlite/bin/boxlite-guest",
        );

        // Source path must be quoted so debugfs handles the space correctly
        assert!(cmds.contains(
            "write \"/Users/user/Library/Application Support/boxlite/runtimes/v0.6.0/boxlite-guest\" /boxlite/bin/boxlite-guest\n"
        ));
    }
}