gunk-dev/the-valley

bundle.go

source9b67d021e86fmain's published tip history
15.5 KiB
1package export
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "syscall"
15 "time"
16)
17
18// GitProgram is the git this package runs: git on PATH, unless a build
19// fixes it to an absolute path with
20// -ldflags "-X the-valley/web/export.GitProgram=<path>".
21var GitProgram = "git"
22
23// MainRef is the one ref a bundle carries, and the one a generation's
24// repository holds.
25const MainRef = "refs/heads/main"
26
27// maxBundleHeader is the most bytes of a bundle's header read: its version
28// line, capabilities, prerequisites and refs.
29const maxBundleHeader = 64 << 10
30
31// AcceptBundle checks the bundle at path and fetches it into repo, a fresh
32// bare repository it creates, in this order:
33//
34// 1. the bundle's header has no prerequisite, so the bundle is complete;
35// 2. it carries exactly one ref, refs/heads/main, at tip;
36// 3. git fetches it into the fresh repository with the explicit refspec
37// refs/heads/main:refs/heads/main, no tags, and
38// transfer.fsckObjects=true, so every object is checked as it is
39// indexed;
40// 4. the repository then holds refs/heads/main at tip, and no other ref;
41// 5. git writes the repository's commit-graph, so a reader walks main's
42// history, as merge-base and log do, without parsing each commit.
43//
44// A refused bundle leaves no repository behind. Every refusal is an
45// *Error with CodeBadBundle. Once ctx is done, git is stopped, and the
46// error is no refusal.
47func AcceptBundle(ctx context.Context, path, repo, tip string) error {
48 format, err := checkBundleHeader(path, tip)
49 if err != nil {
50 return err
51 }
52 // git fetches in repo, so the bundle is named from the root.
53 abs, err := filepath.Abs(path)
54 if err != nil {
55 return err
56 }
57 return fetchMain(ctx, abs, repo, tip, format)
58}
59
60// CarryRepo fetches main from from, a repository the receiver holds at tip,
61// into repo, a fresh bare repository, by the same fetch and checks a
62// bundle is fetched by. A new generation carries a project's repository
63// this way when its source tip has not moved, so the project's bundle need
64// not be sent again.
65func CarryRepo(ctx context.Context, from, repo, tip string) error {
66 format := "sha1"
67 if len(tip) == 64 {
68 format = "sha256"
69 }
70 abs, err := filepath.Abs(from)
71 if err != nil {
72 return err
73 }
74 return fetchMain(ctx, abs, repo, tip, format)
75}
76
77// checkBundleHeader reads the bundle's header, as gitformat-bundle defines
78// it, and holds it to steps 1 and 2. It returns the object format.
79func checkBundleHeader(path, tip string) (format string, err error) {
80 bad := func(format string, args ...any) error { return refuse(CodeBadBundle, format, args...) }
81 f, err := os.Open(path)
82 if err != nil {
83 return "", err
84 }
85 defer f.Close()
86 // The bound is on the file, not on the lines read from it, so a line
87 // with no end is never buffered past it.
88 r := bufio.NewReader(io.LimitReader(f, maxBundleHeader+1))
89 read := 0
90 line := func() (string, error) {
91 s, err := r.ReadString('\n')
92 read += len(s)
93 if read > maxBundleHeader {
94 return "", bad("the bundle's header is longer than %d bytes", maxBundleHeader)
95 }
96 if err != nil {
97 return "", bad("the bundle's header ends before its blank line")
98 }
99 return strings.TrimSuffix(s, "\n"), nil
100 }
101 version, err := line()
102 if err != nil {
103 return "", err
104 }
105 if version != "# v2 git bundle" && version != "# v3 git bundle" {
106 return "", bad("the bundle opens with %q, which is not a v2 or v3 bundle", version)
107 }
108 format = "sha1"
109 var refs []string
110 for {
111 s, err := line()
112 if err != nil {
113 return "", err
114 }
115 switch {
116 case s == "":
117 if len(refs) != 1 {
118 return "", bad("the bundle carries %d refs; it carries %s alone", len(refs), MainRef)
119 }
120 oid, name, _ := strings.Cut(refs[0], " ")
121 if name != MainRef {
122 return "", bad("the bundle carries %s; it carries %s alone", name, MainRef)
123 }
124 if oid != tip {
125 return "", bad("the bundle carries %s at %s; the manifest declares %s", MainRef, oid, tip)
126 }
127 if want := map[string]int{"sha1": 40, "sha256": 64}[format]; len(tip) != want {
128 return "", bad("the bundle is %s, and the tip %s is not a %s object ID", format, tip, format)
129 }
130 return format, nil
131 case strings.HasPrefix(s, "@"):
132 if version != "# v3 git bundle" {
133 return "", bad("a v2 bundle has no capability line, and this one has %q", s)
134 }
135 switch s {
136 case "@object-format=sha1":
137 format = "sha1"
138 case "@object-format=sha256":
139 format = "sha256"
140 default:
141 return "", bad("the bundle has the capability %q; a bundle is a full, unfiltered one", s)
142 }
143 case strings.HasPrefix(s, "-"):
144 return "", bad("the bundle has a prerequisite, %q; a bundle carries main's whole history", strings.TrimPrefix(s, "-"))
145 default:
146 oid, name, ok := strings.Cut(s, " ")
147 if !ok || !ValidObjectID(oid) || name == "" {
148 return "", bad("the bundle's header holds %q, which is not a ref line", s)
149 }
150 refs = append(refs, s)
151 }
152 }
153}
154
155// fetchMain makes repo a fresh bare repository holding refs/heads/main at
156// tip, fetched from source, and nothing else but main's commit-graph. It
157// removes repo again on any failure, until ctx is done: a fetch ctx stopped
158// may leave repo part way, for the caller to remove. A fetch ctx stopped
159// is no refusal of the bundle.
160func fetchMain(ctx context.Context, source, repo, tip, format string) (err error) {
161 if !ValidObjectID(tip) {
162 return refuse(CodeBadBundle, "%q is not an object ID", tip)
163 }
164 if _, err := os.Lstat(repo); !errors.Is(err, os.ErrNotExist) {
165 return fmt.Errorf("%s is not a fresh repository: it exists already", repo)
166 }
167 defer func() {
168 if err != nil {
169 removeAll(ctx, repo)
170 }
171 }()
172 if _, err := git(ctx, "", "init", "--quiet", "--bare", "--template=", "--initial-branch=main",
173 "--object-format="+format, repo); err != nil {
174 return err
175 }
176 if _, err := git(ctx, repo, "-c", "transfer.fsckObjects=true", "-c", "core.fsync=all",
177 "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--end-of-options",
178 source, MainRef+":"+MainRef); err != nil {
179 if ctx.Err() != nil {
180 return err
181 }
182 return refuse(CodeBadBundle, "%v", err)
183 }
184 refs, err := git(ctx, repo, "for-each-ref", "--format=%(objectname) %(refname)")
185 if err != nil {
186 return err
187 }
188 if got, want := strings.TrimSuffix(string(refs), "\n"), tip+" "+MainRef; got != want {
189 return refuse(CodeBadBundle, "the fetched repository holds %q, not %q", got, want)
190 }
191 _, err = git(ctx, repo, "-c", "core.fsync=all", "commit-graph", "write", "--reachable", "--no-progress")
192 return err
193}
194
195// Reachable reports whether each of commits is a commit that tip reaches
196// in repo. Browsing serves a commit only when it is: a bundle can carry
197// objects main does not reach, and those are never shown. An argument
198// that is not an object ID, an object repo does not hold, and an object
199// that is not a commit are all unreachable. So is an object ID of another
200// length than tip's: git reads 40 hex digits in a SHA-256 repository as
201// an abbreviation, and a commit is named by its full ID alone. Reachable
202// fails when it is given no commit.
203func Reachable(ctx context.Context, repo, tip string, commits ...string) (bool, error) {
204 if !ValidObjectID(tip) {
205 return false, fmt.Errorf("%q is not an object ID", tip)
206 }
207 if len(commits) == 0 {
208 return false, errors.New("no commit to check")
209 }
210 var stdin bytes.Buffer
211 for _, commit := range commits {
212 if !ValidObjectID(commit) || len(commit) != len(tip) {
213 return false, nil
214 }
215 stdin.WriteString(commit + "\n")
216 }
217 // --git-dir, as Git does, so git neither looks above repo nor holds
218 // a repository another user owns to safe.directory.
219 var out []byte
220 err := run(command(ctx, "", "--git-dir="+repo, "cat-file", "--batch-check=%(objecttype)"), "cat-file",
221 stdin.Bytes(), maxOutput, func(r io.Reader) (err error) {
222 out, err = io.ReadAll(r)
223 return err
224 })
225 if err != nil {
226 return false, err
227 }
228 types := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n")
229 if len(types) != len(commits) {
230 return false, fmt.Errorf("git cat-file gave %d types for %d objects", len(types), len(commits))
231 }
232 for _, t := range types {
233 if t != "commit" {
234 return false, nil
235 }
236 }
237 for _, commit := range commits {
238 cmd := command(ctx, "", "--git-dir="+repo, "merge-base", "--is-ancestor", commit, tip)
239 stderr := &head{max: maxStderr}
240 cmd.Stderr = stderr
241 err = cmd.Run()
242 var exit *exec.ExitError
243 switch {
244 case err == nil:
245 continue
246 case errors.As(err, &exit) && exit.ExitCode() == 1:
247 return false, nil
248 }
249 return false, fmt.Errorf("git merge-base: %w: %s", err, strings.TrimSpace(stderr.String()))
250 }
251 return true, nil
252}
253
254// ErrOutputLimit is the error of a git command that writes more output
255// than its caller set as the limit. git is stopped, and waited for, before
256// the error is returned.
257var ErrOutputLimit = errors.New("git wrote more than its output limit")
258
259// The bounds on what this package keeps of a git command's output.
260const (
261 // maxStderr is the most of git's standard error kept for an error's
262 // message. The rest is read and dropped.
263 maxStderr = 16 << 10
264 // maxOutput is the most standard output this package reads from a
265 // git command it runs for itself: a ref listing or an object's type.
266 maxOutput = 64 << 10
267)
268
269// Git runs git with args on the bare repository at repo and returns what
270// git prints, which may be at most limit bytes. It runs git the way this
271// package runs every git: replacement refs off, none of the caller's GIT_
272// variables, and no system or global configuration. --git-dir names the
273// repository, so git never reads a repository it finds above repo, and
274// reads one another user owns without holding it to safe.directory. When
275// git prints more than limit bytes, Git stops it and fails with
276// ErrOutputLimit. A server reads a generation's repositories with it, and
277// gives it object IDs it has checked, never a name a reader typed.
278func Git(ctx context.Context, repo string, limit int64, args ...string) ([]byte, error) {
279 var out []byte
280 err := GitStream(ctx, repo, limit, func(r io.Reader) (err error) {
281 out, err = io.ReadAll(r)
282 return err
283 }, args...)
284 return out, err
285}
286
287// GitStream runs git as Git does, and calls read with git's standard
288// output as git prints it. read may read at most limit bytes: a read past
289// them fails with ErrOutputLimit. read may also return before the output
290// ends, once it has what it needs. Once read returns, GitStream stops git
291// if it is still running, and waits for it to exit, so no git outlives the
292// call. GitStream returns read's error. When read succeeds, it returns
293// git's own failure only if read reached the end of the output: a git
294// stopped early is not held to how it exited.
295func GitStream(ctx context.Context, repo string, limit int64, read func(io.Reader) error, args ...string) error {
296 return GitStreamInput(ctx, repo, nil, limit, read, args...)
297}
298
299// GitStreamInput runs git as GitStream does, with stdin as git's standard
300// input. A nil stdin gives git no input, as GitStream does.
301func GitStreamInput(ctx context.Context, repo string, stdin []byte, limit int64, read func(io.Reader) error, args ...string) error {
302 if len(args) == 0 {
303 return errors.New("git needs a command")
304 }
305 return run(command(ctx, "", append([]string{"--git-dir=" + repo}, args...)...), args[0], stdin, limit, read)
306}
307
308// run starts cmd, with stdin as its standard input when it is not nil,
309// and gives read cmd's standard output, at most limit bytes of it. It
310// keeps the first maxStderr bytes of cmd's standard error for its error,
311// which names git's verb.
312func run(cmd *exec.Cmd, verb string, stdin []byte, limit int64, read func(io.Reader) error) error {
313 if stdin != nil {
314 cmd.Stdin = bytes.NewReader(stdin)
315 }
316 stderr := &head{max: maxStderr}
317 cmd.Stderr = stderr
318 pipe, err := cmd.StdoutPipe()
319 if err != nil {
320 return fmt.Errorf("git %s: %w", verb, err)
321 }
322 if err := cmd.Start(); err != nil {
323 return fmt.Errorf("git %s: %w", verb, err)
324 }
325 out := &bounded{r: pipe, n: limit, err: fmt.Errorf("git %s: %w", verb, ErrOutputLimit)}
326 readErr := read(out)
327 if readErr != nil || !out.eof {
328 // git, or a process it started, may be blocked writing to a pipe
329 // nobody reads any more.
330 cmd.Cancel()
331 }
332 err = cmd.Wait()
333 switch {
334 case readErr != nil:
335 return readErr
336 case !out.eof:
337 return nil
338 case err != nil:
339 return fmt.Errorf("git %s: %w: %s", verb, err, strings.TrimSpace(stderr.String()))
340 }
341 return nil
342}
343
344// bounded reads r, at most n bytes of it. A read once n bytes are read
345// fails with err if r holds more, and is the end of the output if it does
346// not. eof is set once r's end is read.
347type bounded struct {
348 r io.Reader
349 n int64
350 err error
351 over bool
352 eof bool
353}
354
355func (b *bounded) Read(p []byte) (int, error) {
356 switch {
357 case b.over:
358 return 0, b.err
359 case b.eof:
360 return 0, io.EOF
361 case len(p) == 0:
362 return 0, nil
363 case b.n <= 0:
364 // One byte more is past the limit, and the end is not.
365 var one [1]byte
366 n, err := b.r.Read(one[:])
367 if n > 0 {
368 b.over = true
369 return 0, b.err
370 }
371 b.eof = err == io.EOF
372 return 0, err
373 }
374 if int64(len(p)) > b.n {
375 p = p[:b.n]
376 }
377 n, err := b.r.Read(p)
378 b.n -= int64(n)
379 b.eof = err == io.EOF
380 return n, err
381}
382
383// head keeps the first max bytes written to it and drops the rest, so a
384// command's standard error is read to its end and never held whole.
385type head struct {
386 max int
387 b bytes.Buffer
388}
389
390func (h *head) Write(p []byte) (int, error) {
391 if room := h.max - h.b.Len(); room > 0 {
392 h.b.Write(p[:min(len(p), room)])
393 }
394 return len(p), nil
395}
396
397func (h *head) String() string { return h.b.String() }
398
399// command is git, run in dir unless it is "", with replacement refs off
400// and an environment that holds none of the caller's GIT_ variables and
401// reads no system or global configuration.
402//
403// git runs in a process group of its own, and every process git starts
404// runs in that group unless it leaves it. Once ctx is done, the whole
405// group is killed, so no process git started keeps running, or keeps
406// git's output open, once git is stopped. A process that left the group
407// can still hold the output open. Go closes the output gitWaitDelay after
408// the group is killed, or after git exits once git is waited for.
409func command(ctx context.Context, dir string, args ...string) *exec.Cmd {
410 if dir != "" {
411 args = append([]string{"-C", dir}, args...)
412 }
413 cmd := exec.CommandContext(ctx, GitProgram, append([]string{"--no-replace-objects"}, args...)...)
414 cmd.Env = gitEnvironment(os.Environ())
415 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
416 cmd.Cancel = func() error {
417 // The group's ID is git's process ID.
418 if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); !errors.Is(err, syscall.ESRCH) {
419 return err
420 }
421 return os.ErrProcessDone
422 }
423 cmd.WaitDelay = gitWaitDelay
424 return cmd
425}
426
427// gitWaitDelay is how long a git command's output may stay open once git
428// is stopped or has exited.
429const gitWaitDelay = 2 * time.Second
430
431func gitEnvironment(inherited []string) []string {
432 var env []string
433 for _, kv := range inherited {
434 if !strings.HasPrefix(kv, "GIT_") {
435 env = append(env, kv)
436 }
437 }
438 return append(env,
439 "GIT_CONFIG_NOSYSTEM=1",
440 "GIT_CONFIG_GLOBAL=/dev/null",
441 "GIT_NO_REPLACE_OBJECTS=1",
442 "GIT_ATTR_NOSYSTEM=1",
443 "GIT_TERMINAL_PROMPT=0",
444 )
445}
446
447func git(ctx context.Context, dir string, args ...string) ([]byte, error) {
448 return gitInput(ctx, dir, nil, args...)
449}
450
451func gitInput(ctx context.Context, dir string, stdin []byte, args ...string) ([]byte, error) {
452 verb := args[0]
453 for i := 0; verb == "-c" && i+2 < len(args); i += 2 {
454 verb = args[i+2]
455 }
456 var out []byte
457 err := run(command(ctx, dir, args...), verb, stdin, maxOutput, func(r io.Reader) (err error) {
458 out, err = io.ReadAll(r)
459 return err
460 })
461 return out, err
462}