GITv
master
main.rs1266 lines, 57.2 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
//! Private Git hosting over OpenSSH and Git's native pack protocol.

use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};

use base64::Engine;
use clap::{Parser, Subcommand};
use gitv_core::{
    DESCRIPTION_LIMIT, NAME_RULE, RepoDir, chown_tree, config, entries, git, git_command, git_in, keys_path, kind_at,
    open_dir_at, open_owner, open_root, remove_tree_at, repo_dir, repo_in, repos_root, unix_now, valid_name,
};
use nix::errno::Errno;
use nix::fcntl::{Flock, FlockArg, OFlag, RenameFlags, openat, renameat2};
use nix::sys::stat::{Mode, fchmod, fstat, mkdirat};
use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, geteuid, unlinkat};
use std::ffi::OsStr;
use std::os::fd::{AsFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::time::{SystemTime, UNIX_EPOCH};

/// What `help` prints.
fn help() -> String {
    let host = config::host();
    format!(
        "Commands for your key, run as: ssh git@{host} <command>
  list                  list your repositories
  create <name>         create an empty repository
  visibility <name> public|private   set web access
  protect <name> [on|off]            show or set whether pushes may rewrite or delete branches
  description <name> [<text>]        show or set the one-line description (\"\" removes it)
  default-branch <name> [<branch>]   show or set the branch the web shows and clones check out
  delete <name> --yes   move a repository to the trash (the operator can restore it for 30 days)
Pushing to a repository that does not exist yet creates it."
    )
}

#[derive(Parser)]
#[command(about = "Private Git hosting over OpenSSH and Git's native pack protocol")]
struct Cli {
    #[command(subcommand)]
    action: Action,
}

#[derive(Subcommand)]
enum Action {
    /// Create an empty repository (root)
    Create {
        #[arg(value_parser = name)]
        owner: String,
        #[arg(value_parser = name)]
        name: String,
    },
    /// Set repository web visibility to public or private (root)
    Visibility { owner: String, name: String, visibility: String },
    /// Show or set whether pushes may force-update or delete branches (root)
    Protect {
        #[arg(value_parser = name)]
        owner: String,
        #[arg(value_parser = name)]
        name: String,
        /// on: branches only move forwards and are never deleted; off: anything
        value: Option<String>,
    },
    /// Show or set a repository's one-line description; "" removes it (root)
    Description {
        #[arg(value_parser = name)]
        owner: String,
        #[arg(value_parser = name)]
        name: String,
        text: Option<String>,
    },
    /// Show or set the branch a repository's web pages show and clones check out (root)
    DefaultBranch {
        #[arg(value_parser = name)]
        owner: String,
        #[arg(value_parser = name)]
        name: String,
        branch: Option<String>,
    },
    /// Move a repository to its owner's trash (root)
    Delete {
        #[arg(value_parser = name)]
        owner: String,
        #[arg(value_parser = name)]
        name: String,
        /// Confirm deletion
        #[arg(long)]
        yes: bool,
    },
    /// List deleted repositories waiting in the trash (root)
    Trash,
    /// Put a deleted repository back, under its old name or another (root)
    Restore {
        #[arg(value_parser = name)]
        owner: String,
        /// The trash entry, as `gitv trash` lists it: <name>.<deletion time>
        entry: String,
        /// Restore under this name instead
        #[arg(long = "as", value_parser = name)]
        as_name: Option<String>,
    },
    /// Copy a bare repository, such as one gitv-restore brought back, into place (root)
    Import {
        #[arg(value_parser = name)]
        owner: String,
        /// The name to give it; anything already there is never replaced
        #[arg(value_parser = name)]
        name: String,
        /// The restored repository's directory
        source: PathBuf,
    },
    /// Permanently remove trash entries deleted at least this many days ago (root)
    Purge {
        #[arg(long, default_value_t = TRASH_DAYS)]
        older_than_days: u64,
    },
    /// Register an Ed25519 public key for an owner (root)
    AddKey {
        #[arg(value_parser = name)]
        owner: String,
        public_key: PathBuf,
        /// A name for the device that holds the key, shown by `gitv keys`
        #[arg(long, value_parser = label)]
        label: Option<String>,
    },
    /// List registered keys with their owner, fingerprint and label (root)
    Keys {
        /// Only this owner's keys
        #[arg(value_parser = name)]
        owner: Option<String>,
    },
    /// Revoke a key by its fingerprint, as `gitv keys` lists it (root)
    RemoveKey {
        /// SHA256:<base64>, with or without the SHA256: prefix
        fingerprint: String,
    },
    /// Handle one SSH request (forced command from authorized_keys)
    Serve {
        #[arg(value_parser = name)]
        owner: String,
    },
}

/// [`check_name`], for clap's argument parsing.
fn name(value: &str) -> Result<String, String> {
    check_name(value).map(str::to_string)
}

/// A key's label becomes the comment field of its authorized_keys line, so it must stay on one
/// line and hold nothing a terminal would act on.
fn label(value: &str) -> Result<String, String> {
    let value = value.trim();
    if value.is_empty() || value.chars().count() > 64 || value.chars().any(char::is_control) {
        return Err("a label is 1 to 64 characters, with no control characters".into());
    }
    Ok(value.to_string())
}

fn check_name(value: &str) -> Result<&str, String> {
    if valid_name(value) { Ok(value) } else { Err(NAME_RULE.into()) }
}

/// Record something for the operator. SSH users only ever see generic errors, so details go to
/// syslog (facility daemon, tag `gitv`), or, when `GITV_LOG` names a file, are appended there
/// for local runs and tests.
fn log_operator(message: &str) {
    let mut message = message.to_string();
    if let Some(path) = std::env::var_os("GITV_LOG") {
        // Only a record that was actually written counts; otherwise fall back to syslog, so
        // the message is never lost, and say why it ended up there.
        match append_line(Path::new(&path), &format!("gitv: {message}")) {
            Ok(()) => return,
            Err(e) => message = format!("{message} (couldn't write {}: {e})", Path::new(&path).display()),
        }
    }
    let message = std::ffi::CString::new(message.replace('\0', " ")).unwrap_or_default();
    // SAFETY: both strings are NUL-terminated and outlive the calls; "%s" keeps the message
    // from being read as a format string.
    unsafe {
        nix::libc::openlog(c"gitv".as_ptr(), nix::libc::LOG_PID, nix::libc::LOG_DAEMON);
        nix::libc::syslog(nix::libc::LOG_WARNING, c"%s".as_ptr(), message.as_ptr());
    }
}

/// Append one line to a file, creating it if needed, and make sure it reached the file.
fn append_line(path: &Path, line: &str) -> std::io::Result<()> {
    let mut file = fs::File::options().create(true).append(true).open(path)?;
    file.write_all(format!("{line}\n").as_bytes())?;
    file.flush()
}

fn is_root() -> bool {
    nix::unistd::geteuid().is_root()
}

/// The `git` account's ids, when running as root and new files must be handed to it.
fn git_account() -> Result<Option<(Uid, Gid)>, String> {
    if !is_root() {
        return Ok(None);
    }
    let user = nix::unistd::User::from_name("git").map_err(|e| e.to_string())?.ok_or("no git account")?;
    Ok(Some((user.uid, user.gid)))
}

/// The owner's directory, created if needed and returned open. Anything else at that name,
/// including a symlink to a directory, is refused rather than followed.
fn owner_directory(owner: &str) -> Result<OwnedFd, String> {
    let root = open_root().ok_or("cannot open the repository root")?;
    let display = repos_root().join(owner);
    // Another push may create it at the same moment; either way, open what's there after.
    match mkdirat(&root, owner, Mode::from_bits_truncate(0o755)) {
        Ok(()) | Err(Errno::EEXIST) => {}
        Err(e) => return Err(format!("cannot create {}: {e}", display.display())),
    }
    let directory =
        open_dir_at(&root, OsStr::new(owner)).map_err(|_| format!("{} is not a directory", display.display()))?;
    if let Some((uid, gid)) = git_account()? {
        fchown(&directory, Some(uid), Some(gid)).map_err(|e| e.to_string())?;
    }
    Ok(directory)
}

/// Create `<owner>/<name>.git`.
///
/// The repository is built inside a private staging directory (mode 0700, made fresh under the
/// open owner directory), so no other user can rename, replace or remove anything inside it.
/// Initialisation, permissions and ownership all go through handles, and publication renames
/// out of the staging directory's own handle into the owner directory's, refusing to replace
/// anything at the name. What gets published is therefore exactly what git initialised.
fn create(owner: &str, name: &str) -> Result<Created, CreateError> {
    publish_new(owner, name, Contents::Empty)
}

/// What a new repository starts as.
#[derive(Clone, Copy)]
enum Contents<'a> {
    /// `git init --bare`.
    Empty,
    /// A copy of the bare repository at this path, outside the live tree: one restored from a
    /// backup, say.
    CopyOf(&'a Path),
}

/// Make `<owner>/<name>.git` from `contents`, as described for [`create`].
fn publish_new(owner: &str, name: &str, contents: Contents) -> Result<Created, CreateError> {
    let directory = owner_directory(owner).map_err(CreateError::Failed)?;
    let target = format!("{name}.git");
    if kind_at(&directory, OsStr::new(&target)).is_some() {
        return Err(CreateError::EXISTS);
    }
    let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.subsec_nanos());
    let staging_name = format!(".create-{}-{nanos}-{name}", std::process::id());
    mkdirat(&directory, staging_name.as_str(), Mode::S_IRWXU)
        .map_err(|e| CreateError::Failed(format!("couldn't make a staging directory: {e}")))?;
    let built = open_dir_at(&directory, OsStr::new(&staging_name))
        .map_err(|e| CreateError::Failed(format!("couldn't open the staging directory: {e}")))
        .and_then(|staging| {
            // The directory just made must be ours and private; anything else at the name means
            // someone got there first, so give up rather than build in it.
            let stat = fstat(staging.as_fd()).map_err(|e| CreateError::Failed(e.to_string()))?;
            if stat.st_uid != geteuid().as_raw() || stat.st_mode & 0o077 != 0 {
                return Err(CreateError::Failed("the staging directory isn't private".into()));
            }
            build_and_publish(&directory, &staging, &target, contents)
        });
    // The staging directory is empty now, whether the repository was published or rolled
    // back. Removing it by name only ever removes an empty directory.
    let leftover = unlinkat(&directory, staging_name.as_str(), UnlinkatFlags::RemoveDir).err().map(|e| {
        format!("couldn't remove the staging directory {}: {e}", repos_root().join(owner).join(&staging_name).display())
    });
    if let Some(leftover) = &leftover {
        // Whatever the outcome and whoever asked, the operator needs to know.
        log_operator(&format!("creating {owner}/{name}.git: {leftover}"));
    }
    match built {
        Ok(()) => Ok(Created { leftover }),
        // A failure that also left something behind carries both, so whoever reads the detail
        // (an administrator, or the operator log) learns about the directory to clean up.
        Err(error) => Err(match leftover {
            None => error,
            Some(leftover) => error.with_leftover(leftover),
        }),
    }
}

/// A repository was created; `leftover` describes anything the operator must clean up.
struct Created {
    leftover: Option<String>,
}

/// Why creation didn't happen. `Exists` is safe to tell anyone; `Failed` carries server details
/// (paths, git's own messages) that only the operator or an administrator should see.
enum CreateError {
    /// Something is already at the name. `leftover` notes anything the attempt left behind.
    Exists {
        leftover: Option<String>,
    },
    Failed(String),
}

impl CreateError {
    const EXISTS: CreateError = CreateError::Exists { leftover: None };

    /// The full story, for the operator or an administrator.
    fn detail(&self) -> String {
        match self {
            CreateError::Exists { leftover: None } => "repository already exists".into(),
            CreateError::Exists { leftover: Some(leftover) } => format!("repository already exists; also {leftover}"),
            CreateError::Failed(detail) => detail.clone(),
        }
    }

    fn with_leftover(self, leftover: String) -> CreateError {
        match self {
            CreateError::Exists { .. } => CreateError::Exists { leftover: Some(leftover) },
            CreateError::Failed(detail) => CreateError::Failed(format!("{detail}; also {leftover}")),
        }
    }
}

/// Run a command whose output only an operator should see: stdout is dropped, and stderr is
/// captured into the error instead of reaching whoever is connected.
fn run_privately(mut command: Command, what: &str) -> Result<(), String> {
    let output = command.stdout(Stdio::null()).output().map_err(|e| format!("{what} couldn't start: {e}"))?;
    if output.status.success() {
        Ok(())
    } else {
        let message = String::from_utf8_lossy(&output.stderr).trim().to_string();
        Err(format!(
            "{what} failed ({}){}",
            output.status,
            if message.is_empty() { String::new() } else { format!(": {message}") }
        ))
    }
}

/// Build a bare repository at `repo` inside the private `staging` directory, then move it to
/// `target` in `directory`. If anything fails after `repo` was made, it is removed again; it
/// never removes a `repo` this call didn't make.
fn build_and_publish(
    directory: &OwnedFd,
    staging: &OwnedFd,
    target: &str,
    contents: Contents,
) -> Result<(), CreateError> {
    let failed = |e: &dyn std::fmt::Display| CreateError::Failed(e.to_string());
    // Only once this succeeds is `repo` ours to roll back.
    mkdirat(staging, "repo", Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?;
    let built = (|| {
        let repo = open_dir_at(staging, OsStr::new("repo")).map_err(|e| failed(&e))?;
        match contents {
            Contents::Empty => {
                // A clean environment, so no caller's init.templateDir can plant hooks in it;
                // and its output stays private, whoever is connected.
                let mut init = git_in(&repo);
                init.args(["init", "--quiet", "--bare", "--initial-branch=main", "."]);
                run_privately(init, "git init").map_err(CreateError::Failed)?;
            }
            Contents::CopyOf(source) => {
                // Everything, the visibility marker, description and HEAD included, with modes and
                // times; links are copied as links, never followed. Not owners (set below) and
                // not SELinux labels: new files take the repository tree's own, not those of
                // the folder a restore was staged in.
                let mut copy = gitv_core::command_in(&repo, "cp");
                copy.args(["-R", "-P", "--preserve=mode,timestamps,links", "--"]).arg(source.join(".")).arg(".");
                run_privately(copy, "copying the repository").map_err(CreateError::Failed)?;
                // Nothing is published that git can't read whole.
                let mut fsck = git_in(&repo);
                fsck.args(["--git-dir=.", "fsck", "--no-progress", "--full"]);
                run_privately(fsck, "git fsck").map_err(CreateError::Failed)?;
            }
        }
        fchmod(&repo, Mode::from_bits_truncate(0o750)).map_err(|e| failed(&e))?;
        if let Some((uid, gid)) = git_account().map_err(CreateError::Failed)? {
            chown_tree(&repo, uid, gid).map_err(|e| failed(&e))?;
        }
        renameat2(staging, "repo", directory, target, RenameFlags::RENAME_NOREPLACE)
            .map_err(|e| if e == Errno::EEXIST { CreateError::EXISTS } else { failed(&e) })
    })();
    if let Err(error) = built {
        return Err(match remove_tree_at(staging, OsStr::new("repo")) {
            Ok(()) => error,
            Err(e) => {
                let problem = format!("couldn't remove a half-built repository after \"{}\": {e}", error.detail());
                log_operator(&problem);
                CreateError::Failed(problem)
            }
        });
    }
    Ok(())
}

/// Copy the bare repository at `source` into the live tree as `<owner>/<name>.git`, never
/// replacing anything already there: how a repository restored from a backup goes back.
fn import(owner: &str, name: &str, source: &Path) -> Result<(), String> {
    // Only a real bare repository is copied: a directory, not a link to one, with a HEAD file.
    let from = gitv_core::open_dir(source).map_err(|e| format!("can't open {}: {e}", source.display()))?;
    if kind_at(&from, OsStr::new("HEAD")) != Some(nix::sys::stat::SFlag::S_IFREG) {
        return Err(format!("{} isn't a bare repository", source.display()));
    }
    match publish_new(owner, name, Contents::CopyOf(source)) {
        Ok(created) => {
            println!("imported git@{}:{owner}/{name}.git", config::host());
            if let Some(leftover) = created.leftover {
                eprintln!("gitv: imported {owner}/{name}.git, but {leftover}");
            }
            Ok(())
        }
        Err(CreateError::Exists { .. }) => {
            Err(format!("{owner}/{name}.git already exists; import under another name, or delete it first"))
        }
        Err(error) => Err(error.detail()),
    }
}

/// Deleted repositories wait in `<owner>/.trash` for this many days before `gitv purge` removes them.
const TRASH_DAYS: u64 = 30;
/// The trash directory inside each owner's directory. Its leading dot keeps it out of every listing.
const TRASH: &str = ".trash";

/// The owner's trash directory, created (private, and the git account's) if needed.
fn trash_directory(owner_dir: &OwnedFd) -> Result<OwnedFd, String> {
    match mkdirat(owner_dir, TRASH, Mode::S_IRWXU) {
        Ok(()) | Err(Errno::EEXIST) => {}
        Err(e) => return Err(format!("cannot create the trash: {e}")),
    }
    let trash = open_dir_at(owner_dir, OsStr::new(TRASH)).map_err(|_| "the trash is not a directory".to_string())?;
    if let Some((uid, gid)) = git_account()? {
        fchown(&trash, Some(uid), Some(gid)).map_err(|e| e.to_string())?;
    }
    Ok(trash)
}

/// A trash entry's repository name and deletion time: `<name>.<unix seconds>`.
fn parse_trash_entry(entry: &str) -> Option<(&str, u64)> {
    let (name, stamp) = entry.rsplit_once('.')?;
    (valid_name(name) && !stamp.is_empty() && stamp.bytes().all(|b| b.is_ascii_digit()))
        .then_some((name, stamp.parse().ok()?))
}

/// Move `<owner>/<name>.git` into the owner's trash, returning the trash entry's name. One handle
/// on the owner directory serves the check and the move; if the entry were swapped for a symlink
/// after the check, only the link would be moved. Nothing is removed until `gitv purge`.
fn delete(owner: &str, name: &str) -> Result<String, String> {
    let directory = open_owner(owner).ok_or("repository unavailable")?;
    repo_in(&directory, owner, name).ok_or("repository unavailable")?;
    let trash = trash_directory(&directory)?;
    let entry = format!("{name}.{}", unix_now());
    renameat2(&directory, format!("{name}.git").as_str(), &trash, entry.as_str(), RenameFlags::RENAME_NOREPLACE)
        .map_err(|e| match e {
            Errno::EEXIST => "the repository was deleted moments ago under the same name; try again".to_string(),
            e => e.to_string(),
        })?;
    Ok(entry)
}

/// Every trash entry: owner, entry name, and deletion time when the name carries one.
fn trash_entries() -> Result<Vec<(String, String, Option<u64>)>, String> {
    let root = open_root().ok_or("cannot open the repository root")?;
    let mut found = Vec::new();
    for owner in entries(&root).into_iter().filter_map(|o| o.into_string().ok()).filter(|o| valid_name(o)) {
        let Some(owner_dir) = open_owner(&owner) else { continue };
        let trash = match open_dir_at(&owner_dir, OsStr::new(TRASH)) {
            Ok(trash) => trash,
            Err(Errno::ENOENT) => continue,
            Err(e) => return Err(format!("cannot open {owner}/{TRASH}: {e}")),
        };
        let names = gitv_core::try_entries(&trash).map_err(|e| format!("cannot list {owner}/{TRASH}: {e}"))?;
        for entry in names {
            let entry = entry.to_string_lossy().into_owned();
            let stamp = parse_trash_entry(&entry).map(|(_, stamp)| stamp);
            found.push((owner.clone(), entry, stamp));
        }
    }
    found.sort();
    Ok(found)
}

fn list_trash() -> Result<(), String> {
    let now = unix_now();
    for (owner, entry, stamp) in trash_entries()? {
        match stamp {
            Some(stamp) => {
                let days = now.saturating_sub(stamp) / 86_400;
                let left = TRASH_DAYS.saturating_sub(days);
                println!("{owner} {entry}  deleted {days} days ago, purged in {left} days");
            }
            None => println!("{owner} {entry}  (not a trash entry; purge leaves it alone)"),
        }
    }
    Ok(())
}

/// Move a trash entry back to `<owner>/<name>.git`, never replacing anything at that name.
fn restore(owner: &str, entry: &str, as_name: Option<&str>) -> Result<(), String> {
    let (original, _) = parse_trash_entry(entry).ok_or("not a trash entry; see `gitv trash`")?;
    let name = as_name.unwrap_or(original);
    let directory = open_owner(owner).ok_or("no such owner")?;
    let trash = open_dir_at(&directory, OsStr::new(TRASH)).map_err(|_| "this owner has no trash")?;
    renameat2(&trash, entry, &directory, format!("{name}.git").as_str(), RenameFlags::RENAME_NOREPLACE).map_err(
        |e| match e {
            Errno::EEXIST => format!("{owner}/{name}.git already exists; restore with --as <other name>"),
            Errno::ENOENT => "no such trash entry; see `gitv trash`".to_string(),
            e => e.to_string(),
        },
    )?;
    println!("restored git@{}:{owner}/{name}.git", config::host());
    Ok(())
}

/// Remove trash entries deleted at least `days` days ago, through handles and without following
/// symlinks. Entries that don't look like `<name>.<time>` are left for a person to look at.
fn purge(days: u64) -> Result<(), String> {
    let cutoff = days.saturating_mul(86_400);
    let now = unix_now();
    let mut failures = 0;
    for (owner, entry, stamp) in trash_entries()? {
        let Some(stamp) = stamp else { continue };
        if now.saturating_sub(stamp) < cutoff {
            continue;
        }
        let removed = open_owner(&owner)
            .ok_or_else(|| "owner directory unavailable".to_string())
            .and_then(|dir| open_dir_at(&dir, OsStr::new(TRASH)).map_err(|e| e.to_string()))
            .and_then(|trash| remove_tree_at(&trash, OsStr::new(&entry)).map_err(|e| e.to_string()));
        match removed {
            Ok(()) => println!("purged {owner}/{TRASH}/{entry}"),
            Err(e) => {
                failures += 1;
                log_operator(&format!("purging {owner}/{TRASH}/{entry}: {e}"));
                eprintln!("gitv: couldn't purge {owner}/{TRASH}/{entry}: {e}");
            }
        }
    }
    if failures == 0 { Ok(()) } else { Err(format!("{failures} trash entries couldn't be purged")) }
}

fn add_key(owner: &str, file: &Path, label: Option<&str>) -> Result<(), String> {
    let text = fs::read_to_string(file).map_err(|e| e.to_string())?;
    let parts: Vec<&str> = text.split_whitespace().collect();
    if parts.len() < 2 || parts[0] != "ssh-ed25519" {
        return Err("expected an OpenSSH Ed25519 public key".into());
    }
    let engine = base64::engine::general_purpose::STANDARD;
    let blob = engine.decode(parts[1]).map_err(|_| "invalid Ed25519 public key")?;
    let mut header = 11u32.to_be_bytes().to_vec();
    header.extend_from_slice(b"ssh-ed25519");
    header.extend_from_slice(&32u32.to_be_bytes());
    if blob.len() != 51 || blob[..19] != header[..] {
        return Err("invalid Ed25519 public key".into());
    }
    let token = engine.encode(&blob);
    // Prepare everything the key needs first: publishing the key file is the last step, so a
    // failure leaves no key installed and a retry starts clean.
    owner_directory(owner)?;
    // The key file's own comment is dropped (it is often an email address); only a label the
    // operator chose is kept.
    let comment = label.map(|l| format!(" {l}")).unwrap_or_default();
    let mut relabelled = false;
    edit_keys(|old| {
        let registered: Vec<KeyLine> = old.lines().filter_map(parse_key_line).filter(|k| k.blob == blob).collect();
        if registered.is_empty() {
            let separator = if old.is_empty() || old.ends_with('\n') { "" } else { "\n" };
            let command = config::command();
            return Ok(format!(
                "{old}{separator}restrict,command=\"{command} serve {owner}\" ssh-ed25519 {token}{comment}\n"
            ));
        }
        // Registering a key again with a label renames it, but only for the owner it already
        // serves: a key never moves to another owner this way.
        let Some(label) = label else { return Err("key already registered".into()) };
        if registered.iter().any(|k| k.owner() != Some(owner)) {
            return Err("key already registered for another owner".into());
        }
        relabelled = true;
        Ok(old
            .split_inclusive('\n')
            .map(|row| {
                let line = row.trim_end_matches(['\n', '\r']);
                match parse_key_line(line) {
                    // Everything up to the key stays as it was, options included.
                    Some(k) if k.blob == blob => format!("{} {label}{}", &line[..k.key_end], &row[line.len()..]),
                    _ => row.to_string(),
                }
            })
            .collect())
    })?;
    if relabelled {
        println!("relabelled {} as {}", fingerprint(&blob), label.unwrap_or_default());
    }
    Ok(())
}

/// Read the keys file, let `change` produce its new contents, and publish them, all under the
/// keys lock, so two administrators changing keys at once can't undo each other's work.
fn edit_keys(change: impl FnOnce(&str) -> Result<String, String>) -> Result<(), String> {
    let keys = keys_path();
    let directory = keys.parent().ok_or("authorized_keys has no directory")?;
    let lock =
        fs::File::options().create(true).append(true).open(directory.join("keys.lock")).map_err(|e| e.to_string())?;
    let _lock = Flock::lock(lock, FlockArg::LockExclusive).map_err(|(_, e)| e.to_string())?;
    let old = read_keys(&keys)?;
    let new = change(&old)?;
    // Readable by sshd. The change counts only once the rename survives a crash.
    gitv_core::publish_file(&keys, new.as_bytes(), 0o644, true, |_| Ok::<(), String>(()))
        .map_err(|e| format!("couldn't write {}: {e}", keys.display()))?;
    relabel(&keys, Path::new("/sys/fs/selinux"), Path::new("/usr/sbin/restorecon"))
}

/// The keys file's contents; a missing file holds no keys.
fn read_keys(keys: &Path) -> Result<String, String> {
    match fs::read_to_string(keys) {
        Ok(text) => Ok(text),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
        Err(e) => Err(format!("couldn't read {}: {e}", keys.display())),
    }
}

/// A key's fingerprint as `ssh-keygen -l` prints it: unpadded base64 of the blob's SHA-256.
fn fingerprint(blob: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    format!("SHA256:{}", base64::engine::general_purpose::STANDARD_NO_PAD.encode(Sha256::digest(blob)))
}

/// Print every active key, one per line: owner, fingerprint, label. Lines not written by
/// `add-key` are listed too, with `-` for an owner that isn't a GITv forced command.
fn list_keys(only: Option<&str>) -> Result<(), String> {
    let text = read_keys(&keys_path())?;
    let rows: Vec<(&str, String, &str)> = text
        .lines()
        .filter_map(parse_key_line)
        .map(|k| (k.owner().unwrap_or("-"), fingerprint(&k.blob), k.comment))
        .filter(|(owner, _, _)| only.is_none_or(|o| o == *owner))
        .collect();
    if rows.is_empty() {
        eprintln!("gitv: no keys registered");
    }
    let width = rows.iter().map(|(owner, _, _)| owner.len()).max().unwrap_or(0);
    for (owner, fingerprint, label) in rows {
        println!("{owner:<width$}  {fingerprint}  {label}");
    }
    Ok(())
}

/// Remove the key with this fingerprint. Every other line, including comments and lines
/// `add-key` didn't write, is kept byte for byte.
fn remove_key(wanted: &str) -> Result<(), String> {
    let wanted = format!("SHA256:{}", wanted.strip_prefix("SHA256:").unwrap_or(wanted));
    let mut removed = Vec::new();
    edit_keys(|old| {
        let mut kept = String::with_capacity(old.len());
        for row in old.split_inclusive('\n') {
            match parse_key_line(row.trim_end_matches(['\n', '\r'])) {
                Some(k) if fingerprint(&k.blob) == wanted => {
                    removed.push(format!("{} {}", k.owner().unwrap_or("-"), k.comment).trim_end().to_string())
                }
                _ => kept.push_str(row),
            }
        }
        if removed.is_empty() {
            return Err(format!("no key has the fingerprint {wanted}; run: gitv keys"));
        }
        Ok(kept)
    })?;
    for key in removed {
        println!("removed {wanted} ({key}); connections already open stay open until they end");
    }
    Ok(())
}

/// Give a file the SELinux label the system's policy names for its path. A file published by
/// rename carries the label its directory gives new files, not the one the policy names (sshd
/// reads authorized keys labelled `ssh_home_t`), so without this every added key would leave
/// the keys file mislabelled. Does nothing where SELinux is off or restorecon isn't installed.
fn relabel(path: &Path, selinuxfs: &Path, restorecon: &Path) -> Result<(), String> {
    if !selinuxfs.join("enforce").exists() || !restorecon.is_file() {
        return Ok(());
    }
    let status = Command::new(restorecon).arg(path).stdin(Stdio::null()).status();
    match status {
        Ok(status) if status.success() => Ok(()),
        outcome => Err(format!(
            "updated the keys, but couldn't give {} its SELinux label ({}); run: restorecon {0}",
            path.display(),
            outcome.map_or_else(|e| e.to_string(), |s| s.to_string())
        )),
    }
}

/// An active authorized_keys line, taken apart.
struct KeyLine<'a> {
    options: &'a str,
    blob: Vec<u8>,
    comment: &'a str,
    /// Where the key field ends in the line given to [`parse_key_line`].
    key_end: usize,
}

impl<'a> KeyLine<'a> {
    /// The owner a GITv forced command (`command="<gitv> serve <owner>"`) serves.
    fn owner(&self) -> Option<&'a str> {
        let start = self.options.find("command=\"")? + "command=\"".len();
        let options: &'a str = self.options;
        let value = &options[start..];
        let value = &value[..value.find('"')?];
        match value.split_whitespace().collect::<Vec<_>>().as_slice() {
            [_, "serve", owner] if valid_name(owner) => Some(owner),
            _ => None,
        }
    }
}

