arcbox-vm 0.4.10

Guest-side Firecracker sandbox manager (frozen; see arcbox-vmm for host VMM).
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! `vmm-guest-agent` — in-VM daemon that accepts exec/run sessions over vsock.
//!
//! The agent listens on AF_VSOCK port 52.  For each connection it:
//!
//! 1. Reads an initial `MSG_START` frame carrying a JSON [`StartCommand`].
//! 2. Spawns the requested process (with pipes for non-TTY, with openpty for TTY).
//! 3. Streams `MSG_STDOUT` / `MSG_STDERR` frames back to the host.
//! 4. For interactive sessions, forwards `MSG_STDIN` / `MSG_RESIZE` frames to
//!    the process.
//! 5. Sends a final `MSG_EXIT` frame when the process terminates.
//!
//! ## Frame format
//!
//! ```text
//! [u8: msg_type][u32 LE: payload_len][payload_len bytes]
//! ```
//!
//! | Type | Direction   | Payload                          |
//! |------|-------------|----------------------------------|
//! | 0x01 | Host→Agent  | JSON `StartCommand`              |
//! | 0x02 | Host→Agent  | raw stdin bytes                  |
//! | 0x03 | Host→Agent  | `[u16 LE width][u16 LE height]`  |
//! | 0x04 | Host→Agent  | empty — stdin EOF                |
//! | 0x10 | Agent→Host  | raw stdout bytes                 |
//! | 0x11 | Agent→Host  | raw stderr bytes                 |
//! | 0x12 | Agent→Host  | `[i32 LE exit_code]`             |
//!
//! This binary requires Linux — it uses AF_VSOCK, accept4, openpty, and fork,
//! none of which are available on other platforms.  The workspace compiles the
//! crate everywhere, but the implementation is gated on `target_os = "linux"`.

// =============================================================================
// Linux implementation
// =============================================================================

#[cfg(target_os = "linux")]
mod agent {
    use std::collections::HashMap;
    use std::io::{Read, Write};
    use std::os::unix::io::RawFd;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use std::thread;

    use serde::Deserialize;

    // -------------------------------------------------------------------------
    // Protocol constants
    // -------------------------------------------------------------------------

    pub const AGENT_PORT: u32 = 52;

    // Exec channel (vsock:52) frame types.
    const MSG_START: u8 = 0x01;
    const MSG_STDIN: u8 = 0x02;
    const MSG_RESIZE: u8 = 0x03;
    const MSG_EOF: u8 = 0x04;
    const MSG_CLOCK_SYNC: u8 = 0x05;
    const MSG_STDOUT: u8 = 0x10;
    const MSG_STDERR: u8 = 0x11;
    const MSG_EXIT: u8 = 0x12;

    // File I/O channel (vsock:53) — imported from the shared proto module.
    use arcbox_vm::boot_proto::KernelIpParam;
    use arcbox_vm::file_io::proto::{
        FILE_ACK, FILE_DATA, FILE_DONE, FILE_ERR, FILE_PORT, FILE_READ_REQ, FILE_WRITE_REQ,
        MAX_FILE_SIZE,
    };

    const MAX_FRAME_SIZE: usize = 16 * 1024 * 1024;

    /// Maximum number of concurrently active connection-handling threads.
    /// Prevents memory exhaustion during exec bursts (e.g. health checks).
    const MAX_ACTIVE_CONNECTIONS: usize = 64;

    /// Stack size for connection-handling threads (1 MB instead of the default 8 MB).
    const THREAD_STACK_SIZE: usize = 1 << 20;

    // -------------------------------------------------------------------------
    // Protocol types
    // -------------------------------------------------------------------------

    #[derive(Debug, Deserialize)]
    struct StartCommand {
        cmd: Vec<String>,
        #[serde(default)]
        env: HashMap<String, String>,
        #[serde(default)]
        working_dir: String,
        #[serde(default, rename = "user")]
        _user: String,
        #[serde(default)]
        tty: bool,
        #[serde(default = "default_tty_width")]
        tty_width: u16,
        #[serde(default = "default_tty_height")]
        tty_height: u16,
        #[serde(default)]
        timeout_seconds: u32,
    }

    fn default_tty_width() -> u16 {
        80
    }
    fn default_tty_height() -> u16 {
        24
    }

