GITv
master
lib.rs827 lines, 35.9 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
//! Shared pieces of GITv: configuration, name rules and read-only git access.

pub mod config;

use std::ffi::{OsStr, OsString};
use std::io::Read;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use nix::dir::Dir;
use nix::fcntl::{AtFlags, OFlag, open, openat};
use nix::sys::stat::{Mode, SFlag, fstatat};
use nix::sys::wait::{Id, WaitPidFlag, waitid};
use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, fchownat, unlinkat};

/// Where bare repositories live: `<root>/<owner>/<name>.git`. `GITV_REPOS` overrides it for local runs.
pub fn repos_root() -> PathBuf {
    std::env::var_os("GITV_REPOS").map_or_else(|| PathBuf::from("/srv/gitv/repos"), PathBuf::from)
}

/// The OpenSSH authorized_keys file that maps each key to an owner. `GITV_KEYS` overrides it.
pub fn keys_path() -> PathBuf {
    std::env::var_os("GITV_KEYS").map_or_else(|| PathBuf::from("/etc/gitv/authorized_keys"), PathBuf::from)
}

/// True when running against a local tree instead of the server's real paths.
pub fn is_local() -> bool {
    std::env::var_os("GITV_REPOS").is_some()
}

/// Owner and repository names: 1–63 of `[a-z0-9_-]`, starting with a letter or digit.
pub fn valid_name(value: &str) -> bool {
    let bytes = value.as_bytes();
    (1..=63).contains(&bytes.len())
        && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
        && bytes.iter().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-')
}

pub const NAME_RULE: &str = "use 1–63 lowercase letters, digits, hyphens or underscores";

/// How long any one git command may run before it is killed.
pub const GIT_TIMEOUT: Duration = Duration::from_secs(15);

/// The most stdout any one git command may produce through [`git`].
pub const GIT_OUTPUT_LIMIT: usize = 64 << 20;

/// A `git` command with a minimal environment, so no user or system config (hooks templates,
/// aliases, pagers) leaks in, and with pathspecs taken literally rather than as globs or magic.
pub fn git_base() -> Command {
    let mut command = Command::new("git");
    configure(&mut command);
    command
}

/// Give any git program (`git`, or `git-receive-pack` run directly) the same clean environment
/// as [`git_base`]: no inherited variables, no user or system config, stdin closed until the
/// caller says otherwise.
pub fn configure(command: &mut Command) {
    command
        .env_clear()
        .env("PATH", "/usr/bin:/bin")
        .env("HOME", "/var/empty")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_LITERAL_PATHSPECS", "1")
        .env("LC_ALL", "C.UTF-8")
        .stdin(Stdio::null());
}

/// An open repository directory. Holding the directory itself, not its path, means a symlink
/// swapped in after the checks can't redirect anything: git runs inside this exact directory.
/// Git's file for a repository's one-line description, in the repository directory.
const DESCRIPTION: &str = "description";
/// The longest description, in characters.
pub const DESCRIPTION_LIMIT: usize = 160;

pub struct RepoDir {
    /// Where it was found, for messages and cache keys only; never reopened.
    pub path: PathBuf,
    fd: OwnedFd,
    deadline: Option<Instant>,
}

