rargo 0.7.1

The rargo client: syncs a worktree and its environment to a rargo build server and brings back the results
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
mod daemon;
mod git;
mod known;
mod mux;
mod outfs;
mod partial;
mod place;
mod project;
mod report;
mod scan;
mod status;
mod tmp;
mod watch;

use rargo_proto::secure;
use rargo_proto::{ExecRequest, LocalReply, LocalRequest};
use std::ffi::{CString, OsString};
use std::io::{IsTerminal, Read, Write};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};

const ROUTED: &[&str] =
    &["build", "b", "check", "c", "clippy", "test", "t", "run", "r", "doc", "d", "bench", "rustc", "rustdoc", "nextest"];

pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
    let tmp = path.with_file_name(format!("{}{}-{}-{name}", tmp::BESIDE, std::process::id(), tmp::seq()));
    let _watched = tmp::watch(&tmp);
    std::fs::write(&tmp, bytes)?;
    std::fs::rename(&tmp, path).inspect_err(|_| {
        let _ = std::fs::remove_file(&tmp);
    })
}

fn home_dir() -> PathBuf {
    PathBuf::from(std::env::var_os("HOME").unwrap_or_else(|| "/".into()))
}

pub struct Config {
    pub host: String,
    pub server: String,
    pub user: String,
    pub secret: Option<String>,
    pub psk: [u8; 32],
}

pub fn load_config() -> Result<Config, String> {
    let env = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
    let local_name = || env("USER").or_else(|| env("LOGNAME")).unwrap_or_else(|| "user".into());
    let from_token = |token: &str| -> Result<(String, Option<String>), String> {
        let (id, secret) = project::split_token(token).ok_or("RARGO_TOKEN is not a token (an id, a dot and a secret)")?;
        Ok((id.to_string(), Some(secret.to_string())))
    };
    if env("RARGO_DAEMON_CONFIG").is_some() {
        let server = env("RARGO_SERVER").ok_or("the daemon was started without a server")?;
        let (user, secret) = match env("RARGO_TOKEN") {
            Some(t) => from_token(&t)?,
            None => (local_name(), None),
        };
        let psk = secret.as_ref().map_or_else(secure::open_psk, |s| secure::psk_from_secret(s.as_bytes()));
        return Ok(Config { host: server.clone(), server, user, secret, psk });
    }
    let (host, _) = server_host()?;
    let server = project::resolve(&host)?;
    let (user, secret) = if let Some(token) = env("RARGO_TOKEN") {
        from_token(&token)?
    } else if let Some(c) = project::credential(&host) {
        (c.id, Some(c.secret))
    } else {
        (local_name(), None)
    };
    let psk = secret.as_ref().map_or_else(secure::open_psk, |s| secure::psk_from_secret(s.as_bytes()));
    Ok(Config { host, server, user, secret, psk })
}

enum HostFrom {
    Env,
    File(PathBuf),
}

fn server_host() -> Result<(String, HostFrom), String> {
    if let Some(h) = std::env::var("RARGO_SERVER").ok().filter(|v| !v.is_empty()) {
        return Ok((h, HostFrom::Env));
    }
    let cwd = std::env::current_dir().map_err(|e| format!("cannot determine the current directory: {e}"))?;
    match project::project_host(&cwd)? {
        Some((h, path)) => Ok((h, HostFrom::File(path))),
        None => Err(format!("no rargo server is named here: run `rargo @rargo.rs` (or `rargo @HOST` for a server of your own), which writes {}", project::CONFIG)),
    }
}

fn is_loopback(server: &str) -> bool {
    let name = server.rsplit_once(':').map_or(server, |(h, _)| h);
    name == "localhost" || name.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
}

pub fn cache_dir() -> PathBuf {
    if let Some(d) = std::env::var_os("RARGO_CACHE_DIR") {
        return PathBuf::from(d);
    }
    std::env::var_os("XDG_CACHE_HOME").map(PathBuf::from).unwrap_or_else(|| home_dir().join(".cache")).join("rargo")
}

pub fn hostname() -> String {
    let mut buf = [0u8; 256];
    if unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) } != 0 {
        return "unknown".into();
    }
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    String::from_utf8_lossy(&buf[..end]).into_owned()
}

pub fn find_root(cwd: &Path) -> Option<PathBuf> {
    let ancestors: Vec<&Path> = cwd.ancestors().collect();
    if let Some(d) = ancestors.iter().find(|d| d.join(".git").exists()) {
        return Some(d.to_path_buf());
    }
    ancestors.iter().rev().find(|d| d.join("Cargo.toml").is_file()).map(|d| d.to_path_buf())
}