/// Split off the field at the start of `text` (after any spaces or tabs) from what follows it.
fn next_field(text: &str) -> Option<(&str, &str)> {
    let text = text.trim_start_matches([' ', '\t']);
    let end = text.find([' ', '\t']).unwrap_or(text.len());
    (end > 0).then(|| (&text[..end], text[end..].trim_matches([' ', '\t'])))
}

/// The options, decoded key and comment of an authorized_keys line, wherever the key sits.
///
/// A line is `[options] type key [comment]`. Blank and `#` lines are skipped, options are
/// skipped as one field (they can hold quoted spaces), and only the key field itself is read,
/// so a key mentioned in a comment or a commented-out line doesn't count.
fn parse_key_line(line: &str) -> Option<KeyLine<'_>> {
    const TYPES: [&str; 4] = ["ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "sk-ssh-ed25519@openssh.com"];
    let original = line;
    let line = line.trim_start();
    if line.is_empty() || line.starts_with('#') {
        return None;
    }
    // Fields are separated by spaces or tabs. The first is the key type, or else the options.
    let (first, _) = next_field(line)?;
    let (options, rest) = if TYPES.contains(&first) {
        ("", line)
    } else {
        let rest = skip_options(line)?;
        (&line[..line.len() - rest.len()], rest)
    };
    let (kind, rest) = next_field(rest)?;
    if !TYPES.contains(&kind) {
        return None;
    }
    let (key, comment) = next_field(rest)?;
    let blob = base64::engine::general_purpose::STANDARD.decode(key).ok()?;
    // Every field is a slice of the line handed in, so its position is its address's offset.
    let key_end = key.as_ptr() as usize - original.as_ptr() as usize + key.len();
    Some(KeyLine { options: options.trim_end(), blob, comment, key_end })
}

