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
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};
pub fn repos_root() -> PathBuf {
std::env::var_os("GITV_REPOS").map_or_else(|| PathBuf::from("/srv/gitv/repos"), PathBuf::from)
}
pub fn keys_path() -> PathBuf {
std::env::var_os("GITV_KEYS").map_or_else(|| PathBuf::from("/etc/gitv/authorized_keys"), PathBuf::from)
}
pub fn is_local() -> bool {
std::env::var_os("GITV_REPOS").is_some()
}
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";
pub const GIT_TIMEOUT: Duration = Duration::from_secs(15);
pub const GIT_OUTPUT_LIMIT: usize = 64 << 20;
pub fn git_base() -> Command {
let mut command = Command::new("git");
configure(&mut command);
command
}
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());
}
const DESCRIPTION: &str = "description";
pub const DESCRIPTION_LIMIT: usize = 160;
pub struct RepoDir {
pub path: PathBuf,
fd: OwnedFd,
deadline: Option<Instant>,
}
impl RepoDir {
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);
}
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)
}
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)
}
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,
}
}
}
pub fn description(&self) -> Option<String> {
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())
}
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 = (|| {
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()
}
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)
}
}
pub fn command_in(dir: &OwnedFd, program: &str) -> Command {
let mut command = Command::new(program);
let fd = dir.try_clone().map_err(|e| e.raw_os_error().unwrap_or(nix::libc::EBADF));
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
}
pub fn git_in(dir: &OwnedFd) -> Command {
let mut command = command_in(dir, "git");
configure(&mut command);
command
}
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
}
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()),
}
}
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()),
}
}
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)
}
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")?;
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>| {
if let Ok(mut child) = child.lock() {
let _ = child.kill();
}
};
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);
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})"))
}
}
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)
}
pub fn unix_now() -> u64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs())
}
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()
}
#[derive(Debug)]
pub enum PublishError<E> {
Exists,
Io(std::io::Error),
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}"),
}
}
}
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)
}
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
}
const DIR_FLAGS: OFlag = OFlag::O_DIRECTORY.union(OFlag::O_CLOEXEC).union(OFlag::O_NOFOLLOW);
pub fn open_root() -> Option<OwnedFd> {
open(&repos_root(), OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).ok()
}
pub fn open_dir(path: &Path) -> std::io::Result<OwnedFd> {
Ok(open(path, DIR_FLAGS, Mode::empty())?)
}
pub fn open_dir_at(dir: &impl AsFd, name: &OsStr) -> nix::Result<OwnedFd> {
openat(dir, name, DIR_FLAGS, Mode::empty())
}
pub fn kind_at(dir: &impl AsFd, name: &OsStr) -> Option<SFlag> {
try_kind_at(dir, name).ok().flatten()
}
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),
}
}
pub fn entries(dir: &impl AsFd) -> Vec<OsString> {
try_entries(dir).unwrap_or_default()
}
pub fn try_entries(dir: &impl AsFd) -> nix::Result<Vec<OsString>> {
list_entries(dir, false)
}
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)
}
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)
}
}
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(())
}
pub fn open_owner(owner: &str) -> Option<OwnedFd> {
if !valid_name(owner) {
return None;
}
open_dir_at(&open_root()?, OsStr::new(owner)).ok()
}
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 })
}
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;
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();
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");
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");
assert!(matches!(publish_file(&path, b"three\n", 0o600, false, none), Err(PublishError::Exists)));
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);
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() {
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);
}
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; }
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"));
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")
};
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);
}
}