#[derive(Default)]
pub struct Policy {
    pub pass: Vec<String>,
    pub exclude: Vec<String>,
    pub git: git::Mode,
    pub gitignored: bool,
    pub include: Vec<String>,
}

pub fn load_policy(root: &Path, start: &Path) -> Policy {
    let read = |path: &Path| std::fs::read_to_string(root.join(path)).ok();
    let policy = rargo_proto::workspace::manifest_for(start, read)
        .and_then(|(path, _)| read(&path)?.parse::<toml::Table>().ok())
        .and_then(|t| ["workspace", "package"].iter().find_map(|kind| t.get(*kind)?.get("metadata")?.get("rargo")?.as_table().cloned()))
        .unwrap_or_default();
    let list = |name: &str, key: &str| -> Vec<String> {
        policy
            .get(name)
            .and_then(|s| s.get(key))
            .and_then(|v| v.as_array())
            .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
            .unwrap_or_default()
    };
    let flag = |key: &str| policy.get("sync").and_then(|s| s.get(key)).and_then(|v| v.as_bool()).unwrap_or(true);
    Policy {
        pass: list("env", "pass"),
        exclude: list("sync", "exclude"),
        git: match policy.get("sync").and_then(|s| s.get("git")) {
            Some(toml::Value::Boolean(false)) => git::Mode::Off,
            Some(toml::Value::String(s)) if s == "head" => git::Mode::Head,
            Some(toml::Value::String(s)) if s == "history" => git::Mode::History,
            _ => git::Mode::Detect,
        },
        gitignored: flag("gitignored"),
        include: list("sync", "include"),
    }
}

pub fn pattern_matches(pattern: &str, name: &str) -> bool {
    match pattern.strip_suffix('*') {
        Some(prefix) => name.starts_with(prefix),
        None => pattern == name,
    }
}

fn parse_hex20(s: &str) -> Option<[u8; 20]> {
    let s = s.trim();
    if s.len() != 40 {
        return None;
    }
    let mut out = [0u8; 20];
    for (i, b) in out.iter_mut().enumerate() {
        *b = u8::from_str_radix(s.get(i * 2..i * 2 + 2)?, 16).ok()?;
    }
    Some(out)
}

pub fn recent_commits(root: &Path, head: &git::Head, wt_cache: &Path) -> Vec<[u8; 20]> {
    let head = &head.commit;
    let memo = wt_cache.join("commits");
    let parse = |text: &str| -> Vec<[u8; 20]> { text.lines().filter_map(parse_hex20).collect() };
    if let Ok(text) = std::fs::read_to_string(&memo) {
        if text.lines().next() == Some(head.as_str()) {
            return parse(&text);
        }
    }
    let listed = std::process::Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["rev-list", "--first-parent", "-n", "64", head])
        .stderr(std::process::Stdio::null())
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
        .unwrap_or_else(|| format!("{head}\n"));
    let _ = write_atomic(&memo, listed.as_bytes());
    parse(&listed)
}

pub fn die(msg: &str) -> ! {
    eprintln!("error: {msg}");
    std::process::exit(101)
}

pub fn load_asked(cache: &Path) -> Vec<String> {
    std::fs::read_to_string(cache.join("env-names")).map(|t| t.lines().map(String::from).collect()).unwrap_or_default()
}

fn daemon_socket(cfg: &Config, cache: &Path) -> PathBuf {
    let mut h = blake3::Hasher::new();
    for part in [cfg.server.as_bytes(), cfg.user.as_bytes(), &cfg.psk[..], cache.as_os_str().as_bytes()] {
        h.update(&(part.len() as u64).to_le_bytes());
        h.update(part);
    }
    for name in ["RARGO_TRANSPORT", "RARGO_DAEMON_IDLE_SECS"] {
        h.update(std::env::var(name).unwrap_or_default().as_bytes());
        h.update(&[0]);
    }
    if let Ok(exe) = std::env::current_exe() {
        h.update(exe.as_os_str().as_bytes());
        if let Ok(md) = std::fs::metadata(&exe) {
            use std::os::unix::fs::MetadataExt;
            h.update(&md.len().to_le_bytes());
            h.update(&md.mtime().to_le_bytes());
            h.update(&md.mtime_nsec().to_le_bytes());
        }
    }
    let name = format!("{}.sock", &h.finalize().to_hex()[..20]);
    let in_cache = cache.join("run").join(&name);
    if in_cache.as_os_str().len() < 100 {
        return in_cache;
    }
    let uid = unsafe { libc::getuid() };
    let dir = match std::env::var_os("XDG_RUNTIME_DIR").filter(|d| !d.is_empty()) {
        Some(d) => PathBuf::from(d).join("rargo"),
        None => PathBuf::from(format!("/tmp/rargo-{uid}")),
    };
    dir.join(name)
}

