gunk-dev/the-valley

bundle.go

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