impl RepoDir {
    /// Open `path` as a repository directory. For tests and tools with a trusted path; serving
    /// code finds repositories through [`repo_dir`] or [`repo_in`].
    pub fn at(path: &Path) -> Option<RepoDir> {
        let fd = open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC | OFlag::O_NOFOLLOW, Mode::empty()).ok()?;
        Some(RepoDir { path: path.to_path_buf(), fd, deadline: None })
    }

    pub fn limit_until(&mut self, deadline: Instant) {
        self.deadline = Some(deadline);
    }

    /// A command that starts inside this directory, whatever happens to its path meanwhile.
    pub fn command(&self, program: &str) -> Command {
        command_in(&self.fd, program)
    }

    pub fn is_public(&self) -> bool {
        self.has_marker("gitv-public")
    }

    pub fn set_public(&self, public: bool) -> nix::Result<()> {
        self.set_marker("gitv-public", public)
    }

    /// Whether pushes may only move branches forwards and never delete them (`gitv protect`).
    pub fn is_protected(&self) -> bool {
        self.has_marker("gitv-protected")
    }

    pub fn set_protected(&self, protected: bool) -> nix::Result<()> {
        self.set_marker("gitv-protected", protected)
    }

    /// A setting kept as an empty file in the repository directory: present (and a regular
    /// file) means on. Backups and restores carry it with the repository.
    fn has_marker(&self, marker: &str) -> bool {
        matches!(try_kind_at(&self.fd, OsStr::new(marker)), Ok(Some(SFlag::S_IFREG)))
    }

    fn set_marker(&self, marker: &str, on: bool) -> nix::Result<()> {
        if on {
            match openat(
                &self.fd,
                marker,
                OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_EXCL | OFlag::O_CLOEXEC,
                Mode::S_IRUSR,
            ) {
                Ok(_) => Ok(()),
                Err(nix::errno::Errno::EEXIST) if self.has_marker(marker) => Ok(()),
                Err(error) => Err(error),
            }
        } else {
            match unlinkat(&self.fd, marker, UnlinkatFlags::NoRemoveDir) {
                Err(nix::errno::Errno::ENOENT) => Ok(()),
                result => result,
            }
        }
    }

    /// The open directory, for reading it by handle.
    /// The repository's one-line description from git's `description` file, or `None` when
    /// there's none or it still holds the placeholder `git init` writes.
    pub fn description(&self) -> Option<String> {
        // Non-blocking, so a FIFO planted at the name can't hang the reader; then only a
        // regular file is read, and only its first kilobyte.
        let flags = OFlag::O_RDONLY | OFlag::O_NOFOLLOW | OFlag::O_NONBLOCK | OFlag::O_CLOEXEC;
        let fd = openat(&self.fd, DESCRIPTION, flags, Mode::empty()).ok()?;
        let meta = nix::sys::stat::fstat(&fd).ok()?;
        if SFlag::from_bits_truncate(meta.st_mode) & SFlag::S_IFMT != SFlag::S_IFREG {
            return None;
        }
        let mut bytes = Vec::new();
        std::fs::File::from(fd).take(DESCRIPTION_LIMIT as u64 * 4).read_to_end(&mut bytes).ok()?;
        let text = String::from_utf8_lossy(&bytes);
        let line = text.lines().next().unwrap_or_default().trim();
        let placeholder = line.starts_with("Unnamed repository");
        (!line.is_empty() && !placeholder).then(|| line.chars().filter(|c| !c.is_control()).collect())
    }

    /// Replace the description, or remove it with `None`. The new file is written beside the old
    /// one and renamed over it inside this open directory, so a reader sees one or the other.
    pub fn set_description(&self, text: Option<&str>) -> nix::Result<()> {
        use std::io::Write as _;
        let Some(text) = text else {
            return match unlinkat(&self.fd, DESCRIPTION, UnlinkatFlags::NoRemoveDir) {
                Err(nix::errno::Errno::ENOENT) => Ok(()),
                result => result,
            };
        };
        let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
        let temporary = format!(".{DESCRIPTION}.tmp-{}-{nanos}", std::process::id());
        let flags = OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_EXCL | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
        let fd = openat(&self.fd, temporary.as_str(), flags, Mode::from_bits_truncate(0o644))?;
        let written = (|| {
            // Created with the umask applied; readers (the web service) need it world-readable.
            nix::sys::stat::fchmod(&fd, Mode::from_bits_truncate(0o644))?;
            let mut file = std::fs::File::from(fd);
            let io = |e: std::io::Error| e.raw_os_error().map_or(nix::errno::Errno::EIO, nix::errno::Errno::from_raw);
            file.write_all(format!("{text}\n").as_bytes()).map_err(io)?;
            file.sync_all().map_err(io)?;
            nix::fcntl::renameat(&self.fd, temporary.as_str(), &self.fd, DESCRIPTION)
        })();
        if written.is_err() {
            let _ = unlinkat(&self.fd, temporary.as_str(), UnlinkatFlags::NoRemoveDir);
        }
        written
    }

    pub fn handle(&self) -> BorrowedFd<'_> {
        self.fd.as_fd()
    }

    /// Lock the repository directory itself, waiting for any conflicting holder. Pushes hold it
    /// shared; a backup holds it exclusive (`flock -x <repo>`) so it never copies a push half
    /// written. Released when the returned lock is dropped.
    pub fn lock(&self, exclusive: bool) -> nix::Result<nix::fcntl::Flock<OwnedFd>> {
        let fd = self.fd.try_clone().map_err(|e| nix::errno::Errno::from_raw(e.raw_os_error().unwrap_or(0)))?;
        let kind = if exclusive { nix::fcntl::FlockArg::LockExclusive } else { nix::fcntl::FlockArg::LockShared };
        nix::fcntl::Flock::lock(fd, kind).map_err(|(_, e)| e)
    }
}

