Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
2419 lines (2175 loc) · 86.1 KB
/
Copy pathlib.rs
File metadata and controls
2419 lines (2175 loc) · 86.1 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
//! Realm-tagged path types.
//!
//! `PathBuf` carries no information about *which* filesystem a path belongs
//! to. In a system that bridges the user's host, the sandbox rootfs, and
//! (eventually) the minimald daemon, that ambiguity is a footgun: it is easy
//! to pass a host path to code that expects a sandbox-internal path, and the
//! type checker will not stop you.
//!
//! This crate encodes the filesystem a path belongs to as a *phantom type
//! parameter*, splits absolute and relative paths into distinct types, and
//! requires crossing realms to go through an explicit [`Translator`].
//!
//! # Quick tour
//!
//! - [`Realm`] is a marker trait; [`Host`], [`Sandbox`], [`Daemon`], and
//! [`ConfigRelative`] are the zero-sized implementors.
//! - [`AbsPath<R>`] is an absolute UTF-8 path tagged with realm `R`.
//! - [`RelPath<R>`] is a relative UTF-8 path tagged with the realm it will
//! eventually resolve in.
//! - [`AbsPath::join`] only accepts a [`RelPath`], which kills the "join an
//! absolute onto an absolute and silently drop the base" footgun by
//! construction.
//! - [`RelPath<ConfigRelative>::bind_to_host`] is the one sanctioned way to
//! leave the [`ConfigRelative`] realm.
//!
//! # Example
//!
//! ```
//! use paths::{AbsPath, Host, RelPath};
//!
//! let base: AbsPath<Host> = AbsPath::try_new("/etc/minimal").unwrap();
//! let rel: RelPath<Host> = RelPath::try_new("hooks/cleanup.sh").unwrap();
//!
//! let joined = base.join(&rel);
//! assert_eq!(joined.as_utf8_path().as_str(), "/etc/minimal/hooks/cleanup.sh");
//!
//! // Passing an absolute string to `RelPath::try_new` is a *compile-time*-shaped
//! // error: it fails at construction, so `AbsPath::join` cannot silently
//! // override its base.
//! assert!(RelPath::<Host>::try_new("/oops/absolute").is_err());
//! ```
use camino::{Utf8Components, Utf8Path, Utf8PathBuf};
use core::fmt;
use core::marker::PhantomData;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::path::Path;
use std::str::FromStr;
/// Marker trait for filesystem realms.
///
/// Implementors are zero-sized; instances never exist at runtime — the realm
/// is encoded purely in the type system. `NAME` is used in [`fmt::Debug`]
/// output so logs and panics are unambiguous about which realm a path belongs
/// to.
pub trait Realm: 'static {
/// Lowercase identifier used in [`fmt::Debug`] output.
const NAME: &'static str;
}
/// The user's host filesystem.
#[derive(Debug, Copy, Clone)]
pub struct Host;
impl Realm for Host {
const NAME: &'static str = "host";
}
/// A sandbox rootfs constructed by `sandbox`.
#[derive(Debug, Copy, Clone)]
pub struct Sandbox;
impl Realm for Sandbox {
const NAME: &'static str = "sandbox";
}
/// The minimald daemon's filesystem view (future).
#[derive(Debug, Copy, Clone)]
pub struct Daemon;
impl Realm for Daemon {
const NAME: &'static str = "daemon";
}
/// A path whose anchor is "the directory of the config file it was decoded
/// from".
///
/// [`ConfigRelative`] paths cannot be used directly — they must be bound to a
/// concrete host directory via
/// [`RelPath::<ConfigRelative>::bind_to_host`].
#[derive(Debug, Copy, Clone)]
pub struct ConfigRelative;
impl Realm for ConfigRelative {
const NAME: &'static str = "config-relative";
}
/// Absolute path on the user's host filesystem.
pub type HostAbsPath = AbsPath<Host>;
/// Relative path resolved against a [`Host`]-realm anchor.
pub type HostRelPath = RelPath<Host>;
/// Either an absolute or relative path in the [`Host`] realm.
pub type HostPath = EitherPath<Host>;
/// Absolute path inside a sandbox rootfs.
pub type SandboxAbsPath = AbsPath<Sandbox>;
/// Relative path resolved against a [`Sandbox`]-realm anchor.
pub type SandboxRelPath = RelPath<Sandbox>;
/// Either an absolute or relative path in the [`Sandbox`] realm.
pub type SandboxPath = EitherPath<Sandbox>;
/// Absolute path in the minimald daemon's filesystem view.
pub type DaemonAbsPath = AbsPath<Daemon>;
/// Relative path resolved against a [`Daemon`]-realm anchor.
pub type DaemonRelPath = RelPath<Daemon>;
/// Either an absolute or relative path in the [`Daemon`] realm.
pub type DaemonPath = EitherPath<Daemon>;
/// Relative path anchored to the directory of the config file it was decoded
/// from. There is no absolute variant — config-relative paths only make
/// sense as relatives waiting to be bound via
/// [`RelPath::<ConfigRelative>::bind_to_host`].
pub type ConfigRelPath = RelPath<ConfigRelative>;
/// Returns minimal's default cache directory, `<cache>/minimal`.
///
/// The base is the platform cache directory (e.g. `$XDG_CACHE_HOME` or
/// `~/.cache` on Linux), falling back to `~/.cache` when it cannot be
/// determined.
///
/// # Panics
///
/// Panics if neither a cache directory nor a home directory can be resolved,
/// or if the resulting path is not valid UTF-8.
pub fn minimal_cache_dir() -> DaemonAbsPath {
default_dir(dirs::cache_dir, ".cache")
}
/// Returns minimal's default state directory, `<state>/minimal`.
///
/// The base is `$XDG_STATE_HOME` when set (honored on all platforms;
/// `dirs::state_dir` ignores it on macOS), else the platform state directory,
/// else `~/.local/state`.
///
/// # Panics
///
/// Panics if neither a state directory nor a home directory can be resolved,
/// or if the resulting path is not valid UTF-8.
pub fn minimal_state_dir() -> DaemonAbsPath {
try_minimal_state_dir().expect("could not determine home directory")
}
/// [`minimal_state_dir`] without the panics: `None` when neither a state
/// directory nor a home directory can be resolved, or the path is not valid
/// UTF-8 or not absolute. For a caller that can do without the directory
/// (a spool that then writes nothing) rather than one that cannot start.
pub fn try_minimal_state_dir() -> Option<DaemonAbsPath> {
let explicit = std::env::var_os("XDG_STATE_HOME")
.map(std::path::PathBuf::from)
.filter(|p| p.is_absolute());
try_default_dir(|| explicit.or_else(dirs::state_dir), ".local/state")
}
/// File name of the daemon SSH socket in a host dir. Served by
/// native minimald or by the minvmd host↔guest bridge — one endpoint either way.
pub const SSH_SOCK_FILE: &str = "ssh.sock";
/// File name of the SSH `known_hosts` in a host dir, recording the
/// daemon's host key under the `local-<kind><instance>` hostname. Written at
/// startup by native minimald, and by minvmd from the guest's boot beacon.
pub const KNOWN_HOSTS_FILE: &str = "known_hosts";
/// Native minimald's single-instance lock, held for the daemon's lifetime.
pub const MINIMALD_LOCK_FILE: &str = "minimald.lock";
/// The minvmd supervisor's alive lock, held for the daemon's lifetime.
pub const MINVMD_LOCK_FILE: &str = "minvmd.lock";
/// The socket the placement unit `min finalize-install` installs listens on
/// (`minimald-place.socket`), which native minimald connects to once its
/// listener is bound. systemd holds it in `/run`, owned by the delegated
/// account with mode 0600, so only that account and root connect. systemd
/// starts the root-owned placer for each connection. The placer finds the
/// daemon from the holders of its listening socket, never from the
/// connection, so a connection asks for a placement and names nothing.
pub const PLACE_REQUEST_SOCKET: &str = "/run/minimald-place.sock";
/// Which local daemon backend (box host) an instance directory belongs to.
///
/// The kind is embedded in the instance name so the native host minimald and
/// the minvmd microVM backends occupy distinct host dirs — and distinct SSH
/// host-key identities — rather than colliding on a shared `local-<N>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostKind {
/// Native host minimald (DM2).
Minimald,
/// minimald inside the minvmd microVM (DM1).
Minvmd,
}
impl HostKind {
/// The tag embedded in the instance name (`local-<tag><instance>`).
#[must_use]
pub fn tag(self) -> &'static str {
match self {
HostKind::Minimald => "minimald",
HostKind::Minvmd => "minvmd",
}
}
}
/// The host name, `local-<kind><instance>` (e.g. `local-minimald0`,
/// `local-minvmd0`). Used both as the `providers/<name>` directory name and as
/// the SSH host-key identity recorded in `known_hosts`.
#[must_use]
pub fn host_name(kind: HostKind, instance: u32) -> String {
format!("local-{}{instance}", kind.tag())
}
/// The SSH host alias a client connects with for a host directory. This
/// is the single source of the `known_hosts` host identity — the daemon
/// records the guest key under it and the ssh readers derive it from the
/// socket's parent directory, so the two can never disagree.
///
/// A host dir (`providers/<name>`) maps to its basename, so the
/// default VM keeps `local-minvmd0`. A named VM's dir nests one level deeper
/// (`providers/local-minvmd0/<vm>`) and maps to `<vm>.local-minvmd0`: ssh
/// matches the host argument against the user's `~/.ssh/config` `Host`
/// blocks, and a bare user-chosen VM name (`dev`, `work`) could pick up a
/// block meant for a real machine. VM names never contain `.`, so the
/// namespaced form cannot clash with another VM's alias.
#[must_use]
pub fn ssh_host_alias(host_dir: &Path) -> Option<String> {
let name = host_dir.file_name()?.to_str()?;
match host_dir
.parent()
.and_then(Path::file_name)
.and_then(|n| n.to_str())
{
Some(parent) if parent != "providers" => Some(format!("{name}.{parent}")),
_ => Some(name.to_owned()),
}
}
/// `<state_dir>/providers/local-<kind><instance>` — the directory holding the
/// sockets, locks, and state files a client needs to reach one local daemon
/// instance.
pub fn host_dir(state_dir: &DaemonAbsPath, kind: HostKind, instance: u32) -> DaemonAbsPath {
sub_path!(state_dir, "providers").sub_path_unchecked(&host_name(kind, instance))
}
/// The VM name that means "the default VM": the single unnamed instance whose
/// on-disk layout predates named VMs. Every path of that VM must stay
/// unchanged (NET-053), so it resolves to the host dir itself
/// rather than a per-name subdirectory.
pub const DEFAULT_VM_NAME: &str = "default";
/// The longest VM name [`validate_vm_name`] accepts. The cap keeps a named
/// VM's socket paths inside the platform's unix-socket budget at the default
/// state dir: the 104-byte macOS `sun_path` leaves about this much for the
/// name under `.../providers/local-minvmd0/<name>/gvproxy-switch.sock`.
const MAX_VM_NAME_BYTES: usize = 24;
/// The VM name reserved for the in-guest diagnostic bundle's directory inside
/// a host dir (`providers/<host>/guest/`, see the `min` diag
/// collector): a VM named `guest` would collide with it and be invisible to
/// every diagnostic listing.
const RESERVED_VM_NAME: &str = "guest";
/// Whether one byte of a VM name is inside the allowed character set.
fn vm_name_byte_allowed(b: u8) -> bool {
b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'
}
/// Validate a VM name (`--vm <NAME>`): it names a directory under the host
/// dir, so the rule is an allowlist, not a sanitiser — ASCII lowercase
/// letters, digits and `-`, at most [`MAX_VM_NAME_BYTES`] bytes, starting
/// with a letter or digit, and never the reserved [`RESERVED_VM_NAME`]. A name
/// that fits can only select a subdirectory *under* the host dir: it can
/// never escape it, and it can never shadow one of the host dir's own
/// files (`ssh.sock`, the payload `guest/` dir).
///
/// # Errors
///
/// [`Error::InvalidVmName`] when `vm` breaks any rule above; the error's
/// message states the whole rule.
pub fn validate_vm_name(vm: &str) -> Result<(), Error> {
let bytes = vm.as_bytes();
if bytes.is_empty()
|| bytes.len() > MAX_VM_NAME_BYTES
|| bytes[0] == b'-'
|| vm == RESERVED_VM_NAME
|| !bytes.iter().all(|b| vm_name_byte_allowed(*b))
{
return Err(Error::InvalidVmName(vm.to_owned()));
}
Ok(())
}
/// The per-name host dir (NET-052, NET-054): the directory
/// holding one named VM's own state files, socket, and locks.
///
/// A named VM — any `vm` other than [`DEFAULT_VM_NAME`] — nests under a
/// per-name subdirectory:
/// `<state_dir>/providers/local-<kind><instance>/<vm>/`. The default VM
/// resolves to the host dir itself, exactly as
/// [`host_dir`] does, so its paths are unchanged (NET-053).
///
/// # Errors
///
/// [`Error::InvalidVmName`] when `vm` breaks the naming rule (see
/// [`validate_vm_name`]).
pub fn host_dir_named(
state_dir: &DaemonAbsPath,
kind: HostKind,
instance: u32,
vm: &str,
) -> Result<DaemonAbsPath, Error> {
let base = host_dir(state_dir, kind, instance);
if vm == DEFAULT_VM_NAME {
return Ok(base);
}
validate_vm_name(vm)?;
Ok(base.sub_path_unchecked(vm))
}
/// Migrate legacy `providers/local-<N>` instance dirs — the pre-split naming,
/// from before the native minimald and minvmd backends had distinct identities
/// — to the kind-tagged scheme (`local-minimald<N>` / `local-minvmd<N>`), so
/// existing on-disk instances are not orphaned by the rename.
///
/// Each legacy dir's kind is inferred from its contents (see
/// [`classify_legacy_host_dir`]). Best-effort and idempotent: it never
/// aborts the caller. Only genuine I/O failures (an unreadable providers dir, a
/// failed rename) warn on stderr — these are rare and actionable. The benign
/// "nothing to migrate here" outcomes are silent so the CLI, which runs this on
/// every command, does not repeat a warning: a dir whose contents are ambiguous
/// or empty, or whose kind-tagged target already exists, is simply left in
/// place rather than clobbered or guessed at. Runs over every legacy dir found,
/// not just instance 0.
///
/// This renames the directory only; it does not coordinate with a running
/// daemon. A live daemon keeps serving via its already-open socket/lock inodes
/// (which survive a dir rename on Unix), but stopping daemons before upgrading
/// avoids the edge entirely.
pub fn migrate_legacy_host_dirs(state_dir: &DaemonAbsPath) {
let providers = sub_path!(state_dir, "providers");
let providers = providers.as_utf8_path().as_std_path();
let entries = match std::fs::read_dir(providers) {
Ok(entries) => entries,
// Nothing was ever spawned here — no migration to do.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
Err(e) => {
eprintln!(
"warning: could not scan {} for legacy provider dirs: {e}",
providers.display()
);
return;
}
};
for entry in entries {
let Ok(entry) = entry else { continue };
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let Ok(name) = entry.file_name().into_string() else {
continue;
};
let Some(instance) = legacy_instance_num(&name) else {
continue;
};
let path = entry.path();
// Ambiguous or empty contents: can't tell the backend apart, so leave it
// untouched. Silent — this recurs on every CLI invocation otherwise.
let Some(kind) = classify_legacy_host_dir(&path) else {
continue;
};
let target_name = host_name(kind, instance);
let target = providers.join(&target_name);
// Target already claimed: don't clobber it. Silent, for the same reason.
if target.exists() {
continue;
}
if let Err(e) = std::fs::rename(&path, &target) {
eprintln!(
"warning: failed to migrate legacy provider dir {name} -> {target_name}: {e}"
);
}
}
}
/// Parse the instance number from a legacy `local-<N>` dir name, where `<N>` is
/// one or more decimal digits. Returns `None` for the kind-tagged names
/// (`local-minimald<N>` / `local-minvmd<N>`, whose suffix is not all digits)
/// and for anything not of the `local-<digits>` shape.
fn legacy_instance_num(name: &str) -> Option<u32> {
let suffix = name.strip_prefix("local-")?;
if suffix.is_empty() || !suffix.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
suffix.parse().ok()
}
/// Infer which backend a legacy host dir belonged to from its contents.
///
/// A minvmd instance carries VM artifacts the native daemon never writes — its
/// `minvmd.toml` state file, its alive lock, or the data-volume image. A native
/// minimald dir carries an on-disk SSH host key (the guest daemon writes its key
/// inside the VM, not the host dir) or its own lock. Returns `None` when both or
/// neither class of marker is present, so the caller can skip rather than guess.
fn classify_legacy_host_dir(dir: &std::path::Path) -> Option<HostKind> {
let has = |file: &str| dir.join(file).exists();
let minvmd = has("minvmd.toml") || has(MINVMD_LOCK_FILE) || has("data-vol.raw");
let minimald = has("ssh_host_ed25519_key") || has(MINIMALD_LOCK_FILE);
match (minvmd, minimald) {
(true, false) => Some(HostKind::Minvmd),
(false, true) => Some(HostKind::Minimald),
_ => None,
}
}
/// Removes any existing [`KNOWN_HOSTS_FILE`] entries for `host` at `port` from
/// the file at `path`, so that a subsequent append records exactly one current
/// entry instead of growing the file by a line on every daemon spawn
/// (gominimal/minimal#782).
///
/// russh's `learn_known_hosts_path` appends unconditionally. Both native
/// `minimald` and `minvmd` (from the guest boot beacon) call it once per spawn
/// to record the daemon's host key under the `local-<instance>` hostname, so
/// without this prune the per-instance `known_hosts` grows without bound — and
/// because the VM guest regenerates its host key on every boot (its key lives
/// on tmpfs), the accumulating lines are stale distinct keys, not harmless
/// duplicates. Prune the prior entry first, then append the fresh one, and the
/// file holds a single up-to-date key across stop/start cycles.
///
/// Matching is by the OpenSSH host marker `learn_known_hosts_path` writes as a
/// line's first field: the bare `host` at the default port 22, or `[host]:port`
/// otherwise. Lines for any other host are preserved verbatim, so an unrelated
/// entry is never dropped. A missing file is a no-op success, and the file is
/// rewritten only when a matching entry was actually removed.
///
/// # Errors
///
/// Returns any I/O error other than "file not found" from reading or rewriting
/// `path`.
pub fn prune_known_hosts_entries(path: &Path, host: &str, port: u16) -> std::io::Result<()> {
let existing = match std::fs::read_to_string(path) {
Ok(contents) => contents,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e),
};
let marker = if port == 22 {
host.to_owned()
} else {
format!("[{host}]:{port}")
};
let mut kept = String::with_capacity(existing.len());
let mut removed = false;
for line in existing.lines() {
if line.split_whitespace().next() == Some(marker.as_str()) {
removed = true;
continue;
}
kept.push_str(line);
kept.push('\n');
}
if removed {
std::fs::write(path, kept)?;
}
Ok(())
}
/// Returns minimal's default config directory, `<config>/minimal`.
///
/// The base is `$XDG_CONFIG_HOME` when set to an absolute path, otherwise
/// `~/.config` on every platform. Deliberately does not use
/// [`dirs::config_dir`]: on macOS that would produce
/// `~/Library/Application Support`, diverging from how the rest of minimal's
/// on-disk state is laid out ([`minimal_state_dir`] already falls through to
/// `~/.local/state`). One layout everywhere is easier to document, and users
/// who genuinely want the platform-native location can override with the
/// CLI's `--config-dir` flag.
///
/// # Panics
///
/// Panics if neither `$XDG_CONFIG_HOME` nor a home directory can be
/// resolved, or if the resulting path is not valid UTF-8.
pub fn minimal_config_dir() -> DaemonAbsPath {
default_dir(xdg_config_home, ".config")
}
/// Returns minimal's config directory, honouring the `--config-dir`
/// override: `<override>/minimal` when `over` is given, else the platform
/// default ([`minimal_config_dir`]). Which flag feeds `over` is the caller's
/// business; this only fixes that an override names the *parent* of the
/// `minimal/` subdirectory, so both branches produce the same layout.
///
/// The return is a plain [`std::path::PathBuf`]: a user-passed flag is
/// untyped on the way in and is not daemon-realm data, so forcing the
/// realm-tagged type on `Some` would lie — and the default branch is
/// converted down to match.
#[must_use]
pub fn minimal_config_dir_with_override(over: Option<&Path>) -> std::path::PathBuf {
match over {
Some(dir) => dir.join("minimal"),
None => minimal_config_dir()
.as_utf8_path()
.as_std_path()
.to_path_buf(),
}
}
/// [`minimal_config_dir_with_override`] without the panics: `None` when no
/// override is given and neither `$XDG_CONFIG_HOME` nor a home directory
/// resolves, or the default path is not valid UTF-8 or not absolute. For a
/// caller that runs before every command and can do without the directory.
#[must_use]
pub fn try_minimal_config_dir_with_override(over: Option<&Path>) -> Option<std::path::PathBuf> {
match over {
Some(dir) => Some(dir.join("minimal")),
None => try_default_dir(xdg_config_home, ".config")
.map(|p| p.as_utf8_path().as_std_path().to_path_buf()),
}
}
/// The certificate files the retired HTTPS reverse proxy left in the config
/// directory: the daemon-issued client certificate, its key, and the CA.
pub const RETIRED_PROXY_CREDENTIAL_FILES: [&str; 3] = ["client.pem", "client.key", "ca.pem"];
/// Deletes the retired HTTPS reverse proxy's certificate files
/// ([`RETIRED_PROXY_CREDENTIAL_FILES`]) from `config_dir`, and returns the
/// path of each file it removed.
///
/// Best-effort and idempotent: a file that is absent is skipped, and a file
/// it cannot remove is left for the next run. It prints nothing. This crate
/// has no logger, so the caller logs one line for each returned path.
// NET-109: the proxy that issued these files is gone, so nothing reads them.
#[must_use]
pub fn remove_retired_proxy_credentials(config_dir: &Path) -> Vec<std::path::PathBuf> {
RETIRED_PROXY_CREDENTIAL_FILES
.iter()
.map(|name| config_dir.join(name))
.filter(|path| std::fs::remove_file(path).is_ok())
.collect()
}
/// Return `$XDG_CONFIG_HOME` if it's set to an absolute path. Matches the
/// spec: [XDG Base Directory Specification, "XDG_CONFIG_HOME"](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html)
/// says relative paths are invalid and should be ignored.
fn xdg_config_home() -> Option<std::path::PathBuf> {
std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.filter(|p| p.is_absolute())
}
/// Returns minimal's default data directory, `<data>/minimal`.
///
/// The base is `$XDG_DATA_HOME` when set to an absolute path, otherwise
/// `~/.local/share` on every platform — the same resolution
/// `scripts/install.sh` uses for `data`-prefix components, so paths derived
/// here point at what the installer actually shipped. Like
/// [`minimal_config_dir`], deliberately not [`dirs::data_dir`]: on macOS that
/// would be `~/Library/Application Support`.
///
/// # Panics
///
/// Panics if neither `$XDG_DATA_HOME` nor a home directory can be resolved,
/// or if the resulting path is not valid UTF-8.
pub fn minimal_data_dir() -> DaemonAbsPath {
default_dir(xdg_data_home, ".local/share")
}
/// Return `$XDG_DATA_HOME` if it's set to an absolute path, per the XDG
/// spec's rule that relative paths are invalid and should be ignored.
fn xdg_data_home() -> Option<std::path::PathBuf> {
std::env::var_os("XDG_DATA_HOME")
.map(std::path::PathBuf::from)
.filter(|p| p.is_absolute())
}
/// [`default_dir`] without the panics: `None` where it would panic.
fn try_default_dir(
base_dir: impl FnOnce() -> Option<std::path::PathBuf>,
home_fallback: &str,
) -> Option<DaemonAbsPath> {
let base = match base_dir() {
Some(b) => b,
None => dirs::home_dir()?.join(home_fallback),
};
let path = Utf8PathBuf::from_path_buf(base.join("minimal")).ok()?;
DaemonAbsPath::try_new(path).ok()
}
/// Computes `<base>/minimal`, where `base` comes from `base_dir` or, failing
/// that, `~/<home_fallback>`.
fn default_dir(
base_dir: impl FnOnce() -> Option<std::path::PathBuf>,
home_fallback: &str,
) -> DaemonAbsPath {
let base = base_dir().unwrap_or_else(|| {
dirs::home_dir()
.expect("could not determine home directory")
.join(home_fallback)
});
let path = Utf8PathBuf::from_path_buf(base.join("minimal"))
.expect("default directory path is not valid UTF-8");
DaemonAbsPath::try_new(path).expect("default directory path is not absolute")
}
/// Errors produced when constructing a path.
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum Error {
/// An [`AbsPath`] was constructed from a non-absolute input.
#[error("expected an absolute path, got: {0}")]
NotAbsolute(Utf8PathBuf),
/// A [`RelPath`] was constructed from an absolute input.
#[error("expected a relative path, got: {0}")]
IsAbsolute(Utf8PathBuf),
/// A [`RelPath`] contained a `..` component, which would let it
/// escape whatever base it was joined against. Rejected at
/// construction so any caller who joins the path against a
/// sensitive root (e.g. a sandbox home dir) doesn't have to
/// re-validate.
#[error("path contains a `..` traversal component: {0}")]
ContainsParentDir(Utf8PathBuf),
/// A VM name broke the naming rule, so it cannot name a per-VM
/// subdirectory. The message states the whole rule so the rejection
/// points at what a valid name is.
#[error(
"invalid VM name `{0}`: names are at most 24 bytes of ASCII lowercase letters, digits and `-`, start with a letter or digit, and `guest` is reserved"
)]
InvalidVmName(String),
}
#[doc(hidden)]
pub const fn _validate_subdir(s: &str) {
let bytes = s.as_bytes();
assert!(!bytes.is_empty(), "`sub_path` component must not be empty");
let mut i = 0;
while i < bytes.len() {
assert!(
bytes[i] != b'/',
"`sub_path` component must not contain `/`"
);
i += 1;
}
assert!(
!(bytes.len() == 2 && bytes[0] == b'.' && bytes[1] == b'.'),
"`sub_path` component must not be `..`"
);
}
/// Joins a literal representing a sub-component onto the end of a path. Will
/// emit a compile-time error if the component is not valid, for instance if
/// it contains multiple components, is absolute, or attempts directory traversal.
#[macro_export]
macro_rules! sub_path {
($base:expr, $dir:literal) => {{
#[allow(clippy::used_underscore_items)]
const _: () = $crate::_validate_subdir($dir);
($base).sub_path_unchecked($dir)
}};
}
/// An *absolute* UTF-8 path in realm `R`.
///
/// Invariant: `inner.is_absolute()` is always true. Construction goes through
/// [`AbsPath::try_new`], which validates the input.
///
/// The realm parameter is phantom: `AbsPath<Host>` and `AbsPath<Sandbox>` are
/// distinct types that the compiler will not mix. Crossing realms requires a
/// [`Translator`].
#[must_use]
pub struct AbsPath<R: Realm> {
inner: Utf8PathBuf,
_realm: PhantomData<fn() -> R>,
}
impl<R: Realm> AbsPath<R> {
/// Constructs an [`AbsPath`] after verifying the input is absolute.
///
/// # Errors
///
/// Returns [`Error::NotAbsolute`] if `p` is relative.
pub fn try_new(p: impl Into<Utf8PathBuf>) -> Result<Self, Error> {
let inner = p.into();
if inner.is_absolute() {
Ok(Self {
inner,
_realm: PhantomData,
})
} else {
Err(Error::NotAbsolute(inner))
}
}
/// Construct an [`AbsPath`] without verifying that `p` is
/// absolute.
///
/// Use only when the caller has already proven absoluteness by
/// other means (e.g. the path came from `walkdir::WalkDir::new`
/// rooted at an absolute path). A `debug_assert!` catches misuse
/// in development builds; release builds skip the check.
pub fn new_unchecked(p: impl Into<Utf8PathBuf>) -> Self {
let p = p.into();
debug_assert!(p.is_absolute());
Self {
inner: p,
_realm: PhantomData,
}
}
/// Returns the root path (`/`), assuming a POSIX-like system.
///
/// This is a convenience for places that need a known-absolute
/// root in the [`Realm`] of the caller. Not appropriate on
/// Windows, where the root concept differs.
pub fn root() -> Self {
Self {
inner: Utf8PathBuf::from("/"),
_realm: PhantomData,
}
}
/// Borrows the underlying UTF-8 path.
#[must_use]
pub fn as_utf8_path(&self) -> &Utf8Path {
&self.inner
}
/// Borrows the underlying path as a `&str`.
#[must_use]
pub fn as_str(&self) -> &str {
self.inner.as_str()
}
/// Joins a relative path *in the same realm*, producing a new
/// [`AbsPath<R>`].
///
/// Unlike [`Utf8PathBuf::join`], this cannot be passed an absolute path:
/// [`RelPath`] is constructively non-absolute, so the "join overrides
/// base" footgun is unreachable.
pub fn join(&self, rel: &RelPath<R>) -> AbsPath<R> {
AbsPath {
inner: self.inner.join(&
10BC8
;rel.inner),
_realm: PhantomData,
}
}
/// Joins a single sub-component *in the same realm*, producing a new
/// [`AbsPath<R>`].
///
/// Trusts the caller; prefer the [`sub_path!`] macro at literal call
/// sites so the constraint is enforced at compile time.
pub fn sub_path_unchecked(&self, dir: &str) -> AbsPath<R> {
AbsPath {
inner: self.inner.join(dir),
_realm: PhantomData,
}
}
/// Returns the parent directory, if any.
#[must_use]
pub fn parent(&self) -> Option<AbsPath<R>> {
self.inner.parent().map(|p| AbsPath {
inner: p.to_owned(),
_realm: PhantomData,
})
}
/// Strips `base` from the front of this path and returns the suffix as
/// a [`RelPath<R>`].
///
/// # Errors
///
/// Returns [`std::path::StripPrefixError`] when `base` is not a prefix.
pub fn strip_prefix(
&self,
base: &AbsPath<R>,
) -> Result<RelPath<R>, std::path::StripPrefixError> {
self.inner.strip_prefix(&base.inner).map(|p| RelPath {
inner: p.to_owned(),
_realm: PhantomData,
})
}
/// Returns true if `base` is a prefix of this path.
///
/// Matching is by whole components, so `/srv/work` is not a prefix of
/// `/srv/workbench`. `base` is an [`AbsPath`] in the *same* realm: a
/// containment check across realms compares paths from two different
/// filesystems and is meaningless.
#[must_use]
pub fn starts_with(&self, base: &AbsPath<R>) -> bool {
self.inner.starts_with(&base.inner)
}
/// The final component of the path, if any.
#[must_use]
pub fn file_name(&self) -> Option<&str> {
self.inner.file_name()
}
/// The extension of the final component, if any.
#[must_use]
pub fn extension(&self) -> Option<&str> {
self.inner.extension()
}
/// Iterator over the path's components.
pub fn components(&self) -> Utf8Components<'_> {
self.inner.components()
}
/// Returns an absolute path representing the current
/// working directory in the current realm.
///
/// # Errors
///
/// * The current directory is not accessible
/// * The current directory contains non-UTF8 characters.
pub fn from_cwd() -> Result<Self, std::io::Error> {
let Ok(cwd) = Utf8PathBuf::from_path_buf(std::env::current_dir()?) else {
return Err(std::io::Error::other("cwd contains not-utf8 characters"));
};
Ok(Self {
inner: cwd,
_realm: PhantomData,
})
}
}
impl<R: Realm> Clone for AbsPath<R> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_realm: PhantomData,
}
}
}
impl<R: Realm> PartialEq for AbsPath<R> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<R: Realm> Eq for AbsPath<R> {}
impl<R: Realm> std::hash::Hash for AbsPath<R> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.hash(state);
}
}
impl<R: Realm> PartialOrd for AbsPath<R> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<R: Realm> Ord for AbsPath<R> {
fn cmp(&self, other: &Self) -> Ordering {
self.inner.cmp(&other.inner)
}
}
impl<R: Realm> AsRef<Utf8Path> for AbsPath<R> {
fn as_ref(&self) -> &Utf8Path {
&self.inner
}
}
impl<R: Realm> AsRef<Path> for AbsPath<R> {
fn as_ref(&self) -> &Path {
self.inner.as_std_path()
}
}
impl<R: Realm> AsRef<str> for AbsPath<R> {
fn as_ref(&self) -> &str {
self.inner.as_str()
}
}
impl<R: Realm> Borrow<Utf8Path> for AbsPath<R> {
fn borrow(&self) -> &Utf8Path {
&self.inner
}
}
impl<R: Realm> FromStr for AbsPath<R> {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_new(s)
}
}
impl<R: Realm> fmt::Debug for AbsPath<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AbsPath<{}>({})", R::NAME, self.inner)
}
}
impl<R: Realm> fmt::Display for AbsPath<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.inner, f)
}
}
impl<R: Realm> serde::Serialize for AbsPath<R> {
fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
self.inner.serialize(ser)
}
}
impl<'de, R: Realm> serde::Deserialize<'de> for AbsPath<R> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let p = Utf8PathBuf::deserialize(deserializer)?;
Self::try_new(p).map_err(serde::de::Error::custom)
}
}
/// A *relative* UTF-8 path, tagged with the realm it will resolve in.
///
/// Invariant: `inner.is_absolute()` is always false. Construction goes
/// through [`RelPath::new`], which validates the input.
#[must_use]
pub struct RelPath<R: Realm> {
inner: Utf8PathBuf,
_realm: PhantomData<fn() -> R>,
}
impl<R: Realm> RelPath<R> {
/// Constructs a [`RelPath`] after verifying the input is neither
/// absolute nor contains a `..` traversal component.
///
/// The `..` rejection is what lets callers like the daemon
/// composer trust a [`SandboxRelPath`] arriving over the wire —
/// joining it against the sandbox home can't produce a path
/// outside that home.
///
/// # Errors
///
/// - [`Error::IsAbsolute`] if `p` is an absolute path.
/// - [`Error::ContainsParentDir`] if any component is `..`.
pub fn try_new(p: impl Into<Utf8PathBuf>) -> Result<Self, Error> {
let inner = p.into();
if inner.is_absolute() {
return Err(Error::IsAbsolute(inner));
}
if inner
.components()
.any(|c| matches!(c, camino::Utf8Component::ParentDir))
{
return Err(Error::ContainsParentDir(inner));
}
Ok(Self {
inner,
_realm: PhantomData,
})
}
/// Construct a [`RelPath`] without verifying that `p` is
/// relative.
///
/// Use only when the caller has already proven relativity by other
/// means (e.g. the path was produced by `strip_prefix` against a
/// known absolute root). A `debug_assert!` catches misuse in
/// development builds; release builds skip the check.
pub fn new_unchecked(p: impl Into<Utf8PathBuf>) -> Self {
let p = p.into();
debug_assert!(p.is_relative());
debug_assert!(
!p.components()
.any(|c| matches!(c, camino::Utf8Component::ParentDir)),
"`RelPath::new_unchecked` fed a path with a `..` component: {p}"
);
Self {
inner: p,
_realm: PhantomData,
}
}
/// Borrows the underlying UTF-8 path.
#[must_use]
pub fn as_utf8_path(&self) -> &Utf8Path {
&self.inner
}
/// Borrows the underlying path as a `&str`.
#[must_use]
pub fn as_str(&self) -> &str {
self.inner.as_str()
}
/// Joins another relative path in the same realm.
pub fn join(&self, other: &RelPath<R>) -> RelPath<R> {
RelPath {
inner: self.inner.join(&other.inner),
_realm: PhantomData,
}
}
/// Joins a single sub-component *in the same realm*, producing a new
/// [`RelPath<R>`].