| 1 | package export |
| 2 | |
| 3 | import ( |
| 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>". |
| 21 | var GitProgram = "git" |
| 22 | |
| 23 | // MainRef is the one ref a bundle carries, and the one a generation's |
| 24 | // repository holds. |
| 25 | const 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. |
| 29 | const 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. |
| 47 | func 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. |
| 65 | func 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. |
| 79 | func 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. |
| 160 | func 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. |
| 203 | func 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. |
| 257 | var 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. |
| 260 | const ( |
| 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. |
| 278 | func 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. |
| 295 | func GitStream(ctx context.Context, repo string, limit int64, read func(io.Reader) error, args ...string) error { |
| 296 | if len(args) == 0 { |
| 297 | return errors.New("git needs a command") |
| 298 | } |
| 299 | return run(command(ctx, "", append([]string{"--git-dir=" + repo}, args...)...), args[0], nil, limit, read) |
| 300 | } |
| 301 | |
| 302 | // run starts cmd, with stdin as its standard input when it is not nil, |
| 303 | // and gives read cmd's standard output, at most limit bytes of it. It |
| 304 | // keeps the first maxStderr bytes of cmd's standard error for its error, |
| 305 | // which names git's verb. |
| 306 | func run(cmd *exec.Cmd, verb string, stdin []byte, limit int64, read func(io.Reader) error) error { |
| 307 | if stdin != nil { |
| 308 | cmd.Stdin = bytes.NewReader(stdin) |
| 309 | } |
| 310 | stderr := &head{max: maxStderr} |
| 311 | cmd.Stderr = stderr |
| 312 | pipe, err := cmd.StdoutPipe() |
| 313 | if err != nil { |
| 314 | return fmt.Errorf("git %s: %w", verb, err) |
| 315 | } |
| 316 | if err := cmd.Start(); err != nil { |
| 317 | return fmt.Errorf("git %s: %w", verb, err) |
| 318 | } |
| 319 | out := &bounded{r: pipe, n: limit, err: fmt.Errorf("git %s: %w", verb, ErrOutputLimit)} |
| 320 | readErr := read(out) |
| 321 | if readErr != nil || !out.eof { |
| 322 | // git, or a process it started, may be blocked writing to a pipe |
| 323 | // nobody reads any more. |
| 324 | cmd.Cancel() |
| 325 | } |
| 326 | err = cmd.Wait() |
| 327 | switch { |
| 328 | case readErr != nil: |
| 329 | return readErr |
| 330 | case !out.eof: |
| 331 | return nil |
| 332 | case err != nil: |
| 333 | return fmt.Errorf("git %s: %w: %s", verb, err, strings.TrimSpace(stderr.String())) |
| 334 | } |
| 335 | return nil |
| 336 | } |
| 337 | |
| 338 | // bounded reads r, at most n bytes of it. A read once n bytes are read |
| 339 | // fails with err if r holds more, and is the end of the output if it does |
| 340 | // not. eof is set once r's end is read. |
| 341 | type bounded struct { |
| 342 | r io.Reader |
| 343 | n int64 |
| 344 | err error |
| 345 | over bool |
| 346 | eof bool |
| 347 | } |
| 348 | |
| 349 | func (b *bounded) Read(p []byte) (int, error) { |
| 350 | switch { |
| 351 | case b.over: |
| 352 | return 0, b.err |
| 353 | case b.eof: |
| 354 | return 0, io.EOF |
| 355 | case len(p) == 0: |
| 356 | return 0, nil |
| 357 | case b.n <= 0: |
| 358 | // One byte more is past the limit, and the end is not. |
| 359 | var one [1]byte |
| 360 | n, err := b.r.Read(one[:]) |
| 361 | if n > 0 { |
| 362 | b.over = true |
| 363 | return 0, b.err |
| 364 | } |
| 365 | b.eof = err == io.EOF |
| 366 | return 0, err |
| 367 | } |
| 368 | if int64(len(p)) > b.n { |
| 369 | p = p[:b.n] |
| 370 | } |
| 371 | n, err := b.r.Read(p) |
| 372 | b.n -= int64(n) |
| 373 | b.eof = err == io.EOF |
| 374 | return n, err |
| 375 | } |
| 376 | |
| 377 | // head keeps the first max bytes written to it and drops the rest, so a |
| 378 | // command's standard error is read to its end and never held whole. |
| 379 | type head struct { |
| 380 | max int |
| 381 | b bytes.Buffer |
| 382 | } |
| 383 | |
| 384 | func (h *head) Write(p []byte) (int, error) { |
| 385 | if room := h.max - h.b.Len(); room > 0 { |
| 386 | h.b.Write(p[:min(len(p), room)]) |
| 387 | } |
| 388 | return len(p), nil |
| 389 | } |
| 390 | |
| 391 | func (h *head) String() string { return h.b.String() } |
| 392 | |
| 393 | // command is git, run in dir unless it is "", with replacement refs off |
| 394 | // and an environment that holds none of the caller's GIT_ variables and |
| 395 | // reads no system or global configuration. |
| 396 | // |
| 397 | // git runs in a process group of its own, and every process git starts |
| 398 | // runs in that group unless it leaves it. Once ctx is done, the whole |
| 399 | // group is killed, so no process git started keeps running, or keeps |
| 400 | // git's output open, once git is stopped. A process that left the group |
| 401 | // can still hold the output open. Go closes the output gitWaitDelay after |
| 402 | // the group is killed, or after git exits once git is waited for. |
| 403 | func command(ctx context.Context, dir string, args ...string) *exec.Cmd { |
| 404 | if dir != "" { |
| 405 | args = append([]string{"-C", dir}, args...) |
| 406 | } |
| 407 | cmd := exec.CommandContext(ctx, GitProgram, append([]string{"--no-replace-objects"}, args...)...) |
| 408 | cmd.Env = gitEnvironment(os.Environ()) |
| 409 | cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| 410 | cmd.Cancel = func() error { |
| 411 | // The group's ID is git's process ID. |
| 412 | if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); !errors.Is(err, syscall.ESRCH) { |
| 413 | return err |
| 414 | } |
| 415 | return os.ErrProcessDone |
| 416 | } |
| 417 | cmd.WaitDelay = gitWaitDelay |
| 418 | return cmd |
| 419 | } |
| 420 | |
| 421 | // gitWaitDelay is how long a git command's output may stay open once git |
| 422 | // is stopped or has exited. |
| 423 | const gitWaitDelay = 2 * time.Second |
| 424 | |
| 425 | func gitEnvironment(inherited []string) []string { |
| 426 | var env []string |
| 427 | for _, kv := range inherited { |
| 428 | if !strings.HasPrefix(kv, "GIT_") { |
| 429 | env = append(env, kv) |
| 430 | } |
| 431 | } |
| 432 | return append(env, |
| 433 | "GIT_CONFIG_NOSYSTEM=1", |
| 434 | "GIT_CONFIG_GLOBAL=/dev/null", |
| 435 | "GIT_NO_REPLACE_OBJECTS=1", |
| 436 | "GIT_ATTR_NOSYSTEM=1", |
| 437 | "GIT_TERMINAL_PROMPT=0", |
| 438 | ) |
| 439 | } |
| 440 | |
| 441 | func git(ctx context.Context, dir string, args ...string) ([]byte, error) { |
| 442 | return gitInput(ctx, dir, nil, args...) |
| 443 | } |
| 444 | |
| 445 | func gitInput(ctx context.Context, dir string, stdin []byte, args ...string) ([]byte, error) { |
| 446 | verb := args[0] |
| 447 | for i := 0; verb == "-c" && i+2 < len(args); i += 2 { |
| 448 | verb = args[i+2] |
| 449 | } |
| 450 | var out []byte |
| 451 | err := run(command(ctx, dir, args...), verb, stdin, maxOutput, func(r io.Reader) (err error) { |
| 452 | out, err = io.ReadAll(r) |
| 453 | return err |
| 454 | }) |
| 455 | return out, err |
| 456 | } |