boxlite 0.9.3

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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
mod binary_finder;
pub mod process;

pub use binary_finder::{RuntimeBinaryFinder, find_binary};

use std::path::PathBuf;
use std::process::Command;

use boxlite_shared::errors::{BoxliteError, BoxliteResult};
use tracing_appender::non_blocking::NonBlocking;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, fmt};

pub use process::{
    ProcessExit, ProcessMonitor, is_process_alive, is_same_process, kill_process, read_pid_file,
};

#[cfg(any(target_os = "linux", target_os = "macos"))]
unsafe extern "C" {
    fn dladdr(addr: *const libc::c_void, info: *mut libc::Dl_info) -> libc::c_int;
}

pub(super) struct LibraryLoadPath;

impl LibraryLoadPath {
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    fn get_library_path_via_dladdr(
        default_addr: *const libc::c_void,
        addr: Option<*const libc::c_void>,
    ) -> Option<PathBuf> {
        use libc::Dl_info;
        use std::ffi::CStr;

        let mut info: Dl_info = unsafe { std::mem::zeroed() };
        let result = unsafe { dladdr(addr.unwrap_or(default_addr), &mut info) };

        if result != 0 && !info.dli_fname.is_null() {
            let c_str = unsafe { CStr::from_ptr(info.dli_fname) };
            let path = c_str.to_string_lossy().into_owned();
            Some(PathBuf::from(path))
        } else {
            None
        }
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    fn get(addr: Option<*const libc::c_void>) -> Option<PathBuf> {
        Self::get_library_path_via_dladdr(Self::get as *const libc::c_void, addr)
    }

    #[cfg(target_os = "windows")]
    fn get(addr: Option<*const libc::c_void>) -> Option<PathBuf> {
        use std::ffi::OsString;
        use std::os::windows::ffi::OsStringExt;
        use std::ptr;
        use winapi::um::libloaderapi::GetModuleFileNameW;
        use winapi::um::libloaderapi::GetModuleHandleExW;
        use winapi::um::winnt::HANDLE;

        let mut handle: HANDLE = ptr::null_mut();
        let flags = 0x00000004; // GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
        let ok = unsafe {
            GetModuleHandleExW(
                flags,
                addr.unwrap_or(Self::get as *const libc::c_void),
                &mut handle,
            )
        };
        if ok == 0 {
            return None;
        }

        let mut buffer = [0u16; 260];
        let len = unsafe { GetModuleFileNameW(handle, buffer.as_mut_ptr(), buffer.len() as u32) };
        if len == 0 {
            return None;
        }

        Some(PathBuf::from(OsString::from_wide(&buffer[..len as usize])))
    }
}

/// Configure dynamic library search paths for the Box runner command.
///
/// This ensures engine libraries bundled alongside the runner are
/// discoverable when the subprocess starts. Adds paths from both
/// dladdr-based detection and the embedded runtime cache.
pub fn configure_library_env(cmd: &mut Command, addr: *const libc::c_void) {
    // Collect all library directories to add to search path
    let mut lib_dirs: Vec<PathBuf> = Vec::new();

    // 1. dladdr-based detection (libraries alongside the running binary)
    if let Some(runner_dir) = LibraryLoadPath::get(Some(addr))
        && let Some(dylibs) = runner_dir.parent()
        && dylibs.exists()
    {
        lib_dirs.push(dylibs.to_path_buf());
    }

    // 2. Embedded runtime cache (extracted include_bytes! binaries)
    #[cfg(feature = "embedded-runtime")]
    if let Some(runtime) = crate::runtime::embedded::EmbeddedRuntime::get() {
        lib_dirs.push(runtime.dir().to_path_buf());
    }

    if lib_dirs.is_empty() {
        return;
    }

    #[cfg(target_os = "macos")]
    {
        let mut paths: Vec<String> = lib_dirs.iter().map(|d| d.display().to_string()).collect();
        if let Ok(existing) = std::env::var("DYLD_FALLBACK_LIBRARY_PATH") {
            paths.push(existing);
        }
        let fallback_path = paths.join(":");
        cmd.env("DYLD_FALLBACK_LIBRARY_PATH", &fallback_path);
        tracing::debug!(path = %fallback_path, "Set DYLD_FALLBACK_LIBRARY_PATH");
    }

    #[cfg(target_os = "linux")]
    {
        let mut paths: Vec<String> = lib_dirs.iter().map(|d| d.display().to_string()).collect();
        if let Ok(existing) = std::env::var("LD_LIBRARY_PATH") {
            paths.push(existing);
        }
        let lib_path = paths.join(":");
        cmd.env("LD_LIBRARY_PATH", &lib_path);
        tracing::debug!(path = %lib_path, "Set LD_LIBRARY_PATH");
    }
}

pub fn register_to_tracing(non_blocking: NonBlocking, env_filter: EnvFilter) {
    let _ = tracing_subscriber::registry()
        .with(env_filter)
        .with(
            fmt::layer()
                .with_writer(non_blocking)
                .with_target(true)
                .with_thread_ids(false)
                .with_file(false)
                .with_line_number(false)
                .with_ansi(false),
        )
        .try_init();
}

/// Inject guest binary into a rootfs directory.
///
/// Copies boxlite-guest into `/boxlite/bin/` so it can be executed
/// directly without needing a virtiofs mount at boot time.
///
/// Uses fast mtime+size comparison to avoid unnecessary copies.
/// The binary is only copied if:
/// - It doesn't exist in the destination
/// - The sizes differ
/// - The source is newer than the destination
pub fn inject_guest_binary(rootfs_path: &std::path::Path) -> BoxliteResult<()> {
    let dest_dir = rootfs_path.join("boxlite/bin");
    let dest_path = dest_dir.join("boxlite-guest");
    let guest_bin = find_binary("boxlite-guest")?;

    // Check if binary needs update
    if dest_path.exists() {
        if is_binary_up_to_date(&guest_bin, &dest_path)? {
            return Ok(());
        }
        // Remove old binary before copying (it might be read-only 0o555)
        std::fs::remove_file(&dest_path).map_err(|e| {
            BoxliteError::Storage(format!(
                "Failed to remove old guest binary {}: {}",
                dest_path.display(),
                e
            ))
        })?;
    }

    std::fs::create_dir_all(&dest_dir).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to create guest bin directory {}: {}",
            dest_dir.display(),
            e
        ))
    })?;

    std::fs::copy(&guest_bin, &dest_path).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to copy guest binary to {}: {}",
            dest_path.display(),
            e
        ))
    })?;

    // Ensure executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&dest_path, std::fs::Permissions::from_mode(0o555)).map_err(
            |e| {
                BoxliteError::Storage(format!(
                    "Failed to set permissions on {}: {}",
                    dest_path.display(),
                    e
                ))
            },
        )?;
    }

    tracing::info!("Injected guest binary into {}", dest_path.display());
    Ok(())
}