/// What follows the options field: its end is the first whitespace outside double quotes.
fn skip_options(line: &str) -> Option<&str> {
    let mut quoted = false;
    let mut escaped = false;
    for (i, c) in line.char_indices() {
        match c {
            _ if escaped => escaped = false,
            '\\' => escaped = true,
            '"' => quoted = !quoted,
            c if c.is_whitespace() && !quoted => return Some(line[i..].trim_start()),
            _ => {}
        }
    }
    None
}

fn visibility(owner: &str, name: &str, visibility: &str) -> Result<(), String> {
    let public = match visibility {
        "public" => true,
        "private" => false,
        _ => return Err("choose public or private".into()),
    };
    repo_dir(check_name(owner)?, check_name(name)?)
        .ok_or("repository unavailable")?
        .set_public(public)
        .map_err(|e| format!("couldn't set visibility: {e}"))
}

/// Print whether a repository is protected, or turn protection `on` or `off`.
fn protect(owner: &str, name: &str, value: Option<&str>) -> Result<(), String> {
    let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?;
    let on = match value {
        None => {
            println!("{}", if repo.is_protected() { "on" } else { "off" });
            return Ok(());
        }
        Some("on") => true,
        Some("off") => false,
        Some(_) => return Err("choose on or off".into()),
    };
    repo.set_protected(on).map_err(|e| format!("couldn't set protection: {e}"))
}