fn stop_daemons(cfg: &Config, cache: &Path, req: &LocalRequest) {
    use std::os::unix::net::UnixStream;
    let mut sockets = Vec::new();
    if let Ok(rd) = std::fs::read_dir(cache.join("run")) {
        for ent in rd.flatten() {
            let path = ent.path();
            if path.extension().is_some_and(|ext| ext == "sock") {
                sockets.push(path);
            }
        }
    }
    let primary = daemon_socket(cfg, cache);
    if !sockets.iter().any(|path| path == &primary) {
        sockets.push(primary);
    }
    let bytes = rargo_proto::encode(req);
    for socket in sockets {
        let Ok(mut stream) = UnixStream::connect(&socket) else { continue };
        let _ = stream.write_all(&(bytes.len() as u32).to_le_bytes()).and_then(|_| stream.write_all(&bytes));
        let mut rest = Vec::new();
        let _ = stream.read_to_end(&mut rest);
    }
}

fn private_dir(dir: &Path) -> std::io::Result<()> {
    use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
    match std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir) {
        Ok(()) => {}
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
        Err(e) => return Err(e),
    }
    let md = std::fs::symlink_metadata(dir)?;
    if !md.is_dir() || md.uid() != unsafe { libc::getuid() } {
        return Err(std::io::Error::other(format!("{} is not a directory of this user", dir.display())));
    }
    if md.permissions().mode() & 0o077 != 0 {
        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
    }
    Ok(())
}

fn start_daemon(socket: &Path, cache: &Path, cfg: &Config) -> std::io::Result<()> {
    let exe = std::env::current_exe()?;
    std::fs::create_dir_all(cache)?;
    let log = std::fs::OpenOptions::new().create(true).append(true).open(cache.join("daemon.log"))?;
    let mut cmd = std::process::Command::new(exe);
    cmd.env("RARGO_DAEMON_CONFIG", "1").env("RARGO_SERVER", &cfg.server);
    match &cfg.secret {
        Some(s) => cmd.env("RARGO_TOKEN", format!("{}.{s}", cfg.user)),
        None => cmd.env_remove("RARGO_TOKEN"),
    };
    cmd.arg("--rargo-daemon")
        .arg(socket)
        .stdin(std::process::Stdio::null())
        .stdout(log.try_clone()?)
        .stderr(log)
        .current_dir("/");
    unsafe {
        cmd.pre_exec(|| {
            match libc::fork() {
                -1 => return Err(std::io::Error::last_os_error()),
                0 => {}
                _ => libc::_exit(0),
            }
            libc::setsid();
            Ok(())
        });
    }
    let mut child = cmd.spawn()?;
    let _ = child.wait();
    Ok(())
}

fn connect_daemon(cfg: &Config, cache: &Path) -> std::io::Result<std::os::unix::net::UnixStream> {
    use std::os::unix::net::UnixStream;
    let socket = daemon_socket(cfg, cache);
    if let Ok(s) = UnixStream::connect(&socket) {
        return Ok(s);
    }
    if let Some(dir) = socket.parent() {
        private_dir(dir)?;
    }
    start_daemon(&socket, cache, cfg)?;
    let started = std::time::Instant::now();
    loop {
        match UnixStream::connect(&socket) {
            Ok(s) => return Ok(s),
            Err(e) if started.elapsed() > std::time::Duration::from_secs(10) => {
                return Err(std::io::Error::new(e.kind(), format!("the rargo daemon did not start (see {}): {e}", cache.join("daemon.log").display())));
            }
            Err(_) => std::thread::sleep(std::time::Duration::from_millis(5)),
        }
    }
}

const TOKEN_COMMANDS: &[&str] = &["invite", "create", "tokens", "revoke", "allow", "disallow"];

pub fn mount_ns() -> String {
    std::fs::read_link("/proc/self/ns/mnt").map(|p| p.to_string_lossy().into_owned()).unwrap_or_default()
}

fn kind_needs_server(daemon_cmd: Option<&str>) -> bool {
    daemon_cmd.is_none()
}

fn at_host(host: &str) -> ! {
    let cwd = std::env::current_dir().unwrap_or_else(|e| die(&format!("cannot determine the current directory: {e}")));
    match project::set_host(&cwd, host) {
        Ok(path) => {
            eprintln!("{} now names `{host}` as this checkout's rargo server.", path.display());
            if host.contains(':') || project::resolve(host).is_ok() {
                if project::credential(host).is_none() && std::env::var_os("RARGO_TOKEN").is_none() {
                    eprintln!("Next: `rargo auth`, then `rargo build`.");
                }
            } else {
                eprintln!("warning: no rargo server answers for `{host}` right now (https://{host}/.well-known/rargo.json)");
            }
            std::process::exit(0)
        }
        Err(e) => die(&e),
    }
}