/// A command that starts inside the open directory `dir`. The command owns its own duplicate
/// of the descriptor, so it stays valid however long the command outlives the caller's handle.
pub fn command_in(dir: &OwnedFd, program: &str) -> Command {
    let mut command = Command::new(program);
    // Everything that can fail or allocate happens here, in the parent. The child, between
    // fork and exec in a multithreaded process, only calls fchdir and builds errors from raw
    // error numbers, neither of which allocates.
    let fd = dir.try_clone().map_err(|e| e.raw_os_error().unwrap_or(nix::libc::EBADF));
    // SAFETY: fchdir is async-signal-safe, and from_raw_os_error doesn't allocate.
    unsafe {
        command.pre_exec(move || match &fd {
            Ok(fd) if nix::libc::fchdir(fd.as_raw_fd()) == 0 => Ok(()),
            Ok(_) => Err(std::io::Error::last_os_error()),
            Err(code) => Err(std::io::Error::from_raw_os_error(*code)),
        });
    }
    command
}

/// [`git_base`] run inside an open directory, without pointing it at a repository: for `git
/// init` in a directory being built.
pub fn git_in(dir: &OwnedFd) -> Command {
    let mut command = command_in(dir, "git");
    configure(&mut command);
    command
}

/// [`git_base`] run inside an open repository.
pub fn git_command(dir: &RepoDir) -> Command {
    let mut command = dir.command("git");
    configure(&mut command);
    command.args(["-c", "safe.directory=*", "-c", "core.quotePath=false", "--git-dir=."]);
    command
}

/// Run a read-only git command and return its stdout. The command is killed if it runs longer
/// than [`GIT_TIMEOUT`]; output beyond [`GIT_OUTPUT_LIMIT`] is an error.
pub fn git<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S]) -> Result<Vec<u8>, String> {
    match git_capped(git_dir, args, GIT_OUTPUT_LIMIT)? {
        (output, false) => Ok(output),
        (_, true) => Err("git output too large".into()),
    }
}

/// Like [`git`], with `input` written to the command's stdin, as for `cat-file --batch-check`.
pub fn git_with_input<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], input: &[u8]) -> Result<Vec<u8>, String> {
    match run_git(git_dir, args, Some(input), GIT_OUTPUT_LIMIT, GIT_TIMEOUT)? {
        (output, false) => Ok(output),
        (_, true) => Err("git output too large".into()),
    }
}

/// Like [`git`], but output beyond `cap` bytes stops the command and comes back truncated, with
/// `true` to say so, rather than as an error.
pub fn git_capped<S: AsRef<OsStr>>(git_dir: &RepoDir, args: &[S], cap: usize) -> Result<(Vec<u8>, bool), String> {
    git_capped_for(git_dir, args, cap, GIT_TIMEOUT)
}

/// Apply a shorter budget to optional work while respecting the overall page deadline.
pub fn git_capped_for<S: AsRef<OsStr>>(
    git_dir: &RepoDir,
    args: &[S],
    cap: usize,
    timeout: Duration,
) -> Result<(Vec<u8>, bool), String> {
    run_git(git_dir, args, None, cap, timeout)
}