/// Check if destination binary is up-to-date compared to source.
///
/// Uses fast mtime+size comparison instead of content hashing.
fn is_binary_up_to_date(source: &std::path::Path, dest: &std::path::Path) -> BoxliteResult<bool> {
    let source_meta = std::fs::metadata(source).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to get metadata for {}: {}",
            source.display(),
            e
        ))
    })?;

    let dest_meta = std::fs::metadata(dest).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to get metadata for {}: {}",
            dest.display(),
            e
        ))
    })?;

    // Quick rejection: different sizes means definitely different content
    if source_meta.len() != dest_meta.len() {
        tracing::debug!(
            "Guest binary size changed ({} -> {} bytes)",
            dest_meta.len(),
            source_meta.len()
        );
        return Ok(false);
    }

    // Compare modification times
    let source_mtime = source_meta.modified().map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to get mtime for {}: {}",
            source.display(),
            e
        ))
    })?;

    let dest_mtime = dest_meta.modified().map_err(|e| {
        BoxliteError::Storage(format!("Failed to get mtime for {}: {}", dest.display(), e))
    })?;

    if dest_mtime >= source_mtime {
        tracing::debug!(
            "Guest binary at {} is up-to-date (size: {} bytes)",
            dest.display(),
            dest_meta.len()
        );
        return Ok(true);
    }

    tracing::debug!("Guest binary source is newer than destination");
    Ok(false)
}