fn auth_command(args: &[OsString]) -> ! {
    let args: Vec<String> = args.iter().map(|a| a.to_string_lossy().into_owned()).collect();
    let mut what = "auth";
    let mut host: Option<String> = None;
    let mut token: Option<String> = None;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "status" if i == 0 => what = "status",
            "remove" if i == 0 => what = "remove",
            "--token" => {
                i += 1;
                token = Some(args.get(i).cloned().unwrap_or_else(|| die("`--token` needs the token")));
            }
            "-h" | "--help" => {
                println!(
                    "rargo auth [HOST]            get this machine a token for the project's server (or HOST), confirmed in a browser\n\
                     rargo auth --token T [HOST]  store a token an administrator made (rargod token create)\n\
                     rargo auth status            which server this checkout builds on, what named it, and as whom\n\
                     rargo auth remove [HOST]     revoke the token for the project's server (or HOST) there and forget it here\n\
                     \n\
                     On the project's server, for an administrator (anyone may list and revoke their own tokens):\n\
                     rargo auth invite [--user NAME] [--admin] [--days N] [--uses N] [--token-days N]\n\
                     rargo auth create --user NAME [--admin] [--days N]\n\
                     rargo auth tokens\n\
                     rargo auth revoke ID-OR-USER\n\
                     rargo auth allow GITHUB-LOGIN [--admin]\n\
                     rargo auth disallow GITHUB-LOGIN"
                );
                std::process::exit(0)
            }
            a if a.starts_with('-') => die(&format!("unknown option `{a}` (see `rargo auth --help`)")),
            a if host.is_none() => host = Some(a.trim_start_matches('@').to_string()),
            a => die(&format!("unexpected `{a}` (see `rargo auth --help`)")),
        }
        i += 1;
    }
    let (host, from) = match host {
        Some(h) => (h, None),
        None => match server_host() {
            Ok((h, from)) => (h, Some(from)),
            Err(e) => die(&format!("{e}; or say `rargo auth HOST`")),
        },
    };
    if !project::valid_host(&host) {
        die(&format!("`{host}` is not a host"));
    }
    match what {
        "status" => {
            match &from {
                Some(HostFrom::Env) => println!("server named by RARGO_SERVER"),
                Some(HostFrom::File(path)) => println!("server named by {}", path.display()),
                None => {}
            }
            let server = project::resolve(&host).unwrap_or_else(|e| format!("unknown ({e})"));
            match project::credential(&host) {
                Some(c) if c.name.is_empty() => println!("{host} (server {server}): authenticated (token {})", c.id),
                Some(c) => println!("{host} (server {server}): authenticated as {} (token {})", c.name, c.id),
                None => println!("{host} (server {server}): not authenticated; run `rargo auth`"),
            }
            std::process::exit(0)
        }
        "remove" => {
            if project::credential(&host).is_none() {
                die(&format!("there is no token for {host} on this machine"));
            }
            let revoked = project::revoke_on_server(&host);
            if let Err(e) = project::forget(&host) {
                die(&e);
            }
            match revoked {
                Ok(true) => println!("revoked the token for {host} on the server and forgot it here"),
                Ok(false) => println!("forgot the token for {host} (the server did not know it as a token that still works)"),
                Err(e) => {
                    println!("forgot the token for {host} on this machine");
                    eprintln!("warning: the server could not be told to revoke it ({e}); it keeps working for whoever has a copy until an administrator runs `rargod token revoke`");
                }
            }
            std::process::exit(0)
        }
        _ => {}
    }
    if let Some(token) = token {
        let stored = project::holder(&host, &token).and_then(|name| match name {
            Some(name) => project::store_token(&host, &token, &name).map(|()| name),
            None => Err(format!("{host}: {}", rargo_proto::REFUSED)),
        });
        match stored {
            Ok(name) => {
                println!("stored the token for {host}, held by {name}");
                std::process::exit(0)
            }
            Err(e) => die(&format!("rargo auth: {e}")),
        }
    }
    match project::auth(&host) {
        Ok(name) => {
            println!("Authenticated to {host} as {name}. `rargo build` now builds there.");
            std::process::exit(0)
        }
        Err(e) => die(&format!("rargo auth: {e}")),
    }
}