fn run_git<S: AsRef<OsStr>>(
    git_dir: &RepoDir,
    args: &[S],
    input: Option<&[u8]>,
    cap: usize,
    timeout: Duration,
) -> Result<(Vec<u8>, bool), String> {
    let deadline = Instant::now() + timeout.min(GIT_TIMEOUT);
    let deadline = git_dir.deadline.map_or(deadline, |limit| limit.min(deadline));
    if Instant::now() >= deadline {
        return Err("page time budget exhausted".into());
    }
    let mut command = git_command(git_dir);
    command.args(args).stdout(Stdio::piped()).stderr(Stdio::null());
    if input.is_some() {
        command.stdin(Stdio::piped());
    }
    let mut child = command.spawn().map_err(|e| format!("cannot run git: {e}"))?;
    let mut stdout = child.stdout.take().ok_or("git has no stdout")?;
    // Written from its own thread, so git can't block on a full stdout while we block on a full
    // stdin. A killed git fails the write (SIGPIPE is ignored in Rust programs), ending the thread.
    let writer = match (input, child.stdin.take()) {
        (Some(input), Some(mut stdin)) => {
            let input = input.to_vec();
            Some(thread::spawn(move || {
                let _ = std::io::Write::write_all(&mut stdin, &input);
            }))
        }
        _ => None,
    };
    let pid = nix::unistd::Pid::from_raw(i32::try_from(child.id()).map_err(|_| "git has no pid")?);
    let child = Arc::new(Mutex::new(child));
    let kill = |child: &Mutex<Child>| {
        // The child is never reaped while the lock is held, so this can't hit a reused pid.
        if let Ok(mut child) = child.lock() {
            let _ = child.kill();
        }
    };
    // The watchdog covers a read that blocks; nobody holds the lock while blocked.
    let (finished, wait) = mpsc::channel::<()>();
    let watchdog = {
        let child = Arc::clone(&child);
        thread::spawn(move || {
            if let Err(RecvTimeoutError::Timeout) =
                wait.recv_timeout(deadline.saturating_duration_since(Instant::now()))
            {
                kill(&child);
            }
        })
    };
    let mut output = Vec::new();
    let read = (&mut stdout).take(cap as u64 + 1).read_to_end(&mut output);
    let overflow = output.len() > cap;
    if overflow {
        output.truncate(cap);
        kill(&child);
    }
    drop(stdout);
    // Wait for git to exit without reaping it (WNOWAIT), holding no lock, so the watchdog can
    // still kill it if it closed its output but kept running. Until it is reaped its pid can't
    // be reused, so that kill can never reach another process. Then reap it at once.
    let status = loop {
        match waitid(Id::Pid(pid), WaitPidFlag::WEXITED | WaitPidFlag::WNOWAIT) {
            Ok(_) => {
                break child.lock().map_err(|_| "git watchdog failed")?.wait().map_err(|e| format!("git failed: {e}"));
            }
            Err(nix::errno::Errno::EINTR) => continue,
            Err(e) => break Err(format!("git failed: {e}")),
        }
    };
    let _ = finished.send(());
    let _ = watchdog.join();
    if let Some(writer) = writer {
        let _ = writer.join();
    }
    read.map_err(|e| format!("cannot read git output: {e}"))?;
    let status = status?;
    if overflow {
        Ok((output, true))
    } else if status.success() {
        Ok((output, false))
    } else {
        Err(format!("git failed ({status})"))
    }
}

/// A client's requested git protocol (`version=2`, say), when it is well formed, to pass on as
/// `GIT_PROTOCOL`, as sshd and `git http-backend` do. Anything else is ignored.
pub fn git_protocol(value: &str) -> Option<&str> {
    (value.len() <= 64 && value.bytes().all(|b| b.is_ascii_alphanumeric() || b"=:.".contains(&b))).then_some(value)
}

/// Seconds since the Unix epoch, or 0 if the clock is set before it.
pub fn unix_now() -> u64 {
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs())
}

/// Make a rename or new file in `path`'s directory durable: until the directory itself is
/// synced, a crash can leave the old name, or none, in place of what was just published.
pub fn sync_directory_of(path: &Path) -> std::io::Result<()> {
    let directory = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
    std::fs::File::open(directory)?.sync_all()
}

/// Why [`publish_file`] failed. Nothing was published in any case but a failed final sync.
#[derive(Debug)]
pub enum PublishError<E> {
    /// Asked not to replace, and something is already at the path.
    Exists,
    /// Writing, renaming or syncing failed.
    Io(std::io::Error),
    /// The caller's `prepare` step failed.
    Prepare(E),
}

impl<E: std::fmt::Display> std::fmt::Display for PublishError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PublishError::Exists => write!(f, "it already exists"),
            PublishError::Io(e) => write!(f, "{e}"),
            PublishError::Prepare(e) => write!(f, "{e}"),
        }
    }
}