/// Print a repository's description, or set it to `text`; an empty text removes it.
fn description(owner: &str, name: &str, text: Option<&str>) -> Result<(), String> {
    let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?;
    let Some(text) = text else {
        if let Some(text) = repo.description() {
            println!("{text}");
        }
        return Ok(());
    };
    // One line of plain text: the web shows it, and a terminal may print it.
    let text = text.trim();
    if text.chars().count() > DESCRIPTION_LIMIT || text.chars().any(char::is_control) {
        return Err(format!("a description is one line of at most {DESCRIPTION_LIMIT} characters"));
    }
    repo.set_description((!text.is_empty()).then_some(text)).map_err(|e| format!("couldn't set the description: {e}"))
}

/// Print the default branch (where HEAD points), or point it at an existing `branch`.
fn default_branch(owner: &str, name: &str, branch: Option<&str>) -> Result<(), String> {
    let repo = repo_dir(check_name(owner)?, check_name(name)?).ok_or("repository unavailable")?;
    let Some(branch) = branch else {
        let head = git(&repo, &["symbolic-ref", "HEAD"]).map_err(|_| "HEAD doesn't name a branch".to_string())?;
        let head = head.strip_suffix(b"\n").unwrap_or(&head);
        println!("{}", String::from_utf8_lossy(head.strip_prefix(b"refs/heads/").unwrap_or(head)));
        return Ok(());
    };
    // Qualified, so a name like `-x` or `HEAD` can only ever mean a branch, and checked as a
    // ref name before git is asked whether that branch exists.
    let full = format!("refs/heads/{branch}");
    let exists = git(&repo, &["check-ref-format", &full]).is_ok()
        && git(&repo, &["rev-parse", "--verify", "--quiet", &format!("{full}^{{commit}}")]).is_ok();
    if !exists {
        return Err(format!("there's no branch named {branch}; push it first"));
    }
    git(&repo, &["symbolic-ref", "HEAD", &full]).map_err(|_| "couldn't set the default branch".to_string())?;
    Ok(())
}

