-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlib.rs
More file actions
4083 lines (3699 loc) · 142 KB
/
Copy pathlib.rs
File metadata and controls
4083 lines (3699 loc) · 142 KB
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! hyperlight-unikraft: run Unikraft kernels on Hyperlight
//!
//! Provides a [`Sandbox`] wrapper around Hyperlight's `MultiUseSandbox`
//! that manages the kernel lifecycle: create → evolve (init) → snapshot
//! → call.
//!
//! # Quick start
//!
//! ```no_run
//! use hyperlight_unikraft::Sandbox;
//! # fn main() -> anyhow::Result<()> {
//! let mut sbox = Sandbox::builder("./kernel")
//! .initrd_file("./initrd.cpio")
//! .heap_size(256 * 1024 * 1024)
//! .build()?;
//! sbox.restore()?;
//! sbox.call_run()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Snapshot lifecycle
//!
//! The sandbox keeps a live snapshot and lets you rewind to it. This
//! underpins [`pyhl`]'s fast cold start and every hermetic-per-call
//! pattern.
//!
//! ```text
//! Sandbox::builder(..).build() → evolve (boot + init); post-evolve snapshot captured
//! │
//! ▼
//! sbox.restore() ←──┐ rewind to snapshot
//! │ │
//! ▼ │
//! sbox.call_*(..) │ dispatch (hermetic via restore)
//! │ │
//! └─────────────────┘
//! ```
//!
//! After a warmup `call_*`, use [`Sandbox::snapshot_now`] to capture
//! post-warmup state — subsequent `restore()` rewinds to that point,
//! skipping the warmup on every call.
//!
//! To persist across processes:
//!
//! - [`Sandbox::save_snapshot`] writes the current snapshot to disk.
//! - [`Sandbox::from_snapshot_file`] recreates a sandbox straight from
//! the file on disk, bypassing evolve entirely. This is how
//! `pyhl run` starts in ~100ms without re-doing `Py_Initialize`.
//!
//! # Host filesystem
//!
//! The guest can access host directories via [`Preopen`] + the
//! `__dispatch` RPC. [`FsSandbox`] rejects path-escape attempts and
//! `normalize_fs_error` rewrites host-OS-specific error wording so
//! the cross-platform Unikraft guest classifies errors uniformly.
pub mod pyhl;
pub mod stderr_capture;
use anyhow::{anyhow, Result};
use hyperlight_host::func::Registerable;
use hyperlight_host::sandbox::snapshot::{OciTag, Snapshot};
use hyperlight_host::sandbox::uninitialized::GuestEnvironment;
use hyperlight_host::sandbox::SandboxConfiguration;
use hyperlight_host::{GuestBinary, HostFunctions, MultiUseSandbox, UninitializedSandbox};
use std::collections::{HashMap, HashSet};
use std::net::IpAddr;
use std::path::Path;
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;
/// Magic header for cmdline embedded in initrd: "HLCMDLN\0"
const CMDLINE_MAGIC: &[u8; 8] = b"HLCMDLN\0";
/// Magic header for the optional hostfs mount point TLV that follows the
/// cmdline (same init_data page).
const MOUNT_MAGIC: &[u8; 8] = b"HLHSMNT\0";
/// Magic header for the optional wall-clock-at-boot TLV. Value is a
/// little-endian u64 of nanoseconds since the Unix epoch. The guest
/// adds its own monotonic delta at read time, so `time.time()` returns
/// a sensible wall time without any host round-trip per call.
const WALLTIME_MAGIC: &[u8; 8] = b"HLWALL0\0";
const PAGE_SIZE: usize = 4096;
/// Guest paths that would shadow the kernel's own ramfs and break the VM.
/// Reject these early on the host before we even boot the guest.
const RESERVED_GUEST_MOUNTPOINTS: &[&str] = &["/", "/bin", "/dev", "/proc", "/sys", "/usr"];
/// Cap for `fs_read_bytes` allocation to prevent guest-controlled OOM (16 MiB).
const MAX_FS_READ: u64 = 16 * 1024 * 1024;
/// Cap for `net_send`/`net_sendto` decoded payload (1 MiB).
const MAX_NET_SEND: usize = 1024 * 1024;
/// Cap for `fs_write`/`fs_write_bytes` payload to prevent guest-triggered OOM (16 MiB).
const MAX_FS_WRITE: usize = 16 * 1024 * 1024;
/// Cap for `fs_truncate` length to prevent disk exhaustion (1 GiB).
const MAX_TRUNCATE_LEN: u64 = 1024 * 1024 * 1024;
/// Cap for incoming dispatch payload size (64 MiB).
const MAX_DISPATCH_PAYLOAD: usize = 64 * 1024 * 1024;
/// Cap for `__hl_sleep` duration to prevent unbounded host-thread blocking (60 s).
const MAX_SLEEP_NS: u64 = 60_000_000_000;
/// Shared cancellation primitive for `__hl_sleep`. Calling
/// [`SleepCancel::cancel`] wakes up any in-progress sleep immediately so
/// the host function returns and the hypervisor execution loop can detect
/// the pending cancellation.
#[derive(Clone)]
pub struct SleepCancel(Arc<(Mutex<bool>, Condvar)>);
impl SleepCancel {
fn new() -> Self {
Self(Arc::new((Mutex::new(false), Condvar::new())))
}
/// Wake any in-progress `__hl_sleep` immediately.
pub fn cancel(&self) {
let (lock, cvar) = &*self.0;
*lock.lock().unwrap() = true;
cvar.notify_all();
}
/// Reset so the next guest call can sleep normally.
pub fn reset(&self) {
*self.0 .0.lock().unwrap() = false;
}
fn wait(&self, dur: Duration) {
let (lock, cvar) = &*self.0;
let guard = lock.lock().unwrap();
if *guard {
return;
}
// wait_timeout_while handles spurious wakeups by re-checking the
// predicate; we only return early when actually cancelled.
let _ = cvar.wait_timeout_while(guard, dur, |cancelled| !*cancelled);
}
}
/// Cap for `fs_list` directory entries to prevent host OOM on huge directories.
const MAX_DIR_ENTRIES: usize = 100_000;
/// Default socket timeout for read/write/connect operations (30 s).
const SOCKET_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
/// A preopened host directory exposed to the guest.
///
/// Semantics mirror Wasmtime's `preopened_dir`: `host_dir` is canonicalised
/// at construction time and used as the sandbox root for every RPC the
/// guest issues; `guest_path` is the absolute path inside the guest where
/// `lib/hostfs` mounts it.
#[derive(Clone, Debug)]
pub struct Preopen {
pub host_dir: std::path::PathBuf,
pub guest_path: String,
pub read_only: bool,
}
impl Preopen {
/// Construct a preopen. `guest_path` must be absolute (`/something`)
/// and not shadow a reserved kernel directory — see
/// `RESERVED_GUEST_MOUNTPOINTS`.
pub fn new<P: AsRef<Path>>(host_dir: P, guest_path: impl Into<String>) -> Result<Self> {
let guest_path = guest_path.into();
if !guest_path.starts_with('/') {
return Err(anyhow!(
"guest mount path {:?} must be absolute",
guest_path
));
}
for reserved in RESERVED_GUEST_MOUNTPOINTS {
if guest_path == *reserved || guest_path.starts_with(&format!("{}/", reserved)) {
return Err(anyhow!(
"refusing to mount at guest path {:?}: shadows reserved kernel dir",
guest_path
));
}
}
let host_dir = std::fs::canonicalize(host_dir.as_ref()).map_err(|e| {
anyhow!(
"canonicalize preopen host dir {:?}: {}",
host_dir.as_ref(),
e
)
})?;
Ok(Self {
host_dir,
guest_path,
read_only: false,
})
}
/// Mark this preopen as read-only.
pub fn read_only(mut self) -> Self {
self.read_only = true;
self
}
/// Parse a `HOST[:GUEST]` CLI argument. When `GUEST` is omitted the
/// default guest mount point is `/host`.
pub fn parse_cli(s: &str) -> Result<Self> {
// Windows absolute paths contain ':'. Disambiguate by splitting on
// the *last* colon only if the right side looks like an absolute
// guest path (starts with /). Otherwise treat the whole string as
// the host dir.
if let Some(idx) = s.rfind(':') {
let (host, guest) = s.split_at(idx);
let guest = &guest[1..];
if guest.starts_with('/') {
return Self::new(host, guest);
}
}
Self::new(s, "/host")
}
}
// ---------------------------------------------------------------------------
// Network policy
// ---------------------------------------------------------------------------
/// Controls which network destinations a guest sandbox can reach.
///
/// By default, networking is **disabled** (no `net_*` tools are registered).
/// Callers must opt in via [`SandboxBuilder::network`] or the `--net` CLI flag.
#[derive(Clone, Debug)]
pub enum NetworkPolicy {
/// All outbound connections are allowed (no filtering).
AllowAll,
/// Only connections to the listed destinations are permitted.
AllowList(AllowList),
/// All connections are allowed *except* to the listed destinations.
BlockList(BlockList),
}
/// A set of allowed network destinations.
///
/// Stores both literal IPs and hostnames. At check time, hostnames are
/// re-resolved so the policy tracks DNS changes (CDN rotation, etc.).
#[derive(Clone, Debug)]
pub struct AllowList {
allowed_ips: HashSet<IpAddr>,
hostnames: Vec<String>,
learned_ips: Arc<Mutex<HashSet<IpAddr>>>,
}
impl AllowList {
/// Build an allowlist from a mixed set of hostnames and IP literals.
///
/// Hostnames are verified to be resolvable at construction time
/// (fail-closed). At check time they are re-resolved so CDN/anycast
/// rotation doesn't cause false denials.
pub fn from_hosts(entries: &[impl AsRef<str>]) -> Result<Self> {
use std::net::ToSocketAddrs;
let mut allowed_ips = HashSet::new();
let mut hostnames = Vec::new();
for entry in entries {
let entry = entry.as_ref();
if let Ok(ip) = entry.parse::<IpAddr>() {
allowed_ips.insert(ip);
} else {
let addrs = (entry, 0u16)
.to_socket_addrs()
.map_err(|e| anyhow!("resolve {:?}: {}", entry, e))?;
let mut found = false;
for sa in addrs {
allowed_ips.insert(sa.ip());
found = true;
}
if !found {
return Err(anyhow!("hostname {:?} resolved to zero addresses", entry));
}
hostnames.push(entry.to_string());
}
}
Ok(Self {
allowed_ips,
hostnames,
learned_ips: Arc::new(Mutex::new(HashSet::new())),
})
}
fn is_allowed(&self, ip: &IpAddr) -> bool {
if self.allowed_ips.contains(ip) {
return true;
}
if let Ok(learned) = self.learned_ips.lock() {
if learned.contains(ip) {
return true;
}
}
// Re-resolve hostnames to catch CDN/anycast IP rotation.
use std::net::ToSocketAddrs;
for host in &self.hostnames {
if let Ok(addrs) = (host.as_str(), 0u16).to_socket_addrs() {
for sa in addrs {
if &sa.ip() == ip {
return true;
}
}
}
}
false
}
fn learn_ip(&self, ip: IpAddr) {
if let Ok(mut learned) = self.learned_ips.lock() {
if learned.len() < MAX_LEARNED_IPS {
learned.insert(ip);
}
}
}
}
/// A set of blocked network destinations.
///
/// Like [`AllowList`], stores both literal IPs and hostnames. At check
/// time, hostnames are re-resolved so the policy tracks DNS changes.
#[derive(Clone, Debug)]
pub struct BlockList {
blocked_ips: HashSet<IpAddr>,
hostnames: Vec<String>,
}
impl BlockList {
/// Build a blocklist from a mixed set of hostnames and IP literals.
///
/// Hostnames are verified to be resolvable at construction time
/// (fail-closed). At check time they are re-resolved so CDN/anycast
/// rotation doesn't cause false passes.
pub fn from_hosts(entries: &[impl AsRef<str>]) -> Result<Self> {
use std::net::ToSocketAddrs;
let mut blocked_ips = HashSet::new();
let mut hostnames = Vec::new();
for entry in entries {
let entry = entry.as_ref();
if let Ok(ip) = entry.parse::<IpAddr>() {
blocked_ips.insert(ip);
} else {
let addrs = (entry, 0u16)
.to_socket_addrs()
.map_err(|e| anyhow!("resolve {:?}: {}", entry, e))?;
let mut found = false;
for sa in addrs {
blocked_ips.insert(sa.ip());
found = true;
}
if !found {
return Err(anyhow!("hostname {:?} resolved to zero addresses", entry));
}
hostnames.push(entry.to_string());
}
}
Ok(Self {
blocked_ips,
hostnames,
})
}
fn is_blocked(&self, ip: &IpAddr) -> bool {
if self.blocked_ips.contains(ip) {
return true;
}
use std::net::ToSocketAddrs;
for host in &self.hostnames {
if let Ok(addrs) = (host.as_str(), 0u16).to_socket_addrs() {
for sa in addrs {
if &sa.ip() == ip {
return true;
}
}
}
}
false
}
}
/// DNS resolver IPs that the AllowList exempts on port 53.
///
/// Includes the host's configured resolvers (from `/etc/resolv.conf` on
/// Unix, `ipconfig /all` on Windows) **plus** well-known public DNS
/// servers (Google, Cloudflare) that the guest may hardcode in its own
/// `/etc/resolv.conf`.
fn dns_resolvers() -> &'static HashSet<IpAddr> {
static RESOLVERS: std::sync::OnceLock<HashSet<IpAddr>> = std::sync::OnceLock::new();
RESOLVERS.get_or_init(|| {
let mut set = HashSet::new();
// Well-known public DNS that the guest's initrd may hardcode.
for ip in [
"8.8.8.8", "8.8.4.4", // Google
"1.1.1.1", "1.0.0.1", // Cloudflare
] {
set.insert(ip.parse::<IpAddr>().unwrap());
}
#[cfg(unix)]
{
if let Ok(contents) = std::fs::read_to_string("/etc/resolv.conf") {
for line in contents.lines() {
let line = line.trim();
if let Some(rest) = line.strip_prefix("nameserver") {
if let Some(ip_str) = rest.split_whitespace().next() {
if let Ok(ip) = ip_str.parse::<IpAddr>() {
set.insert(ip);
}
}
}
}
}
}
#[cfg(windows)]
{
if let Ok(output) = std::process::Command::new("ipconfig").arg("/all").output() {
let text = String::from_utf8_lossy(&output.stdout);
let mut in_dns_block = false;
for line in text.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix("DNS Servers") {
in_dns_block = true;
let value = rest.trim_start_matches(['.', ' ', ':']);
if let Ok(ip) = value.parse::<IpAddr>() {
set.insert(ip);
}
} else if in_dns_block {
if let Ok(ip) = trimmed.parse::<IpAddr>() {
set.insert(ip);
} else {
in_dns_block = false;
}
}
}
}
}
set
})
}
impl NetworkPolicy {
fn check(&self, addr: &std::net::SocketAddr) -> Result<()> {
// Block link-local addresses (169.254.0.0/16, fe80::/10) for all
// policy variants. In cloud environments the IPv4 link-local range
// hosts the instance metadata service (169.254.169.254) which hands
// out credentials without authentication.
let is_link_local = match addr.ip() {
std::net::IpAddr::V4(v4) => v4.is_link_local(),
std::net::IpAddr::V6(v6) => {
let seg = v6.segments();
(seg[0] & 0xffc0) == 0xfe80
}
};
if is_link_local {
return Err(anyhow!(
"network policy denies connection to link-local address {}",
addr
));
}
// Block loopback addresses (127.0.0.0/8, ::1) for all policy
// variants. Host-local services typically trust loopback traffic
// and perform no authentication.
if addr.ip().is_loopback() {
return Err(anyhow!(
"network policy denies connection to loopback address {}",
addr
));
}
match self {
NetworkPolicy::AllowAll => Ok(()),
NetworkPolicy::AllowList(al) => {
if al.is_allowed(&addr.ip())
|| (addr.port() == 53 && dns_resolvers().contains(&addr.ip()))
{
Ok(())
} else {
Err(anyhow!("network policy denies connection to {}", addr))
}
}
NetworkPolicy::BlockList(bl) => {
if bl.is_blocked(&addr.ip()) {
Err(anyhow!("network policy denies connection to {}", addr))
} else {
Ok(())
}
}
}
}
}
// ---------------------------------------------------------------------------
// Listen-port allowlist (inbound)
// ---------------------------------------------------------------------------
/// Controls which ports a guest may bind to for inbound connections.
///
/// Orthogonal to [`NetworkPolicy`] (which governs *outbound* destinations).
/// Without a `ListenPorts` allowlist, `net_bind` / `net_listen` /
/// `net_accept` are still registered but `net_bind` rejects every call.
#[derive(Clone, Debug)]
pub struct ListenPorts {
ports: HashSet<u16>,
}
impl ListenPorts {
/// Create from an iterator of port numbers.
pub fn from_ports(ports: impl IntoIterator<Item = u16>) -> Self {
Self {
ports: ports.into_iter().collect(),
}
}
/// Returns `Ok(())` if `port` is in the allowlist.
fn check(&self, port: u16) -> Result<()> {
if self.ports.contains(&port) {
Ok(())
} else {
Err(anyhow!(
"Permission denied: port {} not in listen allowlist ({:?})",
port,
self.ports
))
}
}
}
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
/// Configuration for a Unikraft VM.
#[non_exhaustive]
pub struct VmConfig {
pub heap_size: u64,
pub stack_size: u64,
pub io_buffer_size: usize,
}
/// Hyperlight I/O buffer size (128 KiB). Each host function call is serialized
/// into a FlatBuffer and pushed onto a shared-memory stack whose capacity is
/// `io_buffer_size`. The hostfs VFS layer chunks writes at 32 KiB, but after
/// base64 encoding + JSON envelope + FlatBuffer framing a single chunk
/// occupies ~44 KiB. The Hyperlight SDK default (16 KiB) is too small; 128 KiB
/// accommodates any single-chunk RPC with comfortable headroom.
const DEFAULT_IO_BUFFER_SIZE: usize = 128 * 1024;
impl Default for VmConfig {
fn default() -> Self {
Self {
heap_size: 512 * 1024 * 1024,
stack_size: 8 * 1024 * 1024,
io_buffer_size: DEFAULT_IO_BUFFER_SIZE,
}
}
}
impl VmConfig {
/// Set the guest heap size in bytes. Convenience chainable setter
/// for building a `VmConfig` inline.
pub fn with_heap_size(mut self, size: u64) -> Self {
self.heap_size = size;
self
}
/// Set the guest stack size in bytes. Chainable setter.
pub fn with_stack_size(mut self, size: u64) -> Self {
self.stack_size = size;
self
}
/// Set the I/O buffer size for host function calls (default 128 KiB).
pub fn with_io_buffer_size(mut self, size: usize) -> Self {
self.io_buffer_size = size;
self
}
fn sandbox_config(&self) -> SandboxConfiguration {
let mut cfg = SandboxConfiguration::default();
cfg.set_heap_size(self.heap_size);
cfg.set_input_data_size(self.io_buffer_size);
cfg.set_output_data_size(self.io_buffer_size);
// Scratch holds page tables + CoW copies of writable pages touched at
// runtime. pt_estimate covers page tables; the base covers kernel
// boot, CPIO extraction, ELF loading, and language runtime startup.
// Use 25% of heap as base: large guests (e.g. Node.js) load 100+ MB
// ELF binaries whose PT_LOAD segments trigger per-page CoW copies.
let pt_estimate = ((self.heap_size as usize / (2 * 1024 * 1024)) + 16) * PAGE_SIZE;
let base = std::cmp::max(self.heap_size as usize / 4, 64 * 1024 * 1024);
let scratch = (pt_estimate + base).next_multiple_of(PAGE_SIZE);
cfg.set_scratch_size(scratch);
cfg
}
}
/// Parse memory size string (e.g., "512Mi", "1Gi") into bytes.
pub fn parse_memory(mem_str: &str) -> Result<u64> {
let s = mem_str.trim();
if let Some(v) = s.strip_suffix("Gi") {
Ok(v.parse::<u64>()? * 1024 * 1024 * 1024)
} else if let Some(v) = s.strip_suffix("Mi") {
Ok(v.parse::<u64>()? * 1024 * 1024)
} else if let Some(v) = s.strip_suffix("Ki") {
Ok(v.parse::<u64>()? * 1024)
} else if let Some(v) = s.strip_suffix("G") {
Ok(v.parse::<u64>()? * 1_000_000_000)
} else if let Some(v) = s.strip_suffix("M") {
Ok(v.parse::<u64>()? * 1_000_000)
} else if let Some(v) = s.strip_suffix("K") {
Ok(v.parse::<u64>()? * 1000)
} else {
s.parse()
.map_err(|e| anyhow!("Invalid memory format: {}", e))
}
}
// ---------------------------------------------------------------------------
// Initrd cmdline prepend
// ---------------------------------------------------------------------------
/// Serialize the shared "cmdline + preopens + wall clock" TLV block into `buf`.
///
/// Layout:
/// [HLCMDLN\0][cmdline_len u32][cmdline…][\0]
/// [HLHSMNT\0][count u32]([path_len u32][path…][\0])*count (optional block)
/// [HLWALL0\0][8 u32][wall_ns_le u64]
///
/// Callers are responsible for any trailing padding / metadata (e.g. the
/// mapped-initrd-size footer used by `build_cmdline_initdata`).
fn write_cmdline_mount_tlv(buf: &mut Vec<u8>, cmdline_bytes: &[u8], preopens: &[Preopen]) {
let cmdline_len = cmdline_bytes.len() as u32;
buf.extend_from_slice(CMDLINE_MAGIC);
buf.extend_from_slice(&cmdline_len.to_le_bytes());
buf.extend_from_slice(cmdline_bytes);
buf.push(0);
if !preopens.is_empty() {
buf.extend_from_slice(MOUNT_MAGIC);
buf.extend_from_slice(&(preopens.len() as u32).to_le_bytes());
for p in preopens {
let b = p.guest_path.as_bytes();
buf.extend_from_slice(&(b.len() as u32).to_le_bytes());
buf.extend_from_slice(b);
buf.push(0);
}
}
// Wall clock: read the host's time once at VM build time and embed
// as ns since epoch. The guest will add its own monotonic delta.
let wall_ns = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
buf.extend_from_slice(WALLTIME_MAGIC);
buf.extend_from_slice(&8u32.to_le_bytes());
buf.extend_from_slice(&wall_ns.to_le_bytes());
}
/// Build init_data with cmdline + preopens + mapped initrd size (for
/// map_file_cow mode). The mapped file size is stored in the last 8
/// bytes of the page-aligned header.
fn build_cmdline_initdata(
app_args: &[String],
mapped_initrd_size: u64,
preopens: &[Preopen],
) -> Option<Vec<u8>> {
let cmdline = app_args.join(" ");
if cmdline.is_empty() && mapped_initrd_size == 0 && preopens.is_empty() {
return None;
}
let cmdline_bytes = cmdline.as_bytes();
let mut buf = Vec::new();
write_cmdline_mount_tlv(&mut buf, cmdline_bytes, preopens);
let padded = (buf.len() + PAGE_SIZE - 1) & !(PAGE_SIZE - 1);
buf.resize(padded - 8, 0);
buf.extend_from_slice(&mapped_initrd_size.to_le_bytes());
Some(buf)
}
/// Prepend application arguments + preopens as a header in the initrd.
pub fn prepend_cmdline_to_initrd(
initrd: Option<&[u8]>,
app_args: &[String],
preopens: &[Preopen],
) -> Option<Vec<u8>> {
let cmdline = app_args.join(" ");
if cmdline.is_empty() && initrd.is_none() && preopens.is_empty() {
return None;
}
if cmdline.is_empty() && preopens.is_empty() {
return initrd.map(|d| d.to_vec());
}
let cmdline_bytes = cmdline.as_bytes();
let mut buf = Vec::new();
write_cmdline_mount_tlv(&mut buf, cmdline_bytes, preopens);
let padded = (buf.len() + PAGE_SIZE - 1) & !(PAGE_SIZE - 1);
buf.resize(padded, 0);
if let Some(data) = initrd {
buf.extend_from_slice(data);
}
Some(buf)
}
// ---------------------------------------------------------------------------
// Tool dispatch (host functions callable from guest)
// ---------------------------------------------------------------------------
/// Registry of tool handlers callable from guest user-space via `/dev/hcall`.
pub struct ToolRegistry {
tools:
HashMap<String, Box<dyn Fn(serde_json::Value) -> Result<serde_json::Value> + Send + Sync>>,
}
impl ToolRegistry {
/// Create an empty registry. Add handlers with
/// [`register`](Self::register) before wiring it into a sandbox.
pub fn new() -> Self {
Self {
tools: HashMap::new(),
}
}
/// Register a named handler. The handler receives the JSON-encoded
/// `args` payload the guest sent and returns a `serde_json::Value`
/// that becomes the `{"result": ...}` portion of the response.
/// Errors returned by the handler become `{"error": "..."}`.
pub fn register<F>(&mut self, name: &str, handler: F)
where
F: Fn(serde_json::Value) -> Result<serde_json::Value> + Send + Sync + 'static,
{
self.tools.insert(name.to_string(), Box::new(handler));
}
/// Decode a guest-side `__dispatch` request, look up the handler by
/// name, invoke it, and encode the response as JSON bytes.
///
/// The request shape is `{"name": "...", "args": <value>}`, and the
/// response is either `{"result": <value>}` or `{"error": "<msg>"}`.
/// Unknown tool names and JSON errors both become error responses;
/// this function never panics.
///
/// Set `HL_DISPATCH_DEBUG=1` in the environment to dump each call's
/// payload and result to stderr — useful when diagnosing
/// guest/host protocol mismatches.
pub fn dispatch(&self, payload: &[u8]) -> Vec<u8> {
if payload.len() > MAX_DISPATCH_PAYLOAD {
return serde_json::to_vec(&serde_json::json!({
"error": format!("payload too large: {} bytes (max {})", payload.len(), MAX_DISPATCH_PAYLOAD)
}))
.unwrap_or_default();
}
let debug = std::env::var("HL_DISPATCH_DEBUG")
.ok()
.map(|v| v == "1")
.unwrap_or(false);
if debug {
let preview = if payload.len() > 200 {
&payload[..200]
} else {
payload
};
eprintln!(
"[__dispatch] payload.len={} preview={:?}",
payload.len(),
std::str::from_utf8(preview).unwrap_or("<non-utf8>")
);
}
let result = (|| -> Result<serde_json::Value> {
let req: serde_json::Value = serde_json::from_slice(payload)?;
let name = req["name"]
.as_str()
.ok_or_else(|| anyhow!("missing 'name'"))?;
let args = req.get("args").cloned().unwrap_or(serde_json::Value::Null);
let handler = self
.tools
.get(name)
.ok_or_else(|| anyhow!("unknown tool: {}", name))?;
handler(args)
})();
if debug {
match &result {
Ok(v) => eprintln!("[__dispatch] OK: {}", v),
Err(e) => eprintln!("[__dispatch] ERR: {}", e),
}
}
let json = match result {
Ok(v) => serde_json::json!({ "result": v }),
Err(e) => {
// Normalize common error strings so the cross-platform
// Unikraft guest doesn't depend on host-OS-specific
// wording to classify the error.
//
// The guest's `lib/hostfs` substring-matches on the
// error payload to pick a POSIX errno. On Linux the
// wording is the canonical "No such file or directory";
// on Windows Rust produces "The system cannot find the
// file specified.", which fell through the match and
// triggered a fatal-error path in vfscore (observed
// crash at hostfs-posix-c:open /host/greeting.txt).
//
// Keep the underlying error code (`os error N`) in the
// string so downstream debugging stays faithful.
serde_json::json!({ "error": normalize_fs_error(&e.to_string()) })
}
};
serde_json::to_vec(&json)
.unwrap_or_else(|_| b"{\"error\":\"serialization failed\"}".to_vec())
}
}
impl Default for ToolRegistry {
fn default() -> Self {
Self::new()
}
}
/// Rewrite host-OS-specific error wording to the canonical Linux form
/// so the Unikraft guest's `lib/hostfs` can classify errors by substring
/// match without caring which host it's running on. Linux wording is
/// canonical because that's what the guest was written against.
///
/// Only rewrites the message when we can identify the error by its
/// `os error N` suffix (that `N` is the POSIX errno — cross-platform).
/// Otherwise passes the string through unchanged so unusual errors are
/// still visible in debug output.
fn normalize_fs_error(s: &str) -> String {
// Map: POSIX errno -> canonical Linux std::io::Error wording.
//
// 2 ENOENT "No such file or directory"
// 13 EACCES "Permission denied"
// 17 EEXIST "File exists"
// 20 ENOTDIR "Not a directory"
// 21 EISDIR "Is a directory"
// 39 ENOTEMPTY "Directory not empty"
const MAP: &[(&str, &str)] = &[
("(os error 2)", "No such file or directory"),
("(os error 13)", "Permission denied"),
("(os error 17)", "File exists"),
("(os error 20)", "Not a directory"),
("(os error 21)", "Is a directory"),
("(os error 39)", "Directory not empty"),
];
for (marker, canonical) in MAP {
if s.contains(marker) {
// Keep the prefix (e.g., `fs_stat "/host/greeting.txt":`) so
// debugging is still legible; just replace the body wording.
if let Some(idx) = s.find(": ") {
let prefix = &s[..idx];
return format!("{prefix}: {canonical} {marker}");
}
return format!("{canonical} {marker}");
}
}
s.to_string()
}
// ---------------------------------------------------------------------------
// Filesystem sandbox — Phase A of host-mediated POSIX FS access
// ---------------------------------------------------------------------------
/// A sandboxed view of a host directory that the guest can read/write via
/// host function calls. All guest-supplied paths are resolved relative to
/// `root`; any attempt to escape the root (`..`, absolute paths, symlinks
/// pointing outside) is rejected.
///
/// Phase A deliberately exposes an explicit RPC surface: the guest calls
/// `fs_read` / `fs_write` / `fs_list` / `fs_stat` / `fs_mkdir` / `fs_unlink`
/// by name. Phase B will add a transparent POSIX shim in Unikraft that
/// forwards VFS operations to these same host handlers.
#[derive(Clone)]
pub struct FsSandbox {
root: std::path::PathBuf,
}
impl FsSandbox {
/// Create a new sandbox rooted at `root` (must be an existing directory).
pub fn new<P: AsRef<Path>>(root: P) -> Result<Self> {
let root = std::fs::canonicalize(root.as_ref())
.map_err(|e| anyhow!("canonicalize mount root {:?}: {}", root.as_ref(), e))?;
if !root.is_dir() {
return Err(anyhow!("mount root is not a directory: {:?}", root));
}
Ok(Self { root })
}
/// The canonicalized host-side root directory. All guest-supplied
/// paths are resolved relative to this; escapes are rejected.
pub fn root(&self) -> &Path {
&self.root
}
/// Resolve a guest-supplied path to a host path that is guaranteed to
/// live under `root`. Returns an error on any escape attempt.
///
/// Strategy:
/// - Strip any leading `/` so guest paths are relative to the mount.
/// - Logically normalise `.` / `..` without touching the filesystem.
/// - If the resolved path exists, `canonicalize` to follow symlinks
/// and verify the target is under `root`.
/// - If it doesn't exist (e.g. creating a new file), canonicalise the
/// nearest existing ancestor and append the remaining components —
/// this still catches symlinked ancestors that escape the root.
pub(crate) fn resolve(&self, guest_path: &str) -> Result<std::path::PathBuf> {
use std::path::{Component, PathBuf};
let rel = guest_path.trim_start_matches('/');
let joined = self.root.join(rel);
// Logical resolution first: reject ".." once we're rooted.
let mut logical = PathBuf::new();
for c in joined.components() {
match c {
Component::ParentDir => {
if !logical.pop() {
return Err(anyhow!("path escapes mount root: {:?}", guest_path));
}
}
Component::CurDir => {}
c => logical.push(c),
}
}
if !logical.starts_with(&self.root) {
return Err(anyhow!("path escapes mount root: {:?}", guest_path));
}
// Symlink check: canonicalise the deepest existing ancestor.
let mut existing = logical.as_path();
let mut tail: Vec<&std::ffi::OsStr> = Vec::new();
let resolved_ancestor = loop {
if existing.exists() {
break std::fs::canonicalize(existing)
.map_err(|e| anyhow!("canonicalize {:?}: {}", existing, e))?;
}
let Some(name) = existing.file_name() else {
return Err(anyhow!("path has no existing ancestor: {:?}", logical));
};
tail.push(name);
existing = existing
.parent()
.ok_or_else(|| anyhow!("path has no existing ancestor: {:?}", logical))?;
};
if !resolved_ancestor.starts_with(&self.root) {
return Err(anyhow!(
"path escapes mount root (symlink): {:?}",
guest_path
));
}
let mut out = resolved_ancestor;
for name in tail.into_iter().rev() {
out.push(name);
// Walk the symlink chain (with hop limit) to catch escapes
// through dangling or chained symlinks.
const MAX_SYMLINK_HOPS: usize = 40;
let mut cursor = out.clone();
for _ in 0..MAX_SYMLINK_HOPS {
let Ok(meta) = std::fs::symlink_metadata(&cursor) else {
break;
};
if !meta.file_type().is_symlink() {
break;
}
let target = std::fs::read_link(&cursor)?;
let abs = if target.is_absolute() {
target
} else {
cursor.parent().unwrap_or(&self.root).join(&target)
};
let mut norm = std::path::PathBuf::new();
for c in abs.components() {
match c {
std::path::Component::ParentDir => {
norm.pop();
}
std::path::Component::CurDir => {}
c => norm.push(c),
}
}
if !norm.starts_with(&self.root) {
return Err(anyhow!(
"symlink target escapes mount root: {:?}",
guest_path
));
}
cursor = norm;
}
}
Ok(out)
}
}
/// Internal helper: assemble the final tool registry from caller-supplied
/// tools plus any preopened directories. Multiple preopens share one set
/// of fs_* tool handlers that route by guest-path prefix: the handler
/// inspects the `path` argument, finds the matching preopen, and