/// Publish `contents` at `path` in one step, so readers see the old file or the new one, never
/// part of either, and a crash leaves one of them in place.
///
/// The contents go to a fresh hidden file beside `path`, under a name no other writer uses,
/// created exclusively (never an existing file opened and truncated) with permissions `mode`
/// (applied after creation, so the umask doesn't narrow them). `prepare` then sees the
/// finished file, to change its ownership say, before it is synced and renamed into place,
/// replacing what's there only if `replace` is set. The directory is synced last, so the
/// rename survives a crash. On any failure before the rename the hidden file is removed.
///
/// # Errors
/// [`PublishError::Exists`] if `replace` is unset and `path` exists; [`PublishError::Prepare`]
/// with `prepare`'s own error; otherwise [`PublishError::Io`].
pub fn publish_file<E>(
    path: &Path,
    contents: &[u8],
    mode: u32,
    replace: bool,
    prepare: impl FnOnce(&std::fs::File) -> Result<(), E>,
) -> Result<(), PublishError<E>> {
    use std::io::Write as _;
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    use std::sync::atomic::{AtomicU64, Ordering};
    static WRITES: AtomicU64 = AtomicU64::new(0);

    let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
    let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.subsec_nanos());
    let serial = WRITES.fetch_add(1, Ordering::Relaxed);
    let temporary = path.with_file_name(format!(".{name}.tmp-{}-{nanos}-{serial}", std::process::id()));
    let mut file =
        std::fs::File::options().write(true).create_new(true).mode(mode).open(&temporary).map_err(PublishError::Io)?;
    let published = (|| {
        file.write_all(contents).map_err(PublishError::Io)?;
        file.set_permissions(std::fs::Permissions::from_mode(mode)).map_err(PublishError::Io)?;
        prepare(&file).map_err(PublishError::Prepare)?;
        file.sync_all().map_err(PublishError::Io)?;
        let flags = if replace { nix::fcntl::RenameFlags::empty() } else { nix::fcntl::RenameFlags::RENAME_NOREPLACE };
        nix::fcntl::renameat2(nix::fcntl::AT_FDCWD, &temporary, nix::fcntl::AT_FDCWD, path, flags).map_err(
            |e| match e {
                nix::errno::Errno::EEXIST => PublishError::Exists,
                e => PublishError::Io(e.into()),
            },
        )
    })();
    if published.is_err() {
        let _ = std::fs::remove_file(&temporary);
        return published;
    }
    sync_directory_of(path).map_err(PublishError::Io)
}

/// Decode `%XX` escapes to raw bytes, as in a URL path or a Markdown link destination. `+`
/// stays a plus (only query strings use it for a space). A malformed escape is kept as written.
pub fn percent_decode(text: &str) -> Vec<u8> {
    let bytes = text.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let hex = |b: u8| (b as char).to_digit(16);
        match bytes[i] {
            b'%' if i + 2 < bytes.len() => match (hex(bytes[i + 1]), hex(bytes[i + 2])) {
                (Some(high), Some(low)) => {
                    out.push((high * 16 + low) as u8);
                    i += 2;
                }
                _ => out.push(b'%'),
            },
            byte => out.push(byte),
        }
        i += 1;
    }
    out
}

// ---------------------------------------------------------------------------------------------
// Working through directory handles
//
// Everything that creates, removes or changes repositories, or decides which ones exist, works
// through open directory handles and never follows a symlink, so a path swapped after a check
// can't redirect it.

const DIR_FLAGS: OFlag = OFlag::O_DIRECTORY.union(OFlag::O_CLOEXEC).union(OFlag::O_NOFOLLOW);

/// The repository root. Its own path is trusted configuration, so it is opened normally.
pub fn open_root() -> Option<OwnedFd> {
    open(&repos_root(), OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).ok()
}

/// The directory at `path`, refused if its last part is a symlink or not a directory, to work
/// inside by handle.
///
/// # Errors
/// The open's failure: `ELOOP` for a symlink, `ENOTDIR` for anything else that isn't a folder.
pub fn open_dir(path: &Path) -> std::io::Result<OwnedFd> {
    Ok(open(path, DIR_FLAGS, Mode::empty())?)
}

/// The directory `name` inside `dir`; refused if it is a symlink or not a directory.
pub fn open_dir_at(dir: &impl AsFd, name: &OsStr) -> nix::Result<OwnedFd> {
    openat(dir, name, DIR_FLAGS, Mode::empty())
}

/// What kind of entry `name` is inside `dir`, without following a symlink; `None` if absent
/// or if it can't be inspected. For display and quick checks; anything that must not skip an
/// entry silently uses [`try_kind_at`].
pub fn kind_at(dir: &impl AsFd, name: &OsStr) -> Option<SFlag> {
    try_kind_at(dir, name).ok().flatten()
}

/// What kind of entry `name` is inside `dir`: `Ok(None)` only when it's absent, and the error
/// when it exists but can't be inspected (no search permission, I/O error, ...).
pub fn try_kind_at(dir: &impl AsFd, name: &OsStr) -> nix::Result<Option<SFlag>> {
    match fstatat(dir, name, AtFlags::AT_SYMLINK_NOFOLLOW) {
        Ok(stat) => Ok(Some(SFlag::from_bits_truncate(stat.st_mode) & SFlag::S_IFMT)),
        Err(nix::errno::Errno::ENOENT) => Ok(None),
        Err(e) => Err(e),
    }
}