fn release_output() {
    let (Ok(cfg), Ok(cwd)) = (load_config(), std::env::current_dir().and_then(|d| d.canonicalize())) else { return };
    let socket = daemon_socket(&cfg, &cache_dir());
    let Ok(mut stream) = std::os::unix::net::UnixStream::connect(&socket) else { return };
    let req = LocalRequest {
        args: Vec::new(),
        kind: "release".into(),
        cwd: cwd.to_string_lossy().into_owned(),
        vars: Vec::new(),
        stdout_tty: false,
        stderr_tty: false,
        mount_ns: mount_ns(),
    };
    let bytes = rargo_proto::encode(&req);
    let _ = stream.write_all(&(bytes.len() as u32).to_le_bytes()).and_then(|_| stream.write_all(&bytes));
    let mut rest = Vec::new();
    let _ = stream.read_to_end(&mut rest);
}

fn relay(reply: LocalReply, cfg: &Config, raw: &[OsString]) {
    match reply {
        LocalReply::Stdout(b) => {
            let mut o = std::io::stdout().lock();
            if o.write_all(&b).and_then(|_| o.flush()).is_err() {
                std::process::exit(141);
            }
        }
        LocalReply::Stderr(b) => {
            let _ = std::io::stderr().lock().write_all(&b);
        }
        LocalReply::Exit(code) => std::process::exit(code),
        LocalReply::Exec(e) => exec(e),
        LocalReply::Unreachable(why) => {
            if std::env::var_os("RARGO_FALLBACK").is_some_and(|v| v == "cargo") {
                passthrough(raw);
            }
            eprintln!("error: cannot reach the rargo server at {}: {why}", cfg.server);
            eprintln!("       (the server is named by `rargo @host`, in {}, or by RARGO_SERVER; RARGO_FALLBACK=cargo uses plain cargo instead)", project::CONFIG);
            std::process::exit(101);
        }
    }
}

fn through_daemon(cfg: Config, cache: PathBuf, req: LocalRequest, raw: &[OsString]) -> ! {
    let no_daemon = std::env::var_os("RARGO_NO_DAEMON").is_some_and(|v| v == "1");
    let stream = if no_daemon { Err(std::io::Error::other("RARGO_NO_DAEMON")) } else { connect_daemon(&cfg, &cache) };
    let mut stream = match stream {
        Ok(s) => s,
        Err(e) => {
            if !no_daemon && std::env::var_os("RARGO_QUIET_DAEMON").is_none() {
                eprintln!("warning: rargo runs without its daemon ({e}); every command connects to the server anew");
            }
            let cfg2 = Config { host: cfg.host.clone(), server: cfg.server.clone(), user: cfg.user.clone(), secret: cfg.secret.clone(), psk: cfg.psk };
            daemon::inline(cfg2, cache, req, |reply| relay(reply, &cfg, raw));
            die("the command ended without a result");
        }
    };
    let bytes = rargo_proto::encode(&req);
    if stream.write_all(&(bytes.len() as u32).to_le_bytes()).and_then(|_| stream.write_all(&bytes)).is_err() {
        die("the rargo daemon closed the connection");
    }
    loop {
        let mut len = [0u8; 4];
        if stream.read_exact(&mut len).is_err() {
            die("the rargo daemon went away while the command was running");
        }
        let mut buf = vec![0u8; u32::from_le_bytes(len) as usize];
        if stream.read_exact(&mut buf).is_err() {
            die("the rargo daemon went away while the command was running");
        }
        match rargo_proto::decode::<LocalReply>(&buf) {
            Ok(reply) => relay(reply, &cfg, raw),
            Err(_) => die("the rargo daemon said something this program does not understand"),
        }
    }
}