/// Handle one SSH request from a key registered to owner.
fn serve(owner: &str, command: &str) -> Result<u8, String> {
    let args =
        shlex::split(command).ok_or_else(|| format!("unreadable command; run: ssh git@{} help", config::host()))?;
    let args: Vec<&str> = args.iter().map(String::as_str).collect();
    match args.as_slice() {
        [] | ["help"] => println!("{}", help()),
        [program @ ("git-upload-pack" | "git-receive-pack"), path] => return serve_git(owner, program, path),
        ["visibility", name, value] => visibility(owner, name, value)?,
        // Unquoted words are one description: `description tools A small toolbox`.
        ["protect", name] => protect(owner, name, None)?,
        ["protect", name, value] => protect(owner, name, Some(value))?,
        ["description", name] => description(owner, name, None)?,
        ["description", name, text @ ..] => description(owner, name, Some(&text.join(" ")))?,
        ["default-branch", name] => default_branch(owner, name, None)?,
        ["default-branch", name, branch] => default_branch(owner, name, Some(branch))?,
        ["list"] => {
            // Listed and checked through one handle on the owner's directory.
            let directory = open_owner(owner);
            let mut names: Vec<String> = directory
                .iter()
                .flat_map(entries)
                .filter_map(|e| e.to_str()?.strip_suffix(".git").map(str::to_string))
                .filter(|n| directory.as_ref().is_some_and(|d| repo_in(d, owner, n).is_some()))
                .collect();
            names.sort();
            for name in names {
                println!("git@{}:{owner}/{name}.git", config::host());
            }
        }
        ["create", name] => {
            // A key holder learns whether it worked, and the clone address; server details go
            // to the operator's log.
            let name = check_name(name)?;
            match create(owner, name) {
                Ok(_) => println!("git@{}:{owner}/{name}.git", config::host()),
                Err(CreateError::Exists { .. }) => return Err("repository already exists".into()),
                Err(error) => {
                    log_operator(&format!("ssh create of {owner}/{name}.git failed: {}", error.detail()));
                    return Err("couldn't create the repository; the server's operator can see why".into());
                }
            }
        }
        ["delete", name, rest @ ..] => {
            let name = check_name(name)?;
            if rest != ["--yes"] {
                return Err(format!(
                    "this moves {owner}/{name}.git to the trash, where only the server's operator can restore it; run: delete {name} --yes"
                ));
            }
            let entry = delete(owner, name)?;
            log_operator(&format!(
                "{owner}/{name}.git moved to the trash as {owner}/{TRASH}/{entry} by its owner's key"
            ));
            println!(
                "moved {owner}/{name}.git to the trash; the server's operator can restore it for {TRASH_DAYS} days"
            );
        }
        _ => return Err(format!("unknown command; run: ssh git@{} help", config::host())),
    }
    Ok(0)
}