/// The names in an open directory, without `.` and `..`. Reads through a fresh open of the
/// same directory, so the caller's handle keeps its own position.
///
/// For display only: a directory that can't be read lists as empty. Anything that changes the
/// tree uses [`try_entries`], which reports the failure instead.
pub fn entries(dir: &impl AsFd) -> Vec<OsString> {
    try_entries(dir).unwrap_or_default()
}

/// The names in an open directory, or the error that stopped the listing part way.
pub fn try_entries(dir: &impl AsFd) -> nix::Result<Vec<OsString>> {
    list_entries(dir, false)
}

/// List only child directories, using directory-entry types when the filesystem supplies them.
pub fn try_subdirs(dir: &impl AsFd) -> nix::Result<Vec<OsString>> {
    list_entries(dir, true)
}

fn list_entries(dir: &impl AsFd, directories_only: bool) -> nix::Result<Vec<OsString>> {
    let fresh = openat(dir, ".", OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty())?;
    let mut listing = Dir::from_fd(fresh)?;
    let mut names = Vec::new();
    for entry in listing.iter() {
        let entry = entry?;
        let name = OsStr::from_bytes(entry.file_name().to_bytes());
        if name == "." || name == ".." {
            continue;
        }
        if directories_only {
            match entry.file_type() {
                Some(nix::dir::Type::Directory) => {}
                None if try_kind_at(dir, name)? == Some(SFlag::S_IFDIR) => {}
                _ => continue,
            }
        }
        names.push(name.to_owned());
    }
    Ok(names)
}

/// Remove `name` from `dir` and, if it is a directory, everything inside it, working through
/// handles all the way down. A symlink is removed itself, never followed.
pub fn remove_tree_at(dir: &impl AsFd, name: &OsStr) -> nix::Result<()> {
    if try_kind_at(dir, name)? == Some(SFlag::S_IFDIR) {
        let inner = open_dir_at(dir, name)?;
        for entry in try_entries(&inner)? {
            remove_tree_at(&inner, &entry)?;
        }
        unlinkat(dir, name, UnlinkatFlags::RemoveDir)
    } else {
        unlinkat(dir, name, UnlinkatFlags::NoRemoveDir)
    }
}

/// Give the open directory `dir` and everything under it to `uid` and `gid`, working through
/// handles and changing symlinks themselves rather than what they point at. Any entry it can't
/// read or change is an error, never a silent skip.
pub fn chown_tree(dir: &OwnedFd, uid: Uid, gid: Gid) -> nix::Result<()> {
    fchown(dir, Some(uid), Some(gid))?;
    for entry in try_entries(dir)? {
        if try_kind_at(dir, &entry)? == Some(SFlag::S_IFDIR) {
            chown_tree(&open_dir_at(dir, &entry)?, uid, gid)?;
        } else {
            fchownat(dir, entry.as_os_str(), Some(uid), Some(gid), AtFlags::AT_SYMLINK_NOFOLLOW)?;
        }
    }
    Ok(())
}

/// The owner's directory, opened with symlinks refused.
pub fn open_owner(owner: &str) -> Option<OwnedFd> {
    if !valid_name(owner) {
        return None;
    }
    open_dir_at(&open_root()?, OsStr::new(owner)).ok()
}

/// An existing repository, `<owner>/<name>.git`, opened through the owner's open directory:
/// a real directory (not a symlink) holding a real `HEAD` file. Everything after this works
/// through the open directory, so there is no window between checking and using it.
pub fn repo_in(owner_dir: &impl AsFd, owner: &str, name: &str) -> Option<RepoDir> {
    if !(valid_name(owner) && valid_name(name)) {
        return None;
    }
    let file = format!("{name}.git");
    let fd = open_dir_at(owner_dir, OsStr::new(&file)).ok()?;
    if kind_at(&fd, OsStr::new("HEAD")) != Some(SFlag::S_IFREG) {
        return None;
    }
    Some(RepoDir { path: repos_root().join(owner).join(file), fd, deadline: None })
}