fn main() {
    let raw: Vec<OsString> = std::env::args_os().skip(1).collect();
    if std::env::var_os("RARGO_BYPASS").is_some() {
        passthrough(&raw);
    }
    let cargo_link = std::env::args_os().next().is_some_and(|arg| Path::new(&arg).file_name().is_some_and(|name| name == "cargo"));
    if !cargo_link && raw.first().is_some_and(|a| a == "status") {
        match raw.get(1).and_then(|arg| arg.to_str()) {
            Some("--help" | "-h") if raw.len() == 2 => println!("Usage: rargo status\n\nShow your server, account, daemon, mount and versions."),
            None if raw.len() == 1 => status::run(),
            _ => die("usage: rargo status"),
        }
        return;
    }
    if !cargo_link && raw.len() == 1 && raw.first().is_some_and(|a| a == "--help" || a == "-h") {
        println!("rargo status    Show your server, account, daemon, mount and versions.\n");
    }
    if raw.first().is_some_and(|a| a == "--rargo-version") {
        println!("rargo {} (protocol {})", env!("CARGO_PKG_VERSION"), rargo_proto::PROTO_VERSION);
        return;
    }
    if let Some(host) = raw.first().and_then(|a| a.to_str()).and_then(|a| a.strip_prefix('@')) {
        at_host(host);
    }
    let token_command = raw.first().is_some_and(|a| a == "auth")
        && raw.get(1).and_then(|a| a.to_str()).is_some_and(|a| TOKEN_COMMANDS.contains(&a));
    if raw.first().is_some_and(|a| a == "auth") && !token_command {
        auth_command(&raw[1..]);
    }
    if raw.first().is_some_and(|a| a == "--rargo-daemon") {
        match raw.get(1) {
            Some(socket) => daemon::serve(Path::new(socket)),
            None => die("usage: rargo --rargo-daemon SOCKET"),
        }
    }
    tmp::install_handlers();
    let mut args: Vec<String> = match raw.iter().map(|a| a.clone().into_string()).collect() {
        Ok(a) => a,
        Err(_) => passthrough(&raw),
    };
    let mut vars: Vec<(String, String)> = std::env::vars_os()
        .filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)))
        .collect();
    if let Some(tc) = args.first().and_then(|a| a.strip_prefix('+')).map(|s| s.to_string()) {
        args.remove(0);
        vars.retain(|(k, _)| k != "RUSTUP_TOOLCHAIN");
        vars.push(("RUSTUP_TOOLCHAIN".into(), tc));
    }
    if subcommand(&args) == Some("nextest")
        && !vars.iter().any(|(k, _)| k == "RARGO_NEXTEST_VERSION")
        && let Some(v) = own_nextest_version()
    {
        vars.push(("RARGO_NEXTEST_VERSION".into(), v));
    }
    let admin = match args.first().map(|s| s.as_str()) {
        Some("auth") if token_command => Some("__token"),
        Some("--rargo-status") => Some("__status"),
        Some("--rargo-settle") => Some("__settle"),
        Some("--rargo-gc") => Some("__gc"),
        Some("--rargo-incr-stats") => Some("__incr"),
        Some("--rargo-compact") => Some("__compact"),
        Some("--rargo-export") => Some("__export"),
        Some("--rargo-import") => Some("__import"),
        _ => None,
    };
    let drift = args.first().map(|s| s.as_str()) == Some("--rargo-drift-check");
    let daemon_cmd = match args.first().map(|s| s.as_str()) {
        Some("--rargo-daemon-status") => Some("status"),
        Some("--rargo-daemon-stop") => Some("stop"),
        Some("--rargo-daemon-sync") => Some("sync"),
        _ => None,
    };
    if daemon_cmd.is_some() {
        args.clear();
    } else if let Some(cmd) = admin {
        let mut a = vec![cmd.to_string()];
        if matches!(cmd, "__export" | "__import") {
            match args.get(1) {
                Some(dir) => a.push(dir.clone()),
                None => {
                    eprintln!("usage: rargo {} DIRECTORY-ON-THE-SERVER", args[0]);
                    std::process::exit(2);
                }
            }
        }
        if cmd == "__token" {
            let what = if args[1] == "tokens" { "list".to_string() } else { args[1].clone() };
            a.push(what);
            a.extend(args[2..].iter().cloned());
        }
        args = a;
    } else if drift {
        args = vec!["__drift".into()];
    } else {
        match subcommand(&args) {
            Some(cmd) if ROUTED.contains(&cmd) => {}
            Some("clean") => {
                release_output();
                passthrough(&raw)
            }
            _ => passthrough(&raw),
        }
        if subcommand(&args) != Some("nextest")
            && args.iter().take_while(|a| *a != "--").any(|a| a == "--help" || a == "-h" || a == "--version" || a == "-V")
        {
            passthrough(&raw);
        }
    }
    let cfg = load_config().unwrap_or_else(|e| die(&e));
    if cfg.secret.is_none() && !is_loopback(&cfg.server) && kind_needs_server(daemon_cmd) {
        die(&format!("this machine is not authenticated to {}: run `rargo auth`", cfg.host));
    }
    let cwd = match std::env::current_dir().and_then(|d| d.canonicalize()) {
        Ok(d) => d,
        Err(e) => die(&format!("cannot determine the current directory: {e}")),
    };
    let kind = if daemon_cmd.is_some() {
        daemon_cmd.unwrap()
    } else if admin.is_some() {
        "admin"
    } else if drift {
        "drift"
    } else {
        "build"
    };
    let req = LocalRequest {
        args,
        kind: kind.to_string(),
        cwd: cwd.to_string_lossy().into_owned(),
        vars,
        stdout_tty: std::io::stdout().is_terminal(),
        stderr_tty: std::io::stderr().is_terminal(),
        mount_ns: mount_ns(),
    };
    let cache = cache_dir();
    if kind == "stop" {
        stop_daemons(&cfg, &cache, &req);
        std::process::exit(0);
    }
    through_daemon(cfg, cache, req, &raw)
}