/// Parse `owner/name.git` or `owner/name` (optionally with leading or trailing slash), as
/// git clients send either and HTTPS clone addresses carry no `.git`.
fn parse_request(path: &str) -> Option<(&str, &str)> {
    let path = path.strip_prefix('/').unwrap_or(path);
    let path = path.strip_suffix('/').unwrap_or(path);
    let (owner, rest) = path.split_once('/')?;
    let name = rest.strip_suffix(".git").unwrap_or(rest);
    (valid_name(owner) && valid_name(name)).then_some((owner, name))
}

fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> {
    let (requested, name) = parse_request(path).ok_or("repository unavailable")?;
    if requested != owner {
        return Err("repository unavailable".into());
    }
    let repo = match repo_dir(owner, name) {
        Some(repo) => repo,
        None if program != "git-receive-pack" => return Err("repository unavailable".into()),
        None => {
            // Pushing to a new name creates it, so a fresh project needs no setup step. create()
            // never replaces anything at the name, so a symlink or file there is refused. If a
            // racing push created the repository first, at any moment, this one opens it afresh;
            // either way what it gets must be a real repository.
            // The client only ever hears "repository unavailable"; the cause goes to the
            // operator's log. Losing a race to a push that created it is ordinary, so that stays
            // quiet (create() has already logged any cleanup problem either way).
            match create(owner, name) {
                Ok(_) => eprintln!("gitv: created {owner}/{name}.git"),
                // Another push created it first: ordinary, so quiet.
                Err(CreateError::Exists { .. }) if repo_dir(owner, name).is_some() => {}
                // This attempt genuinely failed, though a racing push's repository lets the
                // push carry on: the operator still hears why.
                Err(error) if repo_dir(owner, name).is_some() => {
                    log_operator(&format!("first push to {owner}/{name}.git couldn't create it: {}", error.detail()));
                }
                Err(error) => {
                    log_operator(&format!("first push to {owner}/{name}.git couldn't create it: {}", error.detail()));
                    return Err("repository unavailable".into());
                }
            }
            repo_dir(owner, name).ok_or("repository unavailable")?
        }
    };
    // Run inside the opened directory, so the path can't be swapped for a symlink meanwhile.
    let mut command = repo.command(program);
    // The same clean environment as every other git GITv runs, system config included.
    gitv_core::configure(&mut command);
    command.arg(".");
    // Pass the client's protocol request through (when sshd accepts it), so clients can use the
    // faster protocol v2.
    if let Some(protocol) = std::env::var("GIT_PROTOCOL").ok().as_deref().and_then(gitv_core::git_protocol) {
        command.env("GIT_PROTOCOL", protocol);
    }
    let pushing = program == "git-receive-pack";
    // A push holds the repository's lock shared from its first look at the refs until HEAD is
    // settled, so a backup (which holds it exclusive) copies before the push or after it.
    let _lock = if pushing {
        Some(repo.lock(false).map_err(|e| {
            log_operator(&format!("{owner}/{name}.git: couldn't lock for a push: {e}"));
            "repository unavailable".to_string()
        })?)
    } else {
        None
    };
    let before = if pushing {
        // Every ref update gets a reflog entry (bare repositories keep none by default), and
        // objects nothing refers to any more stay as long as those entries do. Given through
        // the environment, so it covers every repository, old or new, and the gc a push
        // triggers inherits it.
        // A protected repository also refuses force-pushes and deletions of every branch (git
        // applies these to refs/heads only; tags stay movable, and the push log records them).
        // Given here, not in the repository's own config, so only `gitv protect` changes it.
        let protection: &[(&str, &str)] = if repo.is_protected() { &PROTECTED_CONFIG } else { &[] };
        let settings: Vec<_> = PUSH_CONFIG.iter().chain(protection).collect();
        command.envs(settings.iter().enumerate().flat_map(|(i, (key, value))| {
            [(format!("GIT_CONFIG_KEY_{i}"), *key), (format!("GIT_CONFIG_VALUE_{i}"), *value)]
        }));
        command.env("GIT_CONFIG_COUNT", settings.len().to_string());
        ref_snapshot(&repo)
            .inspect_err(|e| log_operator(&format!("{owner}/{name}.git: no push log for this push: {e}")))
            .ok()
    } else {
        None
    };
    let status = command.stdin(Stdio::inherit()).stdout(Stdio::inherit()).status().map_err(|e| e.to_string())?;
    if let Some(before) = before
        && let Err(e) = ref_snapshot(&repo).and_then(|after| record_push(&repo, &before, &after))
    {
        log_operator(&format!("{owner}/{name}.git: couldn't write the push log: {e}"));
    }
    if pushing && status.success() {
        fix_head(&repo)?;
    }
    Ok(status.code().unwrap_or(1) as u8)
}