/// Auto-detect terminal size like Docker does
/// Returns (rows, cols) tuple
pub fn get_terminal_size() -> (u32, u32) {
    // Try to get terminal size from environment or use standard defaults
    if let Some((cols, rows)) = term_size::dimensions() {
        (rows as u32, cols as u32)
    } else {
        // Standard terminal size (80x24)
        (24, 80)
    }
}

/// Check if string contains only printable ASCII characters.
///
/// Returns `true` if every character is in the range ' '..='~' (ASCII 32-126).
/// This range matches what libkrun's kernel cmdline accepts.
///
/// # Examples
/// ```
/// assert!(is_printable_ascii("hello"));
/// assert!(is_printable_ascii("PATH=/usr/bin"));
/// assert!(!is_printable_ascii("日本語"));  // Non-ASCII
/// assert!(!is_printable_ascii("hello\t"));  // Tab is below space
/// ```
pub fn is_printable_ascii(s: &str) -> bool {
    s.chars().all(|c| matches!(c, ' '..='~'))
}

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

    #[test]
    fn test_is_printable_ascii() {
        // Valid: printable ASCII (space through tilde)
        assert!(is_printable_ascii("hello"));
        assert!(is_printable_ascii("Hello World!"));
        assert!(is_printable_ascii("PATH=/usr/bin:/bin"));
        assert!(is_printable_ascii("key=value with spaces"));
        assert!(is_printable_ascii(" ")); // Space (ASCII 32)
        assert!(is_printable_ascii("~")); // Tilde (ASCII 126)
        assert!(is_printable_ascii("")); // Empty string is valid

        // Invalid: non-ASCII characters
        assert!(!is_printable_ascii("➜")); // Unicode arrow
        assert!(!is_printable_ascii("hello ➜ world")); // Mixed
        assert!(!is_printable_ascii("José")); // Accented character
        assert!(!is_printable_ascii("日本語")); // Japanese
        assert!(!is_printable_ascii("emoji 🎉")); // Emoji

        // Invalid: control characters (below space)
        assert!(!is_printable_ascii("\t")); // Tab (ASCII 9)
        assert!(!is_printable_ascii("\n")); // Newline (ASCII 10)
        assert!(!is_printable_ascii("\x00")); // Null (ASCII 0)
        assert!(!is_printable_ascii("\x1b")); // Escape (ASCII 27)

        // Invalid: DEL and above
        assert!(!is_printable_ascii("\x7f")); // DEL (ASCII 127)
    }

    #[test]
    fn test_xattr_format_with_leading_zeros() {
        // Test that xattr values are formatted with 4-digit octal (leading zeros)
        let test_cases = vec![
            (0o755, "0:0:0755"),  // rwxr-xr-x
            (0o644, "0:0:0644"),  // rw-r--r--
            (0o700, "0:0:0700"),  // rwx------
            (0o555, "0:0:0555"),  // r-xr-xr-x
            (0o777, "0:0:0777"),  // rwxrwxrwx
            (0o000, "0:0:0000"),  // ---------
            (0o4755, "0:0:4755"), // rwsr-xr-x (setuid)
            (0o2755, "0:0:2755"), // rwxr-sr-x (setgid)
            (0o1755, "0:0:1755"), // rwxr-xr-t (sticky)
        ];

        for (mode, expected) in test_cases {
            let actual = format!("0:0:{:04o}", mode & 0o7777);
            assert_eq!(
                actual, expected,
                "Mode {:o} should format to '{}', got '{}'",
                mode, expected, actual
            );
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_fix_rootfs_permissions_basic() {
        use crate::rootfs::operations::fix_rootfs_permissions;
        use std::fs;
        use std::os::unix::fs::PermissionsExt;
        use std::path::Path;
        use tempfile::TempDir;

        // Create a temporary directory structure
        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path();

        // Set rootfs to 0700 (like a real rootfs would be)
        let mut perms = fs::metadata(rootfs).unwrap().permissions();
        perms.set_mode(0o700);
        fs::set_permissions(rootfs, perms).unwrap();

        // Create test files with different permissions
        let file1 = rootfs.join("executable");
        fs::write(&file1, "#!/bin/sh\necho test").unwrap();
        let mut perms = fs::metadata(&file1).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&file1, perms).unwrap();

        let file2 = rootfs.join("readonly");
        fs::write(&file2, "data").unwrap();
        let mut perms = fs::metadata(&file2).unwrap().permissions();
        perms.set_mode(0o444);
        fs::set_permissions(&file2, perms).unwrap();

        let dir = rootfs.join("subdir");
        fs::create_dir(&dir).unwrap();
        let mut perms = fs::metadata(&dir).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&dir, perms).unwrap();

        // Create a symlink
        #[cfg(unix)]
        {
            use std::os::unix::fs::symlink;
            symlink(&file1, rootfs.join("link")).unwrap();
        }

        // Run the fix_rootfs_permissions function
        let result = fix_rootfs_permissions(rootfs);
        assert!(
            result.is_ok(),
            "fix_rootfs_permissions failed: {:?}",
            result.err()
        );

        // Verify xattr was set on regular files and directories
        let check_xattr = |path: &Path, expected_mode: u32| {
            let xattr_value = xattr::get(path, "user.containers.override_stat")
                .unwrap_or_else(|_| panic!("Failed to read xattr from {:?}", path))
                .unwrap_or_else(|| panic!("xattr not set on {:?}", path));
            let expected = format!("0:0:{:04o}", expected_mode);
            assert_eq!(
                String::from_utf8_lossy(&xattr_value),
                expected,
                "xattr mismatch for {:?}",
                path
            );
        };

        // Root directory should be 700
        check_xattr(rootfs, 0o700);

        // Executable should preserve 755
        check_xattr(&file1, 0o755);

        // Readonly should preserve 444
        check_xattr(&file2, 0o444);

        // Directory should preserve 755
        check_xattr(&dir, 0o755);

        // Verify symlinks don't get xattr (skipped intentionally)
        let symlink_path = rootfs.join("link");
        let symlink_xattr = xattr::get(&symlink_path, "user.containers.override_stat").unwrap();
        assert!(
            symlink_xattr.is_none(),
            "Symlinks should not have xattr set"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn test_fix_rootfs_permissions_preserves_setuid() {
        use crate::rootfs::operations::fix_rootfs_permissions;
        use std::fs;
        use std::os::unix::fs::PermissionsExt;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let rootfs = temp_dir.path();

        // Create a file with setuid bit
        let setuid_file = rootfs.join("setuid_binary");
        fs::write(&setuid_file, "binary").unwrap();
        let mut perms = fs::metadata(&setuid_file).unwrap().permissions();
        perms.set_mode(0o4755); // setuid + rwxr-xr-x
        fs::set_permissions(&setuid_file, perms).unwrap();

        // Run fix_rootfs_permissions
        fix_rootfs_permissions(rootfs).unwrap();

        // Verify setuid bit is preserved in xattr
        let xattr_value = xattr::get(&setuid_file, "user.containers.override_stat")
            .unwrap()
            .expect("xattr not set");
        assert_eq!(
            String::from_utf8_lossy(&xattr_value),
            "0:0:4755",
            "Setuid bit should be preserved in xattr"
        );
    }
}