fn subcommand(args: &[String]) -> Option<&str> {
    let mut it = args.iter();
    while let Some(a) = it.next() {
        if a == "--" {
            return None;
        }
        if matches!(a.as_str(), "--color" | "--config" | "-C" | "-Z" | "--explain") {
            it.next();
            continue;
        }
        if a.starts_with('-') {
            continue;
        }
        return Some(a);
    }
    None
}

fn own_nextest_version() -> Option<String> {
    let out = std::process::Command::new("cargo-nextest")
        .args(["nextest", "--version"])
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;
    let text = String::from_utf8(out.stdout).ok()?;
    let mut words = text.lines().next()?.split_whitespace();
    (words.next()? == "cargo-nextest").then(|| words.next().map(String::from)).flatten()
}

fn real_cargo() -> Option<PathBuf> {
    if let Some(p) = std::env::var_os("RARGO_REAL_CARGO") {
        return Some(PathBuf::from(p));
    }
    let me = std::env::current_exe().ok().and_then(|p| p.canonicalize().ok());
    for dir in std::env::split_paths(&std::env::var_os("PATH")?) {
        let cand = dir.join("cargo");
        if !cand.is_file() {
            continue;
        }
        if cand.canonicalize().ok() == me {
            continue;
        }
        return Some(cand);
    }
    None
}

fn passthrough(args: &[OsString]) -> ! {
    match real_cargo() {
        Some(cargo) => {
            let err = std::process::Command::new(&cargo).args(args).exec();
            eprintln!("error: cannot run {}: {err}", cargo.display());
        }
        None => eprintln!("error: no `cargo` found on PATH to hand this command to"),
    }
    std::process::exit(101)
}

fn cstr(p: &Path) -> CString {
    CString::new(p.as_os_str().as_bytes()).expect("path without NUL")
}

fn mount(src: Option<&Path>, tgt: &Path, fstype: Option<&str>, flags: libc::c_ulong, data: Option<&str>) -> std::io::Result<()> {
    let src_c = src.map(cstr);
    let tgt_c = cstr(tgt);
    let fs_c = fstype.map(|s| CString::new(s).unwrap());
    let data_c = data.map(|s| CString::new(s).unwrap());
    let r = unsafe {
        libc::mount(
            src_c.as_ref().map_or(std::ptr::null(), |c| c.as_ptr()),
            tgt_c.as_ptr(),
            fs_c.as_ref().map_or(std::ptr::null(), |c| c.as_ptr()),
            flags,
            data_c.as_ref().map_or(std::ptr::null(), |c| c.as_ptr() as *const libc::c_void),
        )
    };
    if r != 0 { Err(std::io::Error::last_os_error()) } else { Ok(()) }
}

fn enter_namespace(binds: &[(String, String)]) -> std::io::Result<()> {
    let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
    let os_err = std::io::Error::last_os_error;
    if unsafe { libc::unshare(libc::CLONE_NEWNS) } != 0 {
        if unsafe { libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) } != 0 {
            return Err(os_err());
        }
        std::fs::write("/proc/self/setgroups", "deny")?;
        std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1"))?;
        std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1"))?;
    }
    mount(None, Path::new("/"), None, libc::MS_REC | libc::MS_PRIVATE, None)?;
    let entries: Vec<std::fs::DirEntry> = std::fs::read_dir("/")?.filter_map(|e| e.ok()).collect();
    let covered = ["/tmp", "/mnt", "/media", "/srv", "/opt", "/home", "/var"]
        .into_iter()
        .find(|d| Path::new(d).is_dir() && !binds.iter().any(|(real, _)| Path::new(real).starts_with(d)))
        .ok_or_else(|| std::io::Error::other("no directory to build the namespace on"))?;
    let tmp_fd = std::fs::File::open(covered)?;
    let new_root = Path::new(covered);
    mount(Some(Path::new("tmpfs")), new_root, Some("tmpfs"), 0, Some("mode=755"))?;
    use std::os::fd::AsRawFd;
    for e in entries {
        let name = e.file_name();
        let src = Path::new("/").join(&name);
        let dst = new_root.join(&name);
        let Ok(ft) = e.file_type() else { continue };
        if binds.iter().any(|(_, at)| Path::new(at) == src) {
            continue;
        }
        if ft.is_symlink() {
            if let Ok(t) = std::fs::read_link(&src) {
                let _ = std::os::unix::fs::symlink(t, &dst);
            }
        } else if ft.is_dir() {
            std::fs::create_dir(&dst)?;
            let from = if src == new_root { PathBuf::from(format!("/proc/self/fd/{}", tmp_fd.as_raw_fd())) } else { src };
            mount(Some(&from), &dst, None, libc::MS_BIND | libc::MS_REC, None)?;
        } else if ft.is_file() {
            std::fs::File::create(&dst)?;
            mount(Some(&src), &dst, None, libc::MS_BIND, None)?;
        }
    }
    for (real, at) in binds {
        let dst = new_root.join(at.trim_start_matches('/'));
        std::fs::create_dir_all(&dst)?;
        let real_p = match Path::new(real).strip_prefix(covered) {
            Ok(rest) => PathBuf::from(format!("/proc/self/fd/{}", tmp_fd.as_raw_fd())).join(rest),
            Err(_) => PathBuf::from(real),
        };
        mount(Some(&real_p), &dst, None, libc::MS_BIND | libc::MS_REC, None)?;
    }
    let root_c = cstr(new_root);
    unsafe {
        if libc::chdir(root_c.as_ptr()) != 0
            || libc::syscall(libc::SYS_pivot_root, c".".as_ptr(), c".".as_ptr()) != 0
            || libc::umount2(c".".as_ptr(), libc::MNT_DETACH) != 0
        {
            return Err(os_err());
        }
    }
    Ok(())
}