/// Configuration every push runs with: no hooks, and what lets overwritten or deleted history be
/// recovered for [`TRASH_DAYS`] (reflogs on every ref, unreachable objects kept as long as
/// their entries).
/// The gc a push may trigger runs within the push rather than detached, so it finishes under
/// the push's lock too.
const PUSH_CONFIG: [(&str, &str); 5] = [
    // GITv runs no hooks. A hook in the repository's own folder (one copied in by `gitv
    // import`, say) would run as the git account on every push, so none ever runs.
    ("core.hooksPath", "/dev/null"),
    ("core.logAllRefUpdates", "always"),
    ("gc.reflogExpireUnreachable", "30.days.ago"),
    ("gc.pruneExpire", "30.days.ago"),
    ("gc.autoDetach", "false"),
];

/// What a protected repository's pushes also run with: no branch may move except forwards,
/// and none may be deleted.
const PROTECTED_CONFIG: [(&str, &str); 2] = [("receive.denyNonFastForwards", "true"), ("receive.denyDeletes", "true")];

/// Where each repository records its pushes' ref changes. Git drops a branch's reflog when the
/// branch is deleted; this keeps the commit it pointed at findable.
const PUSH_LOG: &str = "gitv-push.log";

/// Every ref and the object it names.
fn ref_snapshot(repo: &RepoDir) -> Result<BTreeMap<Vec<u8>, Vec<u8>>, String> {
    let out = git(repo, &["for-each-ref", "--format=%(objectname) %(refname)"])?;
    // A ref name can't contain a space or a newline.
    Ok(out
        .split(|b| *b == b'\n')
        .filter_map(|line| {
            let space = line.iter().position(|b| *b == b' ')?;
            Some((line[space + 1..].to_vec(), line[..space].to_vec()))
        })
        .collect())
}

/// Append one line per changed ref to [`PUSH_LOG`]: `<unix time> <old> <new> <ref>`, with `-`
/// for a ref that didn't exist before or doesn't after. Two pushes landing at once may share
/// their lines between them, but every change before and after is recorded.
fn record_push(
    repo: &RepoDir,
    before: &BTreeMap<Vec<u8>, Vec<u8>>,
    after: &BTreeMap<Vec<u8>, Vec<u8>>,
) -> Result<(), String> {
    let now = unix_now().to_string();
    let mut lines = Vec::new();
    let mut line = |old: &[u8], new: &[u8], name: &[u8]| {
        lines.extend_from_slice(now.as_bytes());
        for field in [old, new, name] {
            lines.push(b' ');
            lines.extend_from_slice(field);
        }
        lines.push(b'\n');
    };
    for (name, old) in before {
        match after.get(name) {
            Some(new) if new == old => {}
            Some(new) => line(old, new, name),
            None => line(old, b"-", name),
        }
    }
    for (name, new) in after.iter().filter(|(name, _)| !before.contains_key(*name)) {
        line(b"-", new, name);
    }
    if lines.is_empty() {
        return Ok(());
    }
    let flags = OFlag::O_WRONLY | OFlag::O_APPEND | OFlag::O_CREAT | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
    let fd = openat(repo.handle(), PUSH_LOG, flags, Mode::from_bits_truncate(0o640)).map_err(|e| e.to_string())?;
    // One write, so lines from simultaneous pushes don't interleave mid-line.
    fs::File::from(fd).write_all(&lines).map_err(|e| e.to_string())
}

/// Point HEAD at a pushed branch when its current target does not exist. Branch names are
/// bytes (one per line; a ref can't contain a newline), so names with spaces, non-breaking
/// spaces or non-UTF-8 bytes are passed to git exactly as they are.
fn fix_head(repo: &RepoDir) -> Result<(), String> {
    if git(repo, &["rev-parse", "--verify", "--quiet", "HEAD"]).is_ok() {
        return Ok(());
    }
    let out = git(repo, &["for-each-ref", "--format=%(refname)", "refs/heads"])?;
    let heads: Vec<&[u8]> = out.split(|b| *b == b'\n').filter(|h| !h.is_empty()).collect();
    let Some(first) = heads.first() else { return Ok(()) };
    let preferred: [&[u8]; 2] = [b"refs/heads/main", b"refs/heads/master"];
    let choice = preferred.into_iter().find(|r| heads.contains(r)).unwrap_or(first);
    let status = git_command(repo)
        .args([OsStr::new("symbolic-ref"), OsStr::new("HEAD"), OsStr::from_bytes(choice)])
        .status()
        .map_err(|e| e.to_string())?;
    if !status.success() {
        return Err("could not set the default branch".into());
    }
    let name = String::from_utf8_lossy(&choice[b"refs/heads/".len()..]).into_owned();
    eprintln!("gitv: default branch is now {name}");
    Ok(())
}