    // -------------------------------------------------------------------------
    // Framed I/O over a raw socket fd
    // -------------------------------------------------------------------------

    struct VsockStream {
        fd: RawFd,
    }

    impl VsockStream {
        /// # Safety
        /// `fd` must be a valid, open, connected socket file descriptor.
        unsafe fn from_raw_fd(fd: RawFd) -> Self {
            Self { fd }
        }
    }

    impl Read for VsockStream {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            // SAFETY: buf is a valid mutable slice; fd is a valid socket.
            let n =
                unsafe { libc::read(self.fd, buf.as_mut_ptr().cast::<libc::c_void>(), buf.len()) };
            if n < 0 {
                Err(std::io::Error::last_os_error())
            } else {
                Ok(n as usize)
            }
        }
    }

    impl Write for VsockStream {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            // SAFETY: buf is a valid slice; fd is a valid socket.
            let n = unsafe { libc::write(self.fd, buf.as_ptr().cast::<libc::c_void>(), buf.len()) };
            if n < 0 {
                Err(std::io::Error::last_os_error())
            } else {
                Ok(n as usize)
            }
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl Drop for VsockStream {
        fn drop(&mut self) {
            // SAFETY: fd is valid and owned by this struct.
            unsafe { libc::close(self.fd) };
        }
    }

    // -------------------------------------------------------------------------
    // Frame helpers
    // -------------------------------------------------------------------------

    fn read_frame(r: &mut impl Read) -> std::io::Result<(u8, Vec<u8>)> {
        let mut type_buf = [0u8; 1];
        r.read_exact(&mut type_buf)?;
        let mut len_buf = [0u8; 4];
        r.read_exact(&mut len_buf)?;
        let len = u32::from_le_bytes(len_buf) as usize;
        if len > MAX_FRAME_SIZE {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"),
            ));
        }
        let mut payload = vec![0u8; len];
        if len > 0 {
            r.read_exact(&mut payload)?;
        }
        Ok((type_buf[0], payload))
    }

    /// Write all bytes in a single call to avoid interleaving across threads.
    fn write_frame(w: &mut impl Write, msg_type: u8, payload: &[u8]) -> std::io::Result<()> {
        let mut buf = Vec::with_capacity(5 + payload.len());
        buf.push(msg_type);
        buf.extend_from_slice(&(payload.len() as u32).to_le_bytes());
        buf.extend_from_slice(payload);
        w.write_all(&buf)
    }

    // -------------------------------------------------------------------------
    // Per-connection handler
    // -------------------------------------------------------------------------

    fn handle_connection(conn_fd: RawFd) {
        // SAFETY: conn_fd is a freshly accepted socket fd.
        let mut conn = unsafe { VsockStream::from_raw_fd(conn_fd) };

        let (msg_type, payload) = match read_frame(&mut conn) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("agent: read first frame: {e}");
                return;
            }
        };

        match msg_type {
            MSG_CLOCK_SYNC => handle_clock_sync(conn, &payload),
            MSG_START => {
                let start: StartCommand = match serde_json::from_slice(&payload) {
                    Ok(s) => s,
                    Err(e) => {
                        eprintln!("agent: parse StartCommand: {e}");
                        return;
                    }
                };
                if start.tty {
                    handle_tty(conn, start);
                } else {
                    handle_piped(conn, start);
                }
            }
            other => {
                eprintln!("agent: unexpected frame type 0x{other:02x} on exec port");
            }
        }
    }

    fn handle_clock_sync(mut conn: VsockStream, payload: &[u8]) {
        if payload.len() < 12 {
            eprintln!(
                "agent: MSG_CLOCK_SYNC: payload too short ({} bytes)",
                payload.len()
            );
            let _ = write_frame(&mut conn, MSG_EXIT, &(-1i32).to_le_bytes());
            return;
        }
        let secs = i64::from_le_bytes(payload[..8].try_into().unwrap());
        let nanos = u32::from_le_bytes(payload[8..12].try_into().unwrap());

        // SAFETY: clock_settime requires CAP_SYS_TIME; vm-agent runs as root inside guest.
        let ret = unsafe {
            let ts = libc::timespec {
                tv_sec: secs,
                tv_nsec: libc::c_long::from(nanos),
            };
            libc::clock_settime(libc::CLOCK_REALTIME, &raw const ts)
        };
        if ret != 0 {
            eprintln!(
                "agent: clock_settime failed: {}",
                std::io::Error::last_os_error()
            );
            let _ = write_frame(&mut conn, MSG_EXIT, &(-1i32).to_le_bytes());
            return;
        }
        let _ = write_frame(&mut conn, MSG_EXIT, &0i32.to_le_bytes());
    }

    // -------------------------------------------------------------------------
    // File I/O handler (vsock:53)
    //
    // Trust model: the host is fully trusted — it owns and controls the VM.
    // The guest agent intentionally allows arbitrary file paths because only
    // the host can initiate vsock connections.
    // -------------------------------------------------------------------------

    fn handle_file_connection(conn_fd: RawFd) {
        // SAFETY: conn_fd is a freshly accepted socket fd.
        let mut conn = unsafe { VsockStream::from_raw_fd(conn_fd) };

        let (msg_type, payload) = match read_frame(&mut conn) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("agent: file: read first frame: {e}");
                return;
            }
        };

        match msg_type {
            FILE_WRITE_REQ => handle_file_write(conn, &payload),
            FILE_READ_REQ => handle_file_read(conn, &payload),
            other => eprintln!("agent: file: unexpected frame type 0x{other:02x}"),
        }
    }

    #[derive(serde::Deserialize)]
    struct WriteReq {
        path: String,
        #[serde(default)]
        mode: u32,
    }

    #[derive(serde::Deserialize)]
    struct ReadReq {
        path: String,
    }

    fn handle_file_write(mut conn: VsockStream, header_payload: &[u8]) {
        let req: WriteReq = match serde_json::from_slice(header_payload) {
            Ok(r) => r,
            Err(e) => {
                let _ = write_frame(
                    &mut conn,
                    FILE_ERR,
                    format!("parse WriteReq: {e}").as_bytes(),
                );
                return;
            }
        };
        let mode = if req.mode == 0 { 0o644 } else { req.mode };

        // Collect FILE_DATA chunks until FILE_DONE.
        let mut data: Vec<u8> = Vec::new();
        loop {
            match read_frame(&mut conn) {
                Ok((FILE_DATA, chunk)) => {
                    data.extend_from_slice(&chunk);
                    if data.len() > MAX_FILE_SIZE {
                        let _ = write_frame(
                            &mut conn,
                            FILE_ERR,
                            format!("file too large (>{} bytes)", MAX_FILE_SIZE).as_bytes(),
                        );
                        return;
                    }
                }
                Ok((FILE_DONE, _)) => break,
                Ok((other, _)) => {
                    let _ = write_frame(
                        &mut conn,
                        FILE_ERR,
                        format!("expected FILE_DATA/DONE, got 0x{other:02x}").as_bytes(),
                    );
                    return;
                }
                Err(e) => {
                    let _ = write_frame(&mut conn, FILE_ERR, format!("read data: {e}").as_bytes());
                    return;
                }
            }
        }

        let path = std::path::Path::new(&req.path);
        if let Some(parent) = path.parent()
            && let Err(e) = std::fs::create_dir_all(parent)
        {
            let _ = write_frame(&mut conn, FILE_ERR, format!("create dirs: {e}").as_bytes());
            return;
        }

        use std::os::unix::fs::OpenOptionsExt;
        let result = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(mode)
            .open(path)
            .and_then(|mut f| {
                use std::io::Write;
                f.write_all(&data)
            });

        match result {
            Ok(()) => {
                let _ = write_frame(&mut conn, FILE_ACK, &[]);
            }
            Err(e) => {
                let _ = write_frame(&mut conn, FILE_ERR, format!("write file: {e}").as_bytes());
            }
        }
    }

    fn handle_file_read(mut conn: VsockStream, header_payload: &[u8]) {
        let req: ReadReq = match serde_json::from_slice(header_payload) {
            Ok(r) => r,
            Err(e) => {
                let _ = write_frame(
                    &mut conn,
                    FILE_ERR,
                    format!("parse ReadReq: {e}").as_bytes(),
                );
                return;
            }
        };

        let data = match std::fs::read(&req.path) {
            Ok(d) => d,
            Err(e) => {
                let _ = write_frame(&mut conn, FILE_ERR, format!("read file: {e}").as_bytes());
                return;
            }
        };

        for chunk in data.chunks(MAX_FRAME_SIZE) {
            if write_frame(&mut conn, FILE_DATA, chunk).is_err() {
                return;
            }
        }
        let _ = write_frame(&mut conn, FILE_DONE, &[]);
    }

    // -------------------------------------------------------------------------
    // Non-interactive execution (piped stdio)
    // -------------------------------------------------------------------------

    fn handle_piped(conn: VsockStream, start: StartCommand) {
        use std::process::{Command, Stdio};

        let mut cmd = Command::new(start.cmd.first().expect("empty cmd"));
        cmd.args(start.cmd.get(1..).unwrap_or(&[]));
        cmd.envs(&start.env);
        if !start.working_dir.is_empty() {
            cmd.current_dir(&start.working_dir);
        }
        cmd.stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        let mut child = match cmd.spawn() {
            Ok(c) => c,
            Err(e) => {
                eprintln!("agent: spawn {:?}: {e}", start.cmd);
                return;
            }
        };

        let mut child_stdin = child.stdin.take().unwrap();
        let child_stdout = child.stdout.take().unwrap();
        let child_stderr = child.stderr.take().unwrap();

        // Shared writer so the stdout and stderr threads don't interleave frames.
        let writer: Arc<Mutex<VsockStream>> = Arc::new(Mutex::new(conn));

        let w1 = Arc::clone(&writer);
        let t_stdout = thread::spawn(move || {
            let mut buf = [0u8; 4096];
            let mut out = child_stdout;
            loop {
                match out.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        let _ = write_frame(&mut *w1.lock().unwrap(), MSG_STDOUT, &buf[..n]);
                    }
                }
            }
        });

        let w2 = Arc::clone(&writer);
        let t_stderr = thread::spawn(move || {
            let mut buf = [0u8; 4096];
            let mut err = child_stderr;
            loop {
                match err.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        let _ = write_frame(&mut *w2.lock().unwrap(), MSG_STDERR, &buf[..n]);
                    }
                }
            }
        });

        if start.timeout_seconds > 0 {
            let pid = child.id();
            let timeout = start.timeout_seconds;
            thread::spawn(move || {
                // Sleep for the configured timeout, then check if the process still exists
                // before attempting to send SIGKILL. This reduces the risk of killing a
                // different process if the PID has been recycled.
                thread::sleep(std::time::Duration::from_secs(timeout as u64));
                unsafe {
                    // Probe the process with signal 0. If this fails with ESRCH, the PID
                    // is not currently in use and we must not send SIGKILL.
                    #[allow(clippy::cast_possible_wrap)]
                    let pid_i32 = pid as i32;
                    if libc::kill(pid_i32, 0) == 0 {
                        let _ = libc::kill(pid_i32, libc::SIGKILL);
                    }
                }
            });
        }

        // Read stdin frames from the host and forward to the child.
        // SAFETY: dup gives us a second fd for reading while the Arc owns the write fd.
        let read_fd = unsafe { libc::dup(writer.lock().unwrap().fd) };
        let mut reader = unsafe { VsockStream::from_raw_fd(read_fd) };
        loop {
            match read_frame(&mut reader) {
                Ok((MSG_STDIN, data)) => {
                    if child_stdin.write_all(&data).is_err() {
                        break;
                    }
                }
                Ok((MSG_EOF, _)) | Err(_) => {
                    drop(child_stdin);
                    break;
                }
                Ok(_) => {}
            }
        }

        let _ = t_stdout.join();
        let _ = t_stderr.join();
        let exit_code = child.wait().map_or(-1, |s| s.code().unwrap_or(-1));
        let _ = write_frame(
            &mut *writer.lock().unwrap(),
            MSG_EXIT,
            &exit_code.to_le_bytes(),
        );
    }

    // -------------------------------------------------------------------------
    // Interactive execution (pseudo-TTY)
    // -------------------------------------------------------------------------

    fn handle_tty(conn: VsockStream, start: StartCommand) {
        use nix::pty::OpenptyResult;
        use nix::unistd::{ForkResult, fork, setsid};
        use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};

        let OpenptyResult { master, slave } = match nix::pty::openpty(None, None) {
            Ok(r) => r,
            Err(e) => {
                eprintln!("agent: openpty: {e}");
                return;
            }
        };

        if start.tty_width > 0 && start.tty_height > 0 {
            let winsize = libc::winsize {
                ws_col: start.tty_width,
                ws_row: start.tty_height,
                ws_xpixel: 0,
                ws_ypixel: 0,
            };
            // SAFETY: master is a valid PTY master fd.
            unsafe { libc::ioctl(master.as_raw_fd(), libc::TIOCSWINSZ, &winsize) };
        }

        // Transfer ownership so only one entity (File at line 608) closes master_fd.
        let master_fd: RawFd = master.into_raw_fd();
        let slave_fd: RawFd = slave.as_raw_fd();

        match unsafe { fork() } {
            Err(e) => {
                // SAFETY: fork failed; close the unowned master fd to prevent leak.
                unsafe { libc::close(master_fd) };
                eprintln!("agent: fork: {e}");
            }

            Ok(ForkResult::Child) => {
                // SAFETY: close the inherited master fd in the child process.
                unsafe { libc::close(master_fd) };
                let _ = setsid();
                // SAFETY: all fds are valid in the child process.
                unsafe {
                    libc::ioctl(slave_fd, libc::TIOCSCTTY, 0);
                    libc::dup2(slave_fd, libc::STDIN_FILENO);
                    libc::dup2(slave_fd, libc::STDOUT_FILENO);
                    libc::dup2(slave_fd, libc::STDERR_FILENO);
                    if slave_fd > libc::STDERR_FILENO {
                        libc::close(slave_fd);
                    }
                }

                let cstrings: Vec<std::ffi::CString> = start
                    .cmd
                    .iter()
                    .filter_map(|s| std::ffi::CString::new(s.as_str()).ok())
                    .collect();
                let mut argv: Vec<*const libc::c_char> =
                    cstrings.iter().map(|s| s.as_ptr()).collect();
                argv.push(std::ptr::null());

                for (k, v) in &start.env {
                    if let (Ok(ck), Ok(cv)) = (
                        std::ffi::CString::new(k.as_str()),
                        std::ffi::CString::new(v.as_str()),
                    ) {
                        // SAFETY: setenv is safe with valid C strings.
                        unsafe { libc::setenv(ck.as_ptr(), cv.as_ptr(), 1) };
                    }
                }
                if !start.working_dir.is_empty()
                    && let Ok(cwd) = std::ffi::CString::new(start.working_dir.as_str())
                {
                    // SAFETY: cwd is a valid C string.
                    unsafe { libc::chdir(cwd.as_ptr()) };
                }

                // SAFETY: exec replaces the process image; argv is null-terminated.
                unsafe { libc::execvp(argv[0], argv.as_ptr()) };
                unsafe { libc::_exit(127) };
            }

            Ok(ForkResult::Parent { child }) => {
                drop(slave);
                let writer: Arc<Mutex<VsockStream>> = Arc::new(Mutex::new(conn));

                let w_read = Arc::clone(&writer);
                let t_pty = thread::spawn(move || {
                    let mut buf = [0u8; 4096];
                    // SAFETY: dup of master_fd owned by this thread.
                    let mut r = unsafe { VsockStream::from_raw_fd(libc::dup(master_fd)) };
                    loop {
                        match r.read(&mut buf) {
                            Ok(0) | Err(_) => break,
                            Ok(n) => {
                                let _ = write_frame(
                                    &mut *w_read.lock().unwrap(),
                                    MSG_STDOUT,
                                    &buf[..n],
                                );
                            }
                        }
                    }
                });

                let read_fd = unsafe { libc::dup(writer.lock().unwrap().fd) };
                let mut reader = unsafe { VsockStream::from_raw_fd(read_fd) };
                // SAFETY: master_fd is valid; File takes ownership for writes.
                let mut master_writer = unsafe { std::fs::File::from_raw_fd(master_fd) };

                loop {
                    match read_frame(&mut reader) {
                        Ok((MSG_STDIN, data)) => {
                            let _ = master_writer.write_all(&data);
                        }
                        Ok((MSG_RESIZE, data)) if data.len() >= 4 => {
                            let winsize = libc::winsize {
                                ws_col: u16::from_le_bytes([data[0], data[1]]),
                                ws_row: u16::from_le_bytes([data[2], data[3]]),
                                ws_xpixel: 0,
                                ws_ypixel: 0,
                            };
                            // SAFETY: master_fd is valid.
                            unsafe { libc::ioctl(master_fd, libc::TIOCSWINSZ, &winsize) };
                        }
                        Ok((MSG_EOF, _)) | Err(_) => break,
                        Ok(_) => {}
                    }
                }

                let _ = t_pty.join();

                let mut status: libc::c_int = 0;
                // SAFETY: child.as_raw() is a valid pid returned from fork.
                unsafe { libc::waitpid(child.as_raw(), &raw mut status, 0) };
                let exit_code = if libc::WIFEXITED(status) {
                    libc::WEXITSTATUS(status)
                } else {
                    -1
                };
                let _ = write_frame(
                    &mut *writer.lock().unwrap(),
                    MSG_EXIT,
                    &exit_code.to_le_bytes(),
                );
            }
        }
    }

    // -------------------------------------------------------------------------
    // vsock listener
    // -------------------------------------------------------------------------

    /// Mount essential virtual filesystems for an init process.
    fn mount_filesystems() {
        use std::ffi::CString;

        let mounts: &[(&str, &str, &str, libc::c_ulong, &str)] = &[
            (
                "/proc",
                "proc",
                "proc",
                libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC,
                "",
            ),
            (
                "/sys",
                "sysfs",
                "sysfs",
                libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC,
                "",
            ),
            ("/dev", "devtmpfs", "devtmpfs", libc::MS_NOSUID, "mode=0755"),
            (
                "/dev/pts",
                "devpts",
                "devpts",
                libc::MS_NOSUID | libc::MS_NOEXEC,
                "newinstance,ptmxmode=0666",
            ),
        ];

        for (target, source, fstype, flags, data) in mounts {
            let _ = std::fs::create_dir_all(target);
            let c_source = CString::new(*source).unwrap();
            let c_target = CString::new(*target).unwrap();
            let c_fstype = CString::new(*fstype).unwrap();
            let c_data = CString::new(*data).unwrap();
            // SAFETY: all pointers are valid C strings.
            let ret = unsafe {
                libc::mount(
                    c_source.as_ptr(),
                    c_target.as_ptr(),
                    c_fstype.as_ptr(),
                    *flags,
                    c_data.as_ptr().cast(),
                )
            };
            if ret != 0 {
                eprintln!("mount {target}: {}", std::io::Error::last_os_error());
            }
        }

        // Symlink /dev/ptmx → /dev/pts/ptmx so openpty() works.
        let _ = std::os::unix::fs::symlink("/dev/pts/ptmx", "/dev/ptmx");
    }

    /// Find a whitespace-delimited token in `/proc/cmdline` that starts
    /// with the given prefix (e.g. `"ip="` matches `ip=172.20.0.2::...`).
    fn cmdline_token(prefix: &str) -> Option<String> {
        let cmdline = std::fs::read_to_string("/proc/cmdline").ok()?;
        cmdline
            .split_whitespace()
            .find(|t| t.starts_with(prefix))
            .map(str::to_string)
    }

    /// Write `/etc/resolv.conf` pointing at the sandbox gateway so that
    /// glibc DNS resolution works.  The gateway address hosts the guest
    /// DNS server (`0.0.0.0:53`) which handles container/sandbox name
    /// resolution before forwarding upstream.
    ///
    /// Skipped when the `ip=` parameter is absent (e.g. `network: none`
    /// sandboxes or custom rootfs with their own resolver config).
    fn setup_dns() {
        let Some(token) = cmdline_token("ip=") else {
            eprintln!("vmm-guest-agent: no ip= parameter in cmdline, skipping DNS setup");
            return;
        };
        let ip_param = match token.parse::<KernelIpParam>() {
            Ok(p) => p,
            Err(e) => {
                eprintln!("vmm-guest-agent: invalid ip= parameter: {e}");
                return;
            }
        };

        let content = format!("nameserver {}\n", ip_param.gateway);
        match std::fs::write("/etc/resolv.conf", &content) {
            Ok(()) => eprintln!(
                "vmm-guest-agent: wrote /etc/resolv.conf (nameserver {})",
                ip_param.gateway
            ),
            Err(e) => eprintln!("vmm-guest-agent: failed to write /etc/resolv.conf: {e}"),
        }
    }

    /// Spawn a thread with a reduced stack size and a semaphore-style concurrency
    /// limit.  If the limit is already reached the connection fd is closed and a
    /// warning is logged — this is preferable to OOM-killing the guest.
    fn spawn_bounded(active: &Arc<AtomicUsize>, name: &str, conn_fd: RawFd, handler: fn(RawFd)) {
        let current = active.fetch_add(1, Ordering::Relaxed);
        if current >= MAX_ACTIVE_CONNECTIONS {
            active.fetch_sub(1, Ordering::Relaxed);
            eprintln!(
                "agent: {name}: connection limit reached ({MAX_ACTIVE_CONNECTIONS}), dropping fd {conn_fd}"
            );
            // SAFETY: conn_fd is a valid, freshly accepted socket fd that nobody
            // else owns yet.
            unsafe { libc::close(conn_fd) };
            return;
        }

        let active_clone = Arc::clone(active);
        let thread_name = format!("{name}-{conn_fd}");
        let builder = thread::Builder::new()
            .name(thread_name)
            .stack_size(THREAD_STACK_SIZE);

        if let Err(e) = builder.spawn(move || {
            handler(conn_fd);
            active_clone.fetch_sub(1, Ordering::Relaxed);
        }) {
            // The closure was consumed but never executed — release the slot
            // using the original reference and close the fd.
            active.fetch_sub(1, Ordering::Relaxed);
            eprintln!("agent: {name}: failed to spawn thread: {e}");
            // SAFETY: conn_fd is still valid; the closure never ran.
            unsafe { libc::close(conn_fd) };
        }
    }

    pub fn run() {
        mount_filesystems();
        setup_dns();
        eprintln!(
            "vmm-guest-agent: listening on vsock ports {AGENT_PORT} (exec), {FILE_PORT} (file I/O)"
        );
        let exec_fd = create_vsock_listener(AGENT_PORT);
        let file_fd = create_vsock_listener(FILE_PORT);

        // Shared counters for bounding active connection threads.
        let file_active: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));
        let exec_active: Arc<AtomicUsize> = Arc::new(AtomicUsize::new(0));

        // File I/O listener thread.
        let file_active_clone = Arc::clone(&file_active);
        thread::spawn(move || {
            loop {
                let conn_fd = accept_connection(file_fd);
                spawn_bounded(&file_active_clone, "file", conn_fd, handle_file_connection);
            }
        });

        // Exec listener (main thread).
        loop {
            let conn_fd = accept_connection(exec_fd);
            spawn_bounded(&exec_active, "exec", conn_fd, handle_connection);
        }
    }

    fn create_vsock_listener(port: u32) -> RawFd {
        // SAFETY: socket(2) with valid AF_VSOCK constants.
        let fd = unsafe { libc::socket(libc::AF_VSOCK, libc::SOCK_STREAM, 0) };
        assert!(
            fd >= 0,
            "socket(AF_VSOCK): {}",
            std::io::Error::last_os_error()
        );

        let addr = libc::sockaddr_vm {
            svm_family: libc::AF_VSOCK as libc::sa_family_t,
            svm_reserved1: 0,
            svm_port: port,
            svm_cid: libc::VMADDR_CID_ANY,
            ..unsafe { std::mem::zeroed() }
        };
        // SAFETY: addr is valid; fd is a live socket.
        let ret = unsafe {
            libc::bind(
                fd,
                (&raw const addr).cast::<libc::sockaddr>(),
                std::mem::size_of::<libc::sockaddr_vm>() as libc::socklen_t,
            )
        };
        assert!(
            ret == 0,
            "bind vsock port {port}: {}",
            std::io::Error::last_os_error()
        );
        // SAFETY: fd is a bound socket.
        unsafe { libc::listen(fd, 128) };
        fd
    }

    fn accept_connection(server_fd: RawFd) -> RawFd {
        loop {
            // SAFETY: server_fd is a listening vsock socket.
            let conn_fd =
                unsafe { libc::accept(server_fd, std::ptr::null_mut(), std::ptr::null_mut()) };
            if conn_fd >= 0 {
                return conn_fd;
            }
            let err = std::io::Error::last_os_error();
            assert!(
                err.kind() == std::io::ErrorKind::Interrupted,
                "accept: {err}"
            );
        }
    }
}

// =============================================================================
// Entry point
// =============================================================================

fn main() {
    #[cfg(target_os = "linux")]
    agent::run();

    #[cfg(not(target_os = "linux"))]
    {
        eprintln!("vmm-guest-agent requires Linux (AF_VSOCK)");
        std::process::exit(1);
    }
}