/// [`repo_in`], opening the owner's directory first.
pub fn repo_dir(owner: &str, name: &str) -> Option<RepoDir> {
    repo_in(&open_owner(owner)?, owner, name)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    /// A bare repository holding one blob of `size` bytes, and the blob's id.
    fn repo_with_blob(name: &str, size: usize) -> (RepoDir, String) {
        let dir = scratch(name);
        assert!(git_base().args(["init", "-q", "--bare"]).arg(&dir).status().unwrap().success());
        let dir = RepoDir::at(&dir).unwrap();
        let mut child = git_command(&dir)
            .args(["hash-object", "-w", "--stdin"])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        std::io::Write::write_all(&mut child.stdin.take().unwrap(), &vec![b'x'; size]).unwrap();
        let oid = String::from_utf8(child.wait_with_output().unwrap().stdout).unwrap().trim().to_string();
        (dir, oid)
    }

    #[test]
    fn git_commands_share_the_page_deadline_even_while_blocked_on_io() {
        let (mut dir, oid) = repo_with_blob("deadline", 10);
        let pipe = dir.path.join("pending-config");
        nix::unistd::mkfifo(&pipe, Mode::S_IRUSR | Mode::S_IWUSR).unwrap();
        // Holding both ends open keeps Git waiting for more bytes until its watchdog fires.
        let _writer = fs::OpenOptions::new().read(true).write(true).open(&pipe).unwrap();
        let deadline = Instant::now() + Duration::from_millis(250);
        dir.limit_until(deadline);
        let result = git(&dir, &["config", "--file", "pending-config", "--list"]);
        let finished = Instant::now();
        assert!(result.unwrap_err().contains("SIGKILL"), "the watchdog must kill the running Git command");
        assert!(finished >= deadline);
        assert!(finished.duration_since(deadline) < Duration::from_secs(5), "used the per-command timeout");
        // Even a fast command must be refused once the same page has spent its budget.
        assert_eq!(git(&dir, &["cat-file", "-s", &oid]).unwrap_err(), "page time budget exhausted");
        fs::remove_dir_all(&dir.path).unwrap();
    }

    #[test]
    fn published_files_replace_whole_or_not_at_all() {
        use std::os::unix::fs::PermissionsExt;
        let dir = scratch("publish");
        let path = dir.join("keys");
        let none = |_: &fs::File| Ok::<(), String>(());
        publish_file(&path, b"one\n", 0o644, true, none).unwrap();
        publish_file(&path, b"two\n", 0o644, true, none).unwrap();
        assert_eq!(fs::read(&path).unwrap(), b"two\n");
        assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644, "the umask didn't narrow it");
        // Not replacing: the existing file stays.
        assert!(matches!(publish_file(&path, b"three\n", 0o600, false, none), Err(PublishError::Exists)));
        // A failed preparation publishes nothing and says why.
        let refuse = |_: &fs::File| Err("not today".to_string());
        assert!(
            matches!(publish_file(&path, b"four\n", 0o600, true, refuse), Err(PublishError::Prepare(e)) if e == "not today")
        );
        assert_eq!(fs::read(&path).unwrap(), b"two\n");
        let names: Vec<_> = fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect();
        assert_eq!(names, ["keys"], "no hidden file was left behind");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn only_well_formed_protocol_requests_pass() {
        assert_eq!(git_protocol("version=2"), Some("version=2"));
        assert_eq!(git_protocol("version=2:value=1"), Some("version=2:value=1"));
        for bad in ["version=2\n", "a b", "x;rm", &"v".repeat(65)] {
            assert_eq!(git_protocol(bad), None, "{bad:?}");
        }
    }

    #[test]
    fn capped_output_stops_early_and_says_so() {
        let (dir, oid) = repo_with_blob("capped", 1 << 20);
        let (out, overflow) = git_capped(&dir, &["cat-file", "blob", &oid], 1000).unwrap();
        assert!(overflow);
        assert_eq!(out.len(), 1000);
        let (out, overflow) = git_capped(&dir, &["cat-file", "blob", &oid], 2 << 20).unwrap();
        assert!(!overflow);
        assert_eq!(out.len(), 1 << 20);
        assert!(git(&dir, &["cat-file", "blob", "0000000000000000000000000000000000000000"]).is_err());
        let _ = fs::remove_dir_all(&dir.path);
    }

    #[test]
    fn input_reaches_git_even_when_it_outgrows_a_pipe() {
        let (dir, oid) = repo_with_blob("input", 10);
        // Far more queries than a pipe buffers, so writing and reading must overlap.
        let queries = format!("{oid}\n").repeat(20_000);
        let out = git_with_input(&dir, &["cat-file", "--batch-check"], queries.as_bytes()).unwrap();
        assert_eq!(out, format!("{oid} blob 10\n").repeat(20_000).into_bytes());
        let _ = fs::remove_dir_all(&dir.path);
    }

    #[test]
    fn an_open_repository_stays_bound_to_its_directory() {
        // Open one repository, then swap another into its path: git must still see the first.
        let (dir, oid) = repo_with_blob("bound", 10);
        let (other, _) = repo_with_blob("bound-other", 20);
        let moved = dir.path.with_extension("moved");
        fs::rename(&dir.path, &moved).unwrap();
        std::os::unix::fs::symlink(&other.path, &dir.path).unwrap();
        assert_eq!(git(&dir, &["cat-file", "-s", &oid]).unwrap(), b"10\n");
        let _ = fs::remove_file(&dir.path);
        let _ = fs::remove_dir_all(&moved);
        let _ = fs::remove_dir_all(&other.path);
    }

    /// A scratch directory for one test.
    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("gitv-lib-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::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 handles_see_symlinks_as_symlinks() {
        let dir = scratch("kinds");
        std::fs::create_dir(dir.join("real")).unwrap();
        std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).unwrap();
        std::os::unix::fs::symlink(dir.join("missing"), dir.join("dangling")).unwrap();
        let fd = open_path(&dir);
        assert_eq!(kind_at(&fd, OsStr::new("real")), Some(SFlag::S_IFDIR));
        assert_eq!(kind_at(&fd, OsStr::new("link")), Some(SFlag::S_IFLNK));
        assert_eq!(kind_at(&fd, OsStr::new("dangling")), Some(SFlag::S_IFLNK));
        assert_eq!(kind_at(&fd, OsStr::new("absent")), None);
        assert!(open_dir_at(&fd, OsStr::new("link")).is_err(), "a symlinked directory isn't opened");
        let mut names = entries(&fd);
        names.sort();
        assert_eq!(names, ["dangling", "link", "real"]);
        assert_eq!(entries(&fd).len(), 3, "listing twice gives the same answer");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_directory_opened_by_path_is_never_a_symlink() {
        let dir = scratch("open-dir");
        std::fs::create_dir(dir.join("real")).unwrap();
        std::fs::write(dir.join("file"), "").unwrap();
        std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).unwrap();
        assert!(open_dir(&dir.join("real")).is_ok());
        assert!(open_dir(&dir.join("link")).is_err(), "a symlinked folder is refused");
        assert!(open_dir(&dir.join("file")).is_err(), "a file is refused");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn removing_a_tree_never_follows_symlinks() {
        let dir = scratch("remove");
        let outside = dir.join("outside");
        std::fs::create_dir(&outside).unwrap();
        std::fs::write(outside.join("keep.txt"), "keep").unwrap();
        std::fs::create_dir_all(dir.join("doomed/a/b")).unwrap();
        std::fs::write(dir.join("doomed/a/b/file"), "x").unwrap();
        std::os::unix::fs::symlink(&outside, dir.join("doomed/a/escape")).unwrap();
        std::os::unix::fs::symlink(outside.join("keep.txt"), dir.join("doomed/link-to-file")).unwrap();
        remove_tree_at(&open_path(&dir), OsStr::new("doomed")).unwrap();
        assert!(!dir.join("doomed").exists());
        assert_eq!(std::fs::read_to_string(outside.join("keep.txt")).unwrap(), "keep", "outside is untouched");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn walks_that_change_the_tree_fail_loudly() {
        if nix::unistd::geteuid().is_root() {
            return; // Root reads anything, so the unreadable directory below can't be made.
        }
        use std::os::unix::fs::PermissionsExt;
        let dir = scratch("loud");
        std::fs::create_dir(dir.join("sub")).unwrap();
        std::fs::write(dir.join("sub/file"), "x").unwrap();
        let sub = open_path(&dir.join("sub"));
        // Opened, then made unreadable: listing it now fails.
        std::fs::set_permissions(dir.join("sub"), std::fs::Permissions::from_mode(0o300)).unwrap();
        let (uid, gid) = (nix::unistd::getuid(), nix::unistd::getgid());
        assert!(try_entries(&sub).is_err());
        assert!(chown_tree(&sub, uid, gid).is_err(), "an incomplete ownership walk reported success");
        assert!(remove_tree_at(&open_path(&dir), OsStr::new("sub")).is_err());
        assert!(entries(&sub).is_empty(), "display listings stay forgiving");
        std::fs::set_permissions(dir.join("sub"), std::fs::Permissions::from_mode(0o755)).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_command_keeps_its_directory_after_the_handle_is_dropped() {
        let dir = scratch("command");
        let mut command = {
            let repo = RepoDir::at(&dir).unwrap();
            repo.command("pwd")
        };
        // Use up low descriptor numbers so a recycled number would point elsewhere.
        let _noise: Vec<OwnedFd> = (0..8).map(|_| open_path(&std::env::temp_dir())).collect();
        let out = command.output().unwrap();
        assert!(out.status.success());
        assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), dir.to_string_lossy());
        let _ = std::fs::remove_dir_all(&dir);
    }
}