-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathnsproxy.rs
More file actions
5651 lines (5256 loc) · 235 KB
/
Copy pathnsproxy.rs
File metadata and controls
5651 lines (5256 loc) · 235 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
#![feature(ip_as_octets)]
use anyhow::ensure;
use capctl::prctl;
/// This binary will at most spawn 2 processes (including itself)
/// It's intended to be minimal, which can be used later in higher order composition such as in GUI
use clap::{
CommandFactory, Parser, Subcommand, ValueEnum,
builder::{TypedValueParser, ValueParser, ValueParserFactory},
};
use clap_complete::{generate, shells::Fish};
use futures::stream::{FuturesUnordered, TryStreamExt};
use futures::{
AsyncWriteExt, SinkExt, StreamExt,
channel::{
mpsc::{self, unbounded},
oneshot,
},
future::join_all,
};
use reqwest::redirect::Policy;
use socks5_impl::protocol::WireAddress;
use tokio::{
io::{AsyncReadExt as _, AsyncWriteExt as TokioWriteExt},
time::sleep,
};
use futures_lite::future::block_on;
use hardware_address::MacAddr;
use ipnetwork::{IpNetwork, Ipv4Network};
use libc::KERN_HOTPLUG;
use nix::{
mount::{MsFlags, mount as nix_mount},
pty::openpty,
sched::{CloneFlags, unshare},
unistd::{
ForkResult, Gid, Pid, Uid, chdir, chown, dup2, execve, fork, getresgid, getresuid, pipe,
setgroups, setpgid, setresgid, setresuid, setsid,
},
};
use notify::{Event, EventKind, RecommendedWatcher, Watcher, event::ModifyKind};
use nsproxy_common::{
ExactNS, NSFrom, NSSource, NamespacesRegistry, PidPath, ProfileNamespaces, UniqueFile, forever,
};
use nsproxy_core::{
BasisCommand, Cli, DaemonCliRequest, HotConfig, MainCommand, NetlinkOps, NsproxyConfig, Paths,
PathsBinds, SandboxMode, TemplateConfig, TunMaker,
cmd_common::{
apply_ns_env, check_proxy_mode, enter_ns, enter_ns_sandboxed, read_ns_alive,
read_ns_alive_opt, report_clone3_err, update_ns_alive,
},
env::{ENV_DBUS_SESSION_BUS_ADDRESS, ENV_NS, args_deduce_mount, name_to_mount_path},
hot_reload::{VethIps, sync_links, watch_hot},
sandbox::{
apply_chmod, apply_mounts, assert_mount_ns_matches, collect_sandbox_status,
read_sandbox_status, write_sandbox_status,
},
shell::{ShellArgs, ShellPrefs},
state_paths,
sys::{
Clone3Result, NSEnter, check_capsys, check_selfns, enable_ping_all, mount_bind,
mount_bind_ro_explicit, mount_bind_root, mount_bind_rw_explicit, mount_ns,
mount_nsswitch_conf, mount_resolv_conf, mount_tmpfs, pivot_root_into,
replace_mount_resolv_conf, rm_mount, umount_detach_targets,
},
tokio_netlink_conn,
utils::ToExactNs,
};
use nsproxy_core::{
cmd_uplink::{cmd_uplink, load_saved_uplink_hub},
env::{ENV_CONTAINER, ENV_PROFILE},
*,
};
use owo_colors::OwoColorize;
use passfd::FdPassingExt;
use pidfd::PidFd;
use rtnetlink::packet_route::{
AddressFamily,
link::{LinkAttribute, LinkExtentMask, LinkFlags, LinkHeader},
};
use rtnetlink::{Handle, LinkMessageBuilder, LinkUnspec, LinkVeth};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, HashMap, HashSet, VecDeque, hash_map::Entry},
convert::Infallible,
ffi::OsStr,
fs::{self, Permissions},
future::{pending, ready},
io::{ErrorKind, Read, Write},
mem::ManuallyDrop,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
os::{
fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd},
unix::{
fs::{FileTypeExt, MetadataExt, PermissionsExt, symlink},
net::UnixStream,
process::CommandExt,
},
},
path::{Component, Path, PathBuf},
pin::Pin,
process::{Command, Stdio, exit},
str::FromStr,
sync::Mutex,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant, SystemTime},
};
use tokio::{select, sync};
use tracing::{error, info, level_filters::LevelFilter, warn};
use tracing_subscriber::{Layer, fmt, layer::SubscriberExt, util::SubscriberInitExt};
use tun2socks5::{
ArgMode, IArgs, VirtDNSChange, aok, diag,
dns::VirtDNSHandle,
flume,
ipstack::stream::{IpStackStream, IpStackTcpStream},
tun_rs::AsyncDevice,
};
use uzers::os::unix::UserExt;
use nsproxy_core::HotRoute;
#[derive(Debug, Clone)]
struct VethEndpoint {
arg: NsArg,
label: String,
pid: u32,
}
#[derive(Debug, Serialize, Deserialize)]
enum NetnsChildResult<T> {
Ok(T),
Err(String),
}
use nsproxy_core::internal_dns::run_dns_ipv4_only;
const PTY_SCROLLBACK_CAP: usize = 256 * 1024;
const PTY_BROADCAST_CAP: usize = 128;
struct PtyScrollbackState {
cap: usize,
ring: VecDeque<u8>,
}
impl PtyScrollbackState {
fn new(cap: usize) -> Self {
Self {
cap,
ring: VecDeque::with_capacity(cap),
}
}
}
struct RawLogRingState {
cap: usize,
ring: VecDeque<diag::RawLog>,
}
impl RawLogRingState {
fn new(cap: usize) -> Self {
Self {
cap,
ring: VecDeque::with_capacity(cap),
}
}
}
fn profile_bus_socket(profile: &str) -> PathBuf {
state_paths::profile_dir(profile).join("bus").join("session.sock")
}
fn profile_bus_address(profile: &str) -> String {
format!("unix:path={}", profile_bus_socket(profile).display())
}
fn session_bus_ready(socket_path: &Path) -> bool {
if !fs::symlink_metadata(socket_path).is_ok_and(|metadata| metadata.file_type().is_socket()) {
return false;
}
let address = format!("unix:path={}", socket_path.display());
let mut child = match Command::new("dbus-send")
.arg(format!("--bus={address}"))
.args([
"--dest=org.freedesktop.DBus",
"--type=method_call",
"--print-reply",
"/org/freedesktop/DBus",
"org.freedesktop.DBus.ListNames",
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
Ok(child) => child,
Err(err) => {
warn!(%err, "cannot run dbus-send to check private session bus health");
return false;
}
};
let deadline = Instant::now() + Duration::from_secs(2);
loop {
match child.try_wait() {
Ok(Some(status)) => return status.success(),
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
Ok(None) => {
warn!(socket = %socket_path.display(), "private session bus health check timed out");
let _ = child.kill();
let _ = child.wait();
return false;
}
Err(err) => {
warn!(%err, socket = %socket_path.display(), "private session bus health check failed");
return false;
}
}
}
}
fn dbus_mode_for_profile(ns_alive: &nsproxy_core::NsAlive) -> nsproxy_core::DbusMode {
ns_alive
.profile_name
.as_ref()
.and_then(|profile| TemplateConfig::load(&state_paths::profile_config(profile)).ok())
.map(|template| template.dbus)
.unwrap_or_default()
}
fn maybe_session_bus_address(ns_alive: &nsproxy_core::NsAlive) -> Option<String> {
let profile = ns_alive.profile_name.as_deref()?;
match dbus_mode_for_profile(ns_alive) {
nsproxy_core::DbusMode::Block => None,
nsproxy_core::DbusMode::Pass => std::env::var(ENV_DBUS_SESSION_BUS_ADDRESS).ok(),
nsproxy_core::DbusMode::Proxy => None,
nsproxy_core::DbusMode::Container => Some(profile_bus_address(profile)),
}
}
/// Apply the correct D-Bus environment to `shell_prefs` based on the profile's DbusMode.
/// Must be called AFTER `shell_prefs.adjust()`:
/// - Block: strip DBUS_SESSION_BUS_ADDRESS (adjust() captured it from parent env)
/// - Pass: do nothing (already inherited from parent env via adjust())
/// - Container: replace with the private per-profile dbus-daemon socket address
fn apply_dbus_env(shell_prefs: &mut ShellPrefs, ns_alive: &nsproxy_core::NsAlive) {
match dbus_mode_for_profile(ns_alive) {
nsproxy_core::DbusMode::Block => shell_prefs.strip_dbus_env(),
nsproxy_core::DbusMode::Pass => {}
// Retain the legacy config value without preserving the old incomplete
// proxy implementation or exposing the host bus by accident.
nsproxy_core::DbusMode::Proxy => shell_prefs.strip_dbus_env(),
nsproxy_core::DbusMode::Container => {
if let Some(profile) = ns_alive.profile_name.as_deref() {
shell_prefs.set_dbus_session_bus_env(&profile_bus_address(profile));
}
}
}
}
/// Run one self-contained session bus for a container.
///
/// Unlike `dbus-broker-launch`, `dbus-daemon` handles traditional D-Bus service
/// activation itself, without requiring a host or nested systemd user manager.
/// The daemon is run in the foreground so the `sp dbus` task group owns its
/// lifetime and the UI can report it just like `sp serve`.
fn run_container_dbus_daemon(socket_path: &Path) -> Result<()> {
let address = format!("unix:path={}", socket_path.display());
// `sp` is setuid-root, but the daemon must use the profile owner's real
// credentials. Otherwise it inherits a mixed real/user and effective/root
// identity, which can leave a socket that accepts connections but cannot
// complete D-Bus authentication.
let uid = getresuid()?.real.as_raw();
let gid = getresgid()?.real.as_raw();
let runtime_dir = socket_path
.parent()
.ok_or_else(|| anyhow!("private session-bus socket has no parent directory"))?;
fs::create_dir_all(runtime_dir)?;
chown(
runtime_dir,
Some(Uid::from_raw(uid)),
Some(Gid::from_raw(gid)),
)?;
fs::set_permissions(runtime_dir, Permissions::from_mode(0o700))?;
let mut command = Command::new("dbus-daemon");
command
.args(["--session", "--nofork", "--nopidfile"])
.arg(format!("--address={address}"))
.uid(uid)
.gid(gid)
// Activated services receive DBUS_STARTER_ADDRESS from the daemon.
// Do not preserve the host session address in their inherited env.
.env_remove(ENV_DBUS_SESSION_BUS_ADDRESS);
let status = command.status()?;
let _ = fs::remove_file(socket_path);
ensure!(status.success(), "dbus-daemon exited with {status}");
Ok(())
}
fn build_spawn_env_pairs(
ns_alive: &nsproxy_core::NsAlive,
dbus_address: Option<&str>,
) -> Vec<(String, String)> {
let container_val = ns_alive
.profile_name
.clone()
.unwrap_or_else(|| "UNSPEC".to_string());
let profile_val = ns_alive
.browser_profile
.clone()
.unwrap_or_else(|| "UNSPEC".to_string());
let ns_val = ns_alive.bind_mount.to_string_lossy().to_string();
unsafe {
std::env::set_var(ENV_CONTAINER, &container_val);
std::env::set_var(ENV_PROFILE, &profile_val);
std::env::set_var(ENV_NS, &ns_val);
}
let mut env_pairs: Vec<(String, String)> = std::env::vars().collect();
env_pairs.retain(|(k, _)| {
k != ENV_CONTAINER && k != ENV_PROFILE && k != ENV_NS && k != ENV_DBUS_SESSION_BUS_ADDRESS
});
env_pairs.push((ENV_CONTAINER.to_string(), container_val));
env_pairs.push((ENV_PROFILE.to_string(), profile_val));
env_pairs.push((ENV_NS.to_string(), ns_val));
if let Some(address) = dbus_address {
unsafe {
std::env::set_var(ENV_DBUS_SESSION_BUS_ADDRESS, address);
}
env_pairs.push((
ENV_DBUS_SESSION_BUS_ADDRESS.to_string(),
address.to_string(),
));
}
env_pairs
}
fn build_spawn_env_cstrings(
ns_alive: &nsproxy_core::NsAlive,
dbus_address: Option<&str>,
) -> Result<Vec<std::ffi::CString>> {
build_spawn_env_pairs(ns_alive, dbus_address)
.into_iter()
.map(|(k, v)| std::ffi::CString::new(format!("{}={}", k, v)))
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(Into::into)
}
fn main() -> anyhow::Result<()> {
// Ignore SIGPIPE so logging to a closed pipe does not kill the daemon.
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_IGN);
libc::signal(libc::SIGHUP, libc::SIG_IGN);
}
// Fast path: `sp <fd_num>` — read a bincode-encoded `Cli` directly from the fd.
// This lets callers (e.g. the GUI) pass structured args without string conversion.
let mut cli = {
let raw_args: Vec<String> = std::env::args().collect();
if raw_args.len() == 2 {
if let Ok(fd) = raw_args[1].parse::<i32>() {
nsproxy_core::decode_cli_from_fd(fd)?
} else {
Cli::parse()
}
} else {
Cli::parse()
}
};
if let Some(root) = cli.root.clone() {
state_paths::set_persist_root(root.clone());
info!("Using state root: {:?}", root);
}
diag::set_protocol_version(nsproxy_core::build_identity());
// DEBUG is annoying because its filled with TCP retransmission logs
let (layer, reload_handle) = tracing_subscriber::reload::Layer::new(
fmt::Layer::new()
.without_time()
.with_filter(LevelFilter::INFO),
);
// https://docs.rs/tracing-subscriber/latest/tracing_subscriber/layer/trait.Layer.html
tracing_subscriber::registry()
.with(layer)
.with(diag::DiagTracingLayer)
.init();
let pid = nix::unistd::Pid::this();
use rlimit as rl;
let (soft, hard) = rl::Resource::NOFILE.get()?;
if !matches!(&cli.cmd, MainCommand::Id { .. }) {
info!(
"open file limits, soft={}, hard={}. trying to raise soft limit to max",
soft, hard
);
}
rl::Resource::NOFILE.set(hard, hard)?;
match cli.cmd {
MainCommand::Socks5 { port } => {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
rt.block_on(async {
use socks5_impl::protocol::*;
use socks5_impl::server::*;
warn!("starting socks server on 0.0.0.0:{}", port);
let addr = format!("0.0.0.0:{}", port);
let server = Server::bind(addr.parse()?, Arc::new(auth::NoAuth)).await?;
loop {
let (conn, _) = server.accept().await?;
tokio::spawn(async {
if let Err(err) = handle_socks5_connection(conn).await {
warn!("socks5 connection error: {}", err);
}
});
}
aok!()
})?;
}
MainCommand::Rm { file } => {
rm_mount(&file)?;
}
MainCommand::Id { pid } => {
// Keep this command output clean and human-focused.
let _ = reload_handle.modify(|k| *k.filter_mut() = LevelFilter::WARN);
let env_value = |key: &str| std::env::var(key).ok().filter(|v| !v.is_empty());
let fmt_env = |v: Option<String>| v.unwrap_or_else(|| "-".to_string());
let container = env_value(ENV_CONTAINER);
let browser = env_value(ENV_PROFILE);
let netns = env_value(ENV_NS);
let target_pid = pid;
let target_ns = if let Some(pid) = target_pid {
Some(ProfileNamespaces {
mnt: ExactNS::from_source((PidPath::N(pid as i32), "mnt"))?,
net: ExactNS::from_source((PidPath::N(pid as i32), "net"))?,
pid: ExactNS::from_source((PidPath::N(pid as i32), "pid"))?,
})
} else {
None
};
let self_ns = ProfileNamespaces {
mnt: ExactNS::from_source((PidPath::Selfproc, "mnt"))?,
net: ExactNS::from_source((PidPath::Selfproc, "net"))?,
pid: ExactNS::from_source((PidPath::Selfproc, "pid"))?,
};
let print_divider = |widths: &[usize]| {
print!("+");
for &w in widths {
print!("{}+", "-".repeat(w + 2));
}
println!();
};
let status_width = "MISSING".len();
println!("{}", "NSPROXY ID".bold().bright_cyan());
println!(
"{} {}={} {}={} {}={}",
"env".bold().bright_black(),
"container".bright_blue(),
fmt_env(container.clone()).bright_white(),
"browser".bright_blue(),
fmt_env(browser).bright_white(),
"netns".bright_blue(),
fmt_env(netns).bright_white()
);
let self_rows = [
("mnt", self_ns.mnt.unique.to_string()),
("net", self_ns.net.unique.to_string()),
("pid", self_ns.pid.unique.to_string()),
];
let self_kind_w = self_rows
.iter()
.map(|(k, _)| k.len())
.max()
.unwrap_or(4)
.max("kind".len());
let self_ns_w = self_rows
.iter()
.map(|(_, v)| v.len())
.max()
.unwrap_or(4)
.max("self".len());
println!();
println!("{}", "self".bold().bright_magenta());
let self_widths = [self_kind_w, self_ns_w];
print_divider(&self_widths);
println!(
"| {:<kind_w$} | {:<ns_w$} |",
"kind".bold(),
"self".bold(),
kind_w = self_kind_w,
ns_w = self_ns_w
);
print_divider(&self_widths);
for (kind, val) in &self_rows {
println!(
"| {:<kind_w$} | {:<ns_w$} |",
kind,
val,
kind_w = self_kind_w,
ns_w = self_ns_w
);
}
print_divider(&self_widths);
if let Some(container_name) = container.as_deref().filter(|c| *c != "UNSPEC") {
println!();
println!(
"{} {}",
"claim".bold().bright_magenta(),
format!("profile={}", container_name).bright_white()
);
let registry = NamespacesRegistry::load_locked()?;
let mut claim_rows: Vec<(String, String, String, bool, bool)> = Vec::new();
if let Some(declared) = registry.profiles.get(container_name) {
for (label, declared_ns, self_actual) in [
("mnt", &declared.mnt, &self_ns.mnt),
("net", &declared.net, &self_ns.net),
("pid", &declared.pid, &self_ns.pid),
] {
claim_rows.push((
label.to_string(),
declared_ns.unique.to_string(),
self_actual.unique.to_string(),
declared_ns.unique == self_actual.unique,
false,
));
}
} else {
claim_rows.push((
"-".to_string(),
"-".to_string(),
"-".to_string(),
false,
true,
));
}
let claim_kind_w = claim_rows
.iter()
.map(|r| r.0.len())
.max()
.unwrap_or(4)
.max("kind".len());
let claim_declared_w = claim_rows
.iter()
.map(|r| r.1.len())
.max()
.unwrap_or(8)
.max("declared".len());
let claim_self_w = claim_rows
.iter()
.map(|r| r.2.len())
.max()
.unwrap_or(4)
.max("self".len());
let claim_widths = [claim_kind_w, claim_declared_w, claim_self_w, status_width];
print_divider(&claim_widths);
println!(
"| {:<kind_w$} | {:<decl_w$} | {:<self_w$} | {:<status_w$} |",
"kind".bold(),
"declared".bold(),
"self".bold(),
"status".bold(),
kind_w = claim_kind_w,
decl_w = claim_declared_w,
self_w = claim_self_w,
status_w = status_width
);
print_divider(&claim_widths);
for (kind, declared_val, self_val, ok, missing) in claim_rows {
let status_plain = if missing {
"MISSING"
} else if ok {
"OK"
} else {
"DIFF"
};
let status_padded = format!("{:<width$}", status_plain, width = status_width);
let status_colored = if missing {
format!("{}", status_padded.yellow().bold())
} else if ok {
format!("{}", status_padded.green().bold())
} else {
format!("{}", status_padded.red().bold())
};
println!(
"| {:<kind_w$} | {:<decl_w$} | {:<self_w$} | {} |",
kind,
declared_val,
self_val,
status_colored,
kind_w = claim_kind_w,
decl_w = claim_declared_w,
self_w = claim_self_w
);
}
print_divider(&claim_widths);
}
if let Some(proc) = target_ns {
let target_pid =
target_pid.expect("pid must exist when proc namespaces were built");
println!();
println!(
"{} {}",
"pid".bold().bright_magenta(),
format!("{} vs self", target_pid).bright_white()
);
let mut pid_rows: Vec<(String, String, String, bool)> = Vec::new();
for (label, theirs, ours) in [
("mnt", &proc.mnt, &self_ns.mnt),
("net", &proc.net, &self_ns.net),
("pid", &proc.pid, &self_ns.pid),
] {
pid_rows.push((
label.to_string(),
theirs.unique.to_string(),
ours.unique.to_string(),
theirs.unique == ours.unique,
));
}
let pid_kind_w = pid_rows
.iter()
.map(|r| r.0.len())
.max()
.unwrap_or(4)
.max("kind".len());
let pid_target_w = pid_rows
.iter()
.map(|r| r.1.len())
.max()
.unwrap_or(6)
.max("target".len());
let pid_self_w = pid_rows
.iter()
.map(|r| r.2.len())
.max()
.unwrap_or(4)
.max("self".len());
let pid_widths = [pid_kind_w, pid_target_w, pid_self_w, status_width];
print_divider(&pid_widths);
println!(
"| {:<kind_w$} | {:<target_w$} | {:<self_w$} | {:<status_w$} |",
"kind".bold(),
"target".bold(),
"self".bold(),
"status".bold(),
kind_w = pid_kind_w,
target_w = pid_target_w,
self_w = pid_self_w,
status_w = status_width
);
print_divider(&pid_widths);
for (kind, target_val, self_val, ok) in pid_rows {
let status_plain = if ok { "OK" } else { "DIFF" };
let status_padded = format!("{:<width$}", status_plain, width = status_width);
let status_colored = if ok {
format!("{}", status_padded.green().bold())
} else {
format!("{}", status_padded.red().bold())
};
println!(
"| {:<kind_w$} | {:<target_w$} | {:<self_w$} | {} |",
kind,
target_val,
self_val,
status_colored,
kind_w = pid_kind_w,
target_w = pid_target_w,
self_w = pid_self_w
);
}
print_divider(&pid_widths);
}
let mount_ns = (
std::fs::metadata("/proc/self/ns/mnt"),
std::fs::metadata("/proc/1/ns/mnt"),
);
println!();
match mount_ns {
(Ok(self_mnt), Ok(init_mnt)) => {
let isolated =
self_mnt.dev() != init_mnt.dev() || self_mnt.ino() != init_mnt.ino();
println!(
"{} {} {}",
"mount_ns".bold().bright_blue(),
if isolated {
"isolated".green().bold().to_string()
} else {
"host-shared".red().bold().to_string()
},
format!("(self_ino={} init_ino={})", self_mnt.ino(), init_mnt.ino())
.bright_black(),
);
}
(Err(e), _) | (_, Err(e)) => {
println!(
"{} {} {}",
"mount_ns".bold().bright_blue(),
"unknown".yellow().bold(),
format!("({})", e).bright_black()
);
}
}
println!();
}
MainCommand::Sudo { sargs } => {
let mut shell_prefs = ShellPrefs::default();
shell_prefs.take_args(sargs);
shell_prefs.uid = shell_prefs.uid.or(Some(0));
shell_prefs.adjust();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(async {
let rx = shell_prefs.spawn()?;
rx.wait_for_child().await?;
aok!()
})?;
}
/// We are just putting state in proc now, basically. Seems cleaner
MainCommand::Enter { sargs, target } => {
let mut shell_prefs = ShellPrefs::default();
shell_prefs.take_args(sargs);
shell_prefs.adjust();
// Resolve the bind mount path: profile name resolves to /nsp3/{name}/net,
// otherwise treat as an explicit path if it starts with /, ./, or ~/
let (resolved_path, nsdata) = {
let t = ⌖
if t.starts_with('/') || t.starts_with("./") || t.starts_with("~/") || t == "~" {
let vars = PathExpansionState::without_instance();
let p = vars.expand(Path::new(t));
(Some(p.clone()), state_paths::metadata_for_bind(&p))
} else {
let p = state_paths::profile_netns_bind(t);
let m = state_paths::profile_ns_meta(t);
info!("Resolved profile name {:?} to {:?}", t, &p);
(Some(p), m)
}
};
if let Some(path) = resolved_path {
if let Some(ns_alive) = read_ns_alive_opt(&nsdata) {
let profile = ns_alive.profile_name.as_deref().unwrap_or(target.as_str());
let sandbox_status = read_sandbox_status(profile)
.ok_or_else(|| anyhow!("no valid sandbox status for '{}' — run 'sp sandbox {}' first", profile, profile))?;
enter_ns_sandboxed(&ns_alive, &sandbox_status, &path)?;
apply_ns_env(&mut shell_prefs, &ns_alive);
apply_dbus_env(&mut shell_prefs, &ns_alive);
} else {
error!("NS data not found at {:?}", nsdata)
}
} else {
error!("specify --name <profile> or a path");
}
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(async {
let rx = shell_prefs.spawn()?;
rx.wait_for_child().await?;
aok!()
})?;
}
MainCommand::Install { dir: dstdir } => {
if !dstdir.exists() {
bail!(
"target directory {:?} does not exist. you have to create it manually",
&dstdir
)
}
let dstdir_abs = dstdir.canonicalize()?;
let selfprog = std::env::current_exe()?;
let mut sproxyf = selfprog.clone();
let overwrite = |src: &Path, path: &Path| {
warn!("installing {:?} to {:?}", src, path);
if path.exists() {
std::fs::remove_file(path)?;
}
std::fs::copy(src, path)?;
aok!()
};
let selfprogdst = dstdir.join(selfprog.file_name().unwrap());
overwrite(&selfprog, &selfprogdst)?;
sproxyf.set_file_name("sproxy");
let fd = dstdir.join(sproxyf.file_name().unwrap());
overwrite(&sproxyf, &fd)?;
let f = std::fs::File::open(&fd)?;
let perms = Permissions::from_mode(0o6755);
f.set_permissions(perms)?;
let meta = f.metadata()?;
warn!(
"{fd:?}, uid={:?}, gid={}, suid={}",
meta.uid(),
meta.gid(),
meta.permissions().mode() & 0o4000 != 0
);
let short_path = dstdir_abs.join("sp");
let fd_abs = fd.canonicalize()?;
warn!("Installing symlink {:?} -> {:?}", &short_path, &fd_abs);
symlink(&fd_abs, &short_path);
let short_path_unpriv = dstdir_abs.join("nsp");
let selfprogdst_abs = selfprogdst.canonicalize()?;
warn!(
"Installing symlink {:?} -> {:?}",
&short_path_unpriv, &selfprogdst_abs
);
symlink(&selfprogdst_abs, &short_path_unpriv);
sproxyf.set_file_name("nswrap");
let fd = dstdir.join(sproxyf.file_name().unwrap());
overwrite(&sproxyf, &fd)?;
}
MainCommand::Completions { fish } => {
if fish {
if let Some(home) = std::env::var_os("HOME") {
let dir = PathBuf::from(home)
.join(".config")
.join("fish")
.join("completions");
std::fs::create_dir_all(&dir)?;
for bin_name in ["sp", "nsp", "nsproxy"] {
let mut cmd = Cli::command();
let mut buf = Vec::new();
generate(Fish, &mut cmd, bin_name, &mut buf);
let path = dir.join(format!("{}.fish", bin_name));
info!(
"Installing fish completion for '{}' at {:?}",
bin_name, path
);
std::fs::write(&path, &buf)?;
}
} else {
warn!("HOME is not set; skipping fish completion install");
}
} else {
warn!("No completion target specified; use --fish");
}
}
MainCommand::Clean { veth } => {
if veth {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(async {
let cmd = tokio_netlink_conn()?;
info!("trying to remove v_out if it exists");
let default_v = cmd.fetch_link_by_name("v_out".to_owned()).await?;
cmd.link().del(default_v.header.index).execute().await?;
warn!("v_out removed");
aok!(())
})?;
}
}
MainCommand::Gen { save_to } => {
let conf = HotConfig::default();
let json = serde_json::to_string_pretty(&conf)?;
std::fs::write(&save_to, json)?;
}
MainCommand::Netlink => {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
rt.block_on(async {
let nl = tokio_netlink_conn()?;
let addrs = nl.fetch_all_ip_addrs().await?;
for a in addrs {
println!("{}", a);
}
Ok::<(), anyhow::Error>(())
})?;
}
MainCommand::Curl { url, proxy } => {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
rt.block_on(async {
let client = if let Some(proxy_addr) = proxy {
let proxy_url = format!("socks5h://{}", proxy_addr);
info!("using proxy: {}", proxy_url);
reqwest::Client::builder()
.proxy(reqwest::Proxy::all(proxy_url)?)
.build()?
} else {
reqwest::Client::builder()
.redirect(Policy::default())
.build()?
};
info!("requesting: {}", url);
match client.get(url).send().await {
Ok(response) => {
println!("Status: {}", response.status());
match response.text().await {
Ok(body) => println!("{}", body),
Err(e) => warn!("failed to read response body: {}", e),
}
}
Err(e) => warn!("request failed: {:?}", e),
}
Ok::<(), anyhow::Error>(())
})?;
}
MainCommand::Forward { src, dst } => {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
if dst == src {
bail!("src==dst dead loop");
}
rt.block_on(async {
let list = format!("0.0.0.0:{}", src);
let listener = tokio::net::TcpListener::bind(&list).await?;
info!("tcp forward listening on {}", &list);
loop {
let (mut client, _) = listener.accept().await?;
let dst_addr = format!("127.0.0.1:{}", dst);
tokio::spawn(async move {
match tokio::net::TcpStream::connect(&dst_addr).await {
Ok(mut server) => {
info!("forwarded connection to {}", dst_addr);
if let Err(e) =
tokio::io::copy_bidirectional(&mut client, &mut server).await
{
warn!("forward error: {}", e);
}
}
Err(e) => {
warn!("failed to connect to {}: {}", dst_addr, e);
}
}
});
}
aok!()
})?;
}
MainCommand::Template {
path,
name,
reset,
update,
} => {
if reset && update {
bail!("Cannot use --reset and --update together");
}
info!("Profile Creation");
info!("Creating profile instance with isolated state directory");
info!("Each profile can only be instantiated once (e.g., for VS Code isolation)");
info!("");
// Derive name from config file stem if not provided
let clean_name = if let Some(ref name) = name {
// Sanitize provided name: extract filename, remove .json extension
let name_path = PathBuf::from(name);
name_path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or(name)
.to_string()
} else {
// Derive from config path
path.file_stem()