fn run() -> Result<u8, String> {
    let cli = Cli::parse();
    if let Err(error) = config::load() {
        if matches!(cli.action, Action::Serve { .. }) {
            // A key holder needn't see the server's paths; the operator does.
            log_operator(&format!("bad configuration: {error}"));
            return Err("the server is misconfigured; its operator can see why".into());
        }
        return Err(error);
    }
    if let Action::Serve { owner } = &cli.action {
        return serve(owner, &std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default());
    }
    // Locally (GITV_REPOS set) administration runs as yourself.
    if !is_root() && !gitv_core::is_local() {
        return Err("run repository and key administration as root".into());
    }
    match cli.action {
        Action::Create { owner, name } => {
            // An administrator sees everything.
            let created = create(&owner, &name).map_err(|e| e.detail())?;
            println!("git@{}:{owner}/{name}.git", config::host());
            if let Some(leftover) = created.leftover {
                eprintln!("gitv: created {owner}/{name}.git, but {leftover}");
            }
        }
        Action::Delete { owner, name, yes } => {
            if !yes {
                return Err(format!(
                    "this moves {owner}/{name}.git to the trash for {TRASH_DAYS} days; pass --yes to confirm"
                ));
            }
            let entry = delete(&owner, &name)?;
            println!("moved {owner}/{name}.git to {owner}/{TRASH}/{entry}; restore with: gitv restore {owner} {entry}");
        }
        Action::Trash => list_trash()?,
        Action::Restore { owner, entry, as_name } => restore(&owner, &entry, as_name.as_deref())?,
        Action::Purge { older_than_days } => purge(older_than_days)?,
        Action::Import { owner, name, source } => import(&owner, &name, &source)?,
        Action::Visibility { owner, name, visibility: value } => visibility(&owner, &name, &value)?,
        Action::Protect { owner, name, value } => protect(&owner, &name, value.as_deref())?,
        Action::Description { owner, name, text } => description(&owner, &name, text.as_deref())?,
        Action::DefaultBranch { owner, name, branch } => default_branch(&owner, &name, branch.as_deref())?,
        Action::AddKey { owner, public_key, label } => add_key(&owner, &public_key, label.as_deref())?,
        Action::Keys { owner } => list_keys(owner.as_deref())?,
        Action::RemoveKey { fingerprint } => remove_key(&fingerprint)?,
        Action::Serve { .. } => unreachable!(),
    }
    Ok(0)
}

fn main() -> ExitCode {
    match run() {
        Ok(code) => ExitCode::from(code),
        Err(error) => {
            eprintln!("gitv: {error}");
            ExitCode::FAILURE
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use nix::fcntl::{OFlag, open};
    use std::os::unix::fs::PermissionsExt;

    /// A fresh, empty directory for one test.
    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("gitv-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn open_path(path: &Path) -> OwnedFd {
        open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).unwrap()
    }

    #[test]
    fn published_files_are_relabelled_only_where_selinux_is_on() {
        let dir = scratch("relabel");
        fs::create_dir_all(dir.join("selinuxfs")).unwrap();
        let keys = dir.join("authorized_keys");
        fs::write(&keys, "").unwrap();
        // A stand-in restorecon that records what it was asked to relabel.
        let record = dir.join("relabelled");
        let fake = dir.join("restorecon");
        fs::write(&fake, format!("#!/bin/sh\necho \"$1\" >> '{}'\n", record.display())).unwrap();
        fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap();

        relabel(&keys, &dir.join("selinuxfs"), &fake).unwrap();
        assert!(!record.exists(), "SELinux is off (no enforce file): nothing to do");
        relabel(&keys, &dir.join("selinuxfs"), &dir.join("missing")).unwrap();

        fs::write(dir.join("selinuxfs/enforce"), "1").unwrap();
        relabel(&keys, &dir.join("selinuxfs"), &fake).unwrap();
        assert_eq!(fs::read_to_string(&record).unwrap().trim(), keys.to_str().unwrap());

        fs::write(&fake, "#!/bin/sh\nexit 1\n").unwrap();
        let error = relabel(&keys, &dir.join("selinuxfs"), &fake).unwrap_err();
        assert!(error.contains("run: restorecon"), "{error}");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn creation_errors_keep_their_leftovers() {
        let leftover = || "couldn't remove the staging directory /x".to_string();
        assert_eq!(CreateError::EXISTS.detail(), "repository already exists");
        assert_eq!(
            CreateError::EXISTS.with_leftover(leftover()).detail(),
            "repository already exists; also couldn't remove the staging directory /x"
        );
        assert_eq!(
            CreateError::Failed("git init failed".into()).with_leftover(leftover()).detail(),
            "git init failed; also couldn't remove the staging directory /x"
        );
        // Still "exists" for the callers that treat it specially.
        assert!(matches!(CreateError::EXISTS.with_leftover(leftover()), CreateError::Exists { .. }));
    }

    #[test]
    fn private_commands_keep_their_errors_for_the_operator() {
        let mut command = gitv_core::git_base();
        command.args(["init", "--no-such-option"]);
        let error = run_privately(command, "git init").unwrap_err();
        assert!(error.starts_with("git init failed (exit status: 129): "), "{error}");
        assert!(error.contains("no-such-option"), "git's own message is captured: {error}");
    }

    #[test]
    fn a_log_file_that_cannot_be_written_is_reported() {
        let missing = std::env::temp_dir().join(format!("gitv-no-such-dir-{}/log", std::process::id()));
        assert!(append_line(&missing, "x").is_err(), "a failed write must not count as logged");
        let file = std::env::temp_dir().join(format!("gitv-log-{}", std::process::id()));
        let _ = fs::remove_file(&file);
        append_line(&file, "one").unwrap();
        append_line(&file, "two").unwrap();
        assert_eq!(fs::read_to_string(&file).unwrap(), "one\ntwo\n");
        let _ = fs::remove_file(&file);
    }

    #[test]
    fn a_failed_build_never_removes_what_it_did_not_make() {
        let dir = scratch("build");
        // A staging directory that already holds someone's `repo`, as it would if the staging
        // name had been swapped for another private directory before it was opened.
        fs::create_dir_all(dir.join("owner/.staging/repo")).unwrap();
        fs::write(dir.join("owner/.staging/repo/sentinel"), "precious").unwrap();
        let owner = open_path(&dir.join("owner"));
        let staging = open_path(&dir.join("owner/.staging"));
        let result = build_and_publish(&owner, &staging, "new.git", Contents::Empty);
        assert!(result.is_err(), "building over an existing repo succeeded");
        assert_eq!(fs::read_to_string(dir.join("owner/.staging/repo/sentinel")).unwrap(), "precious");
        assert!(!dir.join("owner/new.git").exists(), "nothing was published");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_failed_build_cleans_up_what_it_made() {
        let dir = scratch("build-clean");
        fs::create_dir_all(dir.join("owner/.staging")).unwrap();
        // The target is taken, so publication fails after the repository was built.
        fs::create_dir_all(dir.join("owner/new.git")).unwrap();
        let owner = open_path(&dir.join("owner"));
        let staging = open_path(&dir.join("owner/.staging"));
        let error = build_and_publish(&owner, &staging, "new.git", Contents::Empty)
            .err()
            .map(|e| e.detail())
            .unwrap_or_default();
        assert!(error.contains("already exists"), "{error}");
        assert!(fs::read_dir(dir.join("owner/.staging")).unwrap().next().is_none(), "the half-built repo is gone");
        assert!(fs::read_dir(dir.join("owner/new.git")).unwrap().next().is_none(), "the target is untouched");
        let _ = fs::remove_dir_all(&dir);
    }
}