fn to_real(s: &str, binds: &[(String, String)]) -> String {
    let mut out = String::new();
    for (i, part) in s.split(':').enumerate() {
        if i > 0 {
            out.push(':');
        }
        let mut done = false;
        for (real, at) in binds {
            if part == at {
                out.push_str(real);
                done = true;
                break;
            }
            if let Some(rest) = part.strip_prefix(at.as_str()) {
                if rest.starts_with('/') {
                    out.push_str(real);
                    out.push_str(rest);
                    done = true;
                    break;
                }
            }
        }
        if !done {
            out.push_str(part);
        }
    }
    out
}

fn exec(mut e: ExecRequest) -> ! {
    e.binds.retain(|(real, _)| Path::new(real).exists());
    if e.binds.is_empty() {
    } else if let Err(err) = enter_namespace(&e.binds) {
        if std::env::var_os("RARGO_QUIET_NS").is_none() {
            eprintln!(
                "warning: cannot create a mount namespace ({err}); running without it. \
                 Paths compiled into the program (such as CARGO_MANIFEST_DIR) will point to `{}`.",
                e.binds.first().map(|b| b.1.as_str()).unwrap_or("/w")
            );
        }
        e.program = to_real(&e.program, &e.binds);
        for (_, v) in e.env.iter_mut() {
            if let Some(v) = v {
                *v = to_real(v, &e.binds);
            }
        }
    }
    let mut cmd = std::process::Command::new(&e.program);
    cmd.args(&e.args).current_dir(&e.cwd);
    for (k, v) in &e.env {
        match v {
            Some(v) => cmd.env(k, v),
            None => cmd.env_remove(k),
        };
    }
    let err = cmd.exec();
    eprintln!("error: could not execute process `{}` (never executed)\n\nCaused by:\n  {err}", e.program);
    std::process::exit(101)
}

#[cfg(test)]
mod tests {
    #[test]
    fn writes_of_one_path_at_once_all_succeed() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shared");
        let threads: Vec<_> = (0..16)
            .map(|t| {
                let path = path.clone();
                std::thread::spawn(move || {
                    for i in 0..200 {
                        crate::write_atomic(&path, format!("{t} {i}").as_bytes()).unwrap();
                    }
                })
            })
            .collect();
        for t in threads {
            t.join().unwrap();
        }
        assert!(std::fs::read_to_string(&path).unwrap().ends_with(" 199"));
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
    }

    use super::*;

    #[test]
    fn socket_name_follows_the_configuration() {
        let cfg = |server: &str| Config { host: server.into(), server: server.into(), user: "u".into(), secret: None, psk: [7; 32] };
        let cache = Path::new("/c");
        let a = daemon_socket(&cfg("a:1"), cache);
        assert_eq!(a, daemon_socket(&cfg("a:1"), cache));
        assert_ne!(a, daemon_socket(&cfg("b:1"), cache));
        assert_ne!(a, daemon_socket(&cfg("a:1"), Path::new("/d")));
        assert!(a.starts_with("/c/run"));
        let long = PathBuf::from(format!("/{}", "x".repeat(120)));
        assert!(!daemon_socket(&cfg("a:1"), &long).starts_with(&long));
    }

    #[test]
    fn subcommands_are_found_behind_global_options() {
        let a = |v: &[&str]| -> Vec<String> { v.iter().map(|s| s.to_string()).collect() };
        assert_eq!(subcommand(&a(&["--color", "always", "build"])), Some("build"));
        assert_eq!(subcommand(&a(&["-q", "test", "--", "x"])), Some("test"));
        assert_eq!(subcommand(&a(&["--", "build"])), None);
    }
}