gitproto

package module
v0.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: BSD-3-Clause Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gitproto

go-vcs gitproto

Go Reference License CI Landing Docs

Git wire protocol v2 (fetch side) as a Go library, with no knowledge of any forge: it takes an io.Reader, an io.Writer and a Repository, so a forge can mount it on SSH and on smart HTTP. Part of go-vcs, a light, secure Git forge.

Status: v0.2.0 adds the receivepack package, the request side of a push: it parses the receive-pack command list and push options, checks ref names (CheckRefName), finds refs that a case-folding file system would store as one file (FoldKey, Request.FoldCollision) and writes the status report (see Push). The fetch side, released as v0.1.0, serves ls-refs and fetch from an on-disk repository; there is no shallow and no filters. A full clone takes 0.93 to 0.96 of the time of git upload-pack (six interleaved runs on one reference repository, v0.1.0, see BENCHMARK.md). You can try receivepack in the browser playground.

Use

srv := &gitproto.Server{Repo: &gitproto.GitRepo{Dir: "/srv/git/x.git"}}

// Stateful transports (ssh, stdio, git://): advertise, then loop.
err := srv.Serve(ctx, conn, conn)

// Smart HTTP: GET info/refs -> Advertise; POST git-upload-pack -> ServeRequest.
err := srv.Advertise(w)
err := srv.ServeRequest(ctx, r, w) // io.EOF = empty request

A refused request is answered with an ERR <reason> pkt-line and returned as *gitproto.ProtocolError; repository failures are answered with the generic ERR internal error (paths and git's stderr never reach the client) and returned to the caller as is.

cmd/gitproto-upload-pack serves git-upload-pack over stdio (cobra), so the real git client can drive it:

git -c protocol.version=2 clone --upload-pack=gitproto-upload-pack file:///srv/git/x.git

It requires GIT_PROTOCOL=version=2 and refuses protocol 0 and 1. --advertise-refs and --stateless-rpc give the smart-HTTP halves.

Object storage: delegated to git, behind one interface

Repository is the narrow seam (Refs, CommonCommits, WritePack). Milestone 1 implements it with the git binary (GitRepo): refs are read directly from a "files" repository and through for-each-ref, symbolic-ref, rev-parse, cat-file --batch-check otherwise (see the bibliography); packs come from pack-objects --revs --stdout. Every command line is fixed in gitrepo.go; no wire input reaches argv (object ids are validated as 40 lowercase hex digits and written to stdin), no shell is involved, and git runs with a minimal environment (GIT_DIR, no user or system config, no replace objects). A pure-Go object store is a later decision, to be taken from measurements; it only has to implement Repository.

What is supported, what is refused

Supported: capability advertisement (version 2, agent, ls-refs=unborn, fetch, object-format=sha1); ls-refs with peel, symrefs, ref-prefix, unborn; fetch with want, have, done, thin-pack, no-progress, include-tag, ofs-delta, acknowledgments (ACK/NAK/ready) and the side-band-64k packfile section.

Refused explicitly, each with a test (server_test.go, TestRefusals, TestLimits, pktline_test.go):

  • pkt-lines: length not four lowercase hex digits, 0003, longer than 65520 bytes (refused after the 4 header bytes, before any payload is read), truncated packets, NUL in a request line;
  • request shape: no command=, invalid command or capability names, delim or response-end packets where they do not belong, a second delim, truncation;
  • capabilities not advertised: server-option, unknown keys, any object-format but sha1, empty / non-printable / duplicated agent;
  • commands not advertised: object-info, bundle-uri, anything else;
  • ls-refs arguments the spec does not define;
  • fetch features not advertised, by name: shallow, deepen, deepen-relative, deepen-since, deepen-not, filter, want-ref, sideband-all, packfile-uris, wait-for-done; unknown arguments; malformed object ids; values on flag arguments;
  • a want that is not an advertised tip (or the peeled object of one): not our ref. Unlike a bare git upload-pack, an object is never served just because the client can name it;
  • bounded requests (Limits, defaults 8 MiB, 100 000 lines, 50 000 wants and haves, 1 024 ref-prefixes); a request that never ends is cut off at the limit (TestBomb*, run under GOMEMLIMIT=64MiB in CI).

Fuzz targets: FuzzReader (pkt-line), FuzzParseRequest, FuzzParseFetch, FuzzParseLsRefs, FuzzServe (whole server over a fake repository). Seed corpus under testdata/fuzz; CI runs each target for 20 s.

Real git is the oracle: ls-refs output is compared byte for byte with git upload-pack --stateless-rpc on seven repository shapes (normal, empty, detached HEAD, HEAD at a tag, symbolic ref, loose refs overriding packed ones, dangling symbolic ref), and Refs is compared with git for-each-ref on nine; packs are checked with git index-pack --strict --fix-thin and git fsck; git clone and git fetch run through the built binary.

Push, pack side: packfile

packfile.Index(ctx, src, dir, store, limits) reads a pack stream as git index-pack --stdin --strict --fix-thin does and writes pack-<sha1>.pack and .idx (version 2) into dir, a quarantine the caller owns. Nothing the client says is believed: every object id is recomputed from the inflated content, the trailer is verified, commits, trees and tags are parsed strictly (ParseObject: one tree line, well-formed idents, tree entry modes and order, no ./../.git names in any case nor in their NTFS (git~1, trailing spaces and dots, :stream) and HFS+ (ignorable code points) spellings, no symbolic link named .gitmodules; the content of a .gitmodules blob is not checked), duplicates are refused, and a REF_DELTA whose base is not in the pack is read from the Store and appended (a thin pack is completed, also when a delta's base is itself a delta on a thin base). Object ids are SHA-1DC (github.com/pjbgf/sha1cd, the collision detection git is built with): an input carrying the signature of a collision attack is refused as ErrCollision (wrapping ErrCorrupt), and an object whose id the Store already holds is compared with the stored content, as git index-pack does. Every Store method takes the context of the call. Result carries the type of every object and the links between them, for the connectivity check. On any error dir is left empty.

Every resource has a bound, defaults in DefaultLimits, each refused with an error wrapping ErrLimit and proved by a test that runs in a child process under GOMEMLIMIT and, on Linux, RLIMIT_AS: object count (a header announcing 2^32-1), one object's size (declared 1 GiB, 5 bytes shipped), total inflated bytes, delta result size, delta chain depth, a fan-out of deltas on one base, live memory while resolving, tree/commit links, the pack stream length (an endless zlib stream), and the timeout. The timeout and the context also interrupt a read of the source that blocks (Index returns as soon as they end; a source with SetReadDeadline is given the deadline; the source must not be used after such an error). The memory held is bounded by MaxLiveBytes, scratch buffer and collected links included. A zlib bomb (the stream inflates past the size it announced) is refused as ErrCorrupt without being inflated past that size.

Result.Walk(ctx, fn) streams the verified objects (id, type, content, deltas resolved), so a consumer that keeps objects in memory or in its own cache needs no pack on disk: index into a scratch directory, Walk, delete. A consumer migrating from its own parser supplies its lookup as the Store.

Tested against git: git pack-objects output (OFS and REF deltas, window 50) yields a .idx byte-identical to git index-pack's; a thin pack from git pack-objects --thin is completed and its idx equals git's; empty pack, and 25 corrupt-pack shapes. Fuzzed: FuzzIndex, FuzzIndexBody (trailer and count recomputed so the inflate and delta code is reached), FuzzIndexAgentd (the 160-input corpus of go-vcs/agentd's FuzzParsePack), FuzzApplyDelta, FuzzParseObject, and FuzzIndexStructured (the fuzzed bytes are a program that builds entries with the real zlib writer: types, delta bases and announced sizes are steered, so refusals deep in the reader are reached), all with committed corpora. Bomb tests (TestBomb*) run in a child process under GOMEMLIMIT and, on Linux, ulimit -v; the TestBombDefault* ones use DefaultLimits for the object count and size, the numbers an unconfigured server runs with; the delta-depth and delta-fan-out ones run the same code at scaled values (depth 256 instead of 4095, a total of 256 MiB instead of 4 GiB) because the race detector cannot afford the defaults, and assert the default depth is the 4095 stated here. internal/refusalcov replays a cover profile and lists any refusal branch never executed:

GITPROTO_BOMB_INPROCESS=1 go test -coverprofile=c.out ./packfile
go run ./internal/refusalcov --module github.com/go-vcs/gitproto --dir . c.out

(63 of 63 refusal blocks executed.) Only SHA-1 repositories (object-format sha1).

Push (receive-pack), request side: receivepack

receivepack.Parse(pktline.NewReader(conn), limits) reads the command list and the push options, and returns a plain *Request (commands, capabilities, push options, WantsPack) so a forge can decide policy BEFORE one byte of pack is read; the source is left on the first byte of the pack. receivepack.WriteReport writes report-status / report-status-v2 (side-band-64k wrapped when negotiated); Advertise writes the v0 ref advertisement. Refused, each with a test: shallow, push certificates, side-band (small), unknown capabilities, object-format other than sha1, malformed ids, bad ref names (git-check-ref-format, plus C1 controls, U+FFFD and invalid UTF-8, which WriteReport cannot print), duplicate refs, bounds on commands, push options and request bytes. MaxMemoryBytes is finite by default (64 MiB) and charged before each allocation. FoldKey and Request.FoldCollision find refs that a folding file system (APFS, NTFS) stores as one file (canonical caseless match, Unicode D145, Unicode 17.0.0); FoldCollision uses the request's budget and deadline. The fold follows the Unicode tables of the Go toolchain that built the binary (unicode.Version), so CheckRefName fails closed: it refuses a ref name with a code point those tables leave unassigned (a Unicode 16 letter under Go 1.26, for instance), which could otherwise alias a protected name on a file system that knows it. It also refuses a name in which any normalisation of the fold holds a U+034F, in the input or inserted by x/text (UAX #15, Stream-Safe Text Format: it cuts a long run of marks and does not reorder across the cut, APFS does). It asks the normaliser itself, because its count also includes some starters (jamo, vowel signs, U+FF9E, compatibility decompositions, Hangul syllables). CheckRefName also applies the component rules to the FOLDED component (main.LOCK and main.loc + Kelvin sign are the lock file of main on APFS, so they are refused), refuses default-ignorable code points outright, the characters ", <, > and |, a component ending with ., the Windows device names (nul, con, aux, prn, com1-com9, lpt0-lpt9, conin$, conout$, with any extension, in any case: git's is_valid_win32_path, compat/mingw.c, under core.protectNTFS; plus com0 and the superscript digits of com/lpt, which Microsoft's naming documentation lists and git does not), every blank, separator and format code point (Zs, Zl, Zp, Cf, U+2800, U+FFFC) and a name longer than 65520 bytes. Parse allows a one-level name (refs/stash) on a delete only, as git's receive-pack.c does (update(): check_refname_format(name + 5, is_null_oid(new_oid) ? REFNAME_ALLOW_ONELEVEL : 0)); CheckRefName itself still refuses it. FoldKey itself refuses nothing; call it on names that passed CheckRefName. A key depends on the toolchain's Unicode tables: never persist it, and check stored refs again with CheckRefName. FoldCollision refuses a Request that Parse did not make (it carries the budget and the deadline), and a deadline overrun is an error, in Parse and in FoldCollision, never a late answer. FuzzParse has a committed corpus; TestRealGitPush runs the real git push against a server built on the package. The pack side (index, delta resolution, bounds) is a separate package.

Benchmark

See BENCHMARK.md.

Bibliography

Opened and used (git v2.47.0, Documentation/):

  • gitprotocol-v2 — capability advertisement, command request, ls-refs, fetch sections, special packets 0000/0001/0002;
  • gitprotocol-common — pkt-line format, the 65520 / 65516 bounds, flush-pkt versus empty pkt-line;
  • gitprotocol-pack — side-band(-64k) framing of the packfile (lines 472–490);
  • gitprotocol-capabilities — side-band-64k (lines 135–168);
  • CaseFolding.txt 17.0.0 (receivepack/testdata/ucd), The Unicode Standard section 3.13 (D145, canonical caseless matching), UAX #15 (normalization forms) — the fold of receivepack.FoldKey.

Opened and used for reading refs without a process (refs_files.go):

  • gitrepository-layout(5) (git 2.54.0 man page on the build machine) — refs/, packed-refs ("the same information ... in a more efficient way"), HEAD as a symref or a detached object id;
  • refs/packed-backend.c (git/git, master, read 2026-11-25) — the "# pack-refs with:" header and its traits, fully-peeled meaning a ref with no ^ line is not peelable (create_snapshot, lines 697-761), the record and peel-line grammar (the record iterator, lines 935-1001);
  • a reftable repository, observed with git init --ref-format=reftable in git 2.54.0: config extensions.refstorage = reftable, a stub HEAD (ref: refs/heads/.invalid), a refs/heads file, a reftable/ directory. The git 2.54 git-config(1) man page on the build machine does not document extensions.refStorage, so that key is cited from the observation, not from a document I read.

Behaviour: only a repository whose config has no extensions.refStorage, or exactly files, with no commondir and no reftable/, is read in Go. A reftable or unknown backend, a linked worktree, a detached HEAD, a dangling or cyclic symbolic ref, a packed-refs without fully-peeled, a malformed or oddly named ref: all go to git for-each-ref, never guessed at. Loose refs outside refs/heads/ are peeled with one cat-file --batch-check (a loose file does not say whether it names a tag); git refuses to write a non-commit under refs/heads/, so those are taken as commits. Bounds, refused with an error: packed-refs 256 MiB, 8 KiB per line or loose file, a million refs, 64 directory levels under refs/. FuzzParsePackedRefs covers the parser.

Opened and used for the pack reader (git-scm.com, read 2026-11-28): gitformat-pack — entry header, OFS/REF delta encodings, delta instructions (copy size 0 means 0x10000, instruction 0 reserved), idx v2 layout, CRC32 of the whole entry, trailer. git-index-pack(1) was not opened: only its observable output is compared, with the git binary.

Push, opened and used (git-scm.com/docs, read 2026-11-28): gitprotocol-pack (update-requests grammar, "packfile MUST NOT be sent if the only command is delete", push-options after the flush, report-status and report-status-v2 grammars). The page does not say the report is wrapped in side-band; that is git's observed behaviour (the real client accepts our wrapped report in TestRealGitPush). gitprotocol-capabilities is the capability list.

gitprotocol-v2 also describes shallow, filter, ref-in-want, sideband-all, packfile-uris, wait-for-done, object-info, bundle-uri and server-option: read, not implemented, refused.

License

BSD-3-Clause.

Documentation

Overview

Package gitproto serves Git wire protocol v2 (fetch side) from a Repository, over any transport that gives an io.Reader and an io.Writer.

It knows nothing about forges, users or permissions: the caller decides who may reach which repository and mounts Serve (stateful: ssh, stdio, git://) or Advertise plus ServeRequest (stateless: smart HTTP) on its transport.

Supported: capability advertisement, ls-refs (peel, symrefs, ref-prefix, unborn), fetch (want, have, done, thin-pack, no-progress, include-tag, ofs-delta). Everything else is refused by name with an "ERR" pkt-line: shallow and deepen*, filter, want-ref, sideband-all, packfile-uris, wait-for-done, object-info, bundle-uri, server-option, any object format but sha1, and protocol versions 0 and 1.

Index

Constants

This section is empty.

Variables

View Source
var DefaultLimits = Limits{
	MaxRequestBytes: 8 << 20,
	MaxRequestLines: 100_000,
	MaxWants:        50_000,
	MaxHaves:        50_000,
	MaxRefPrefixes:  1024,
}

DefaultLimits are used for every zero field of Limits.

Functions

func ValidOID

func ValidOID(s string) bool

ValidOID reports whether s is 40 lowercase hexadecimal digits.

Types

type FetchArgs

type FetchArgs struct {
	Wants      []string
	Haves      []string
	Done       bool
	ThinPack   bool
	NoProgress bool
	IncludeTag bool
	OfsDelta   bool
}

FetchArgs are the parsed arguments of a fetch request.

func ParseFetch

func ParseFetch(args []string, lim Limits) (FetchArgs, error)

ParseFetch parses the argument lines of a fetch request. Arguments of a feature the server does not advertise, and unknown arguments, are refused; so is an object id that is not 40 lowercase hex digits.

type GitRepo

type GitRepo struct {
	// Dir is the repository's git directory (a bare repository, or a
	// .git directory).
	Dir string
	// Git is the git executable. Empty means "git" found on PATH.
	Git string
	// PackThreads is passed to git pack-objects as --threads. Zero leaves
	// git's default (all cores).
	PackThreads int
	// NoNativeRefs makes Refs always ask git, never read the ref files.
	NoNativeRefs bool
}

GitRepo is a Repository backed by the git binary on an on-disk repository.

Milestone 1 delegates object reading and pack building to git: every command line is fixed in this file, nothing from the wire reaches argv (object ids are validated 40-hex strings written to stdin), no shell is involved, and git runs with a minimal environment and no user or system configuration.

func (*GitRepo) CommonCommits

func (g *GitRepo) CommonCommits(ctx context.Context, ids []string) ([]string, error)

CommonCommits implements Repository.

func (*GitRepo) Refs

func (g *GitRepo) Refs(ctx context.Context) ([]Ref, error)

Refs implements Repository. A repository using the files ref backend is read directly (refs_files.go); anything that reader does not fully understand, reftable included, is answered by git.

func (*GitRepo) RefsUnpeeled

func (g *GitRepo) RefsUnpeeled(ctx context.Context) ([]Ref, error)

RefsUnpeeled is Refs without the peeling that costs a process: a loose ref outside refs/heads/ may lack its Peeled id. Every ID is exact, so it answers "is this object a ref's tip" without spawning git; serveFetch asks it first and falls back to Refs only for a want that is not a tip.

func (*GitRepo) WritePack

func (g *GitRepo) WritePack(ctx context.Context, req PackRequest, w io.Writer) error

WritePack implements Repository with git pack-objects --revs --stdout.

type Limits

type Limits struct {
	// MaxRequestBytes bounds the bytes read for one command request.
	MaxRequestBytes int64
	// MaxRequestLines bounds the pkt-lines of one command request.
	MaxRequestLines int
	// MaxWants bounds "want" lines of a fetch request.
	MaxWants int
	// MaxHaves bounds "have" lines of a fetch request.
	MaxHaves int
	// MaxRefPrefixes bounds "ref-prefix" lines of an ls-refs request.
	MaxRefPrefixes int
}

Limits bound what one request may cost. The zero value of a field means the default; a negative value is refused by Validate.

func (Limits) Validate

func (l Limits) Validate() error

Validate refuses negative limits.

type LsRefsArgs

type LsRefsArgs struct {
	Symrefs  bool
	Peel     bool
	Unborn   bool
	Prefixes []string
}

LsRefsArgs are the parsed arguments of an ls-refs request (gitprotocol-v2, "ls-refs").

func ParseLsRefs

func ParseLsRefs(args []string, lim Limits) (LsRefsArgs, error)

ParseLsRefs parses the argument lines of an ls-refs request. Unknown arguments are refused.

type PackRequest

type PackRequest struct {
	// Wants are the objects to send, with everything reachable from them.
	Wants []string
	// Common are commits the client has; everything reachable from them is
	// left out.
	Common []string
	// Thin permits deltas against objects the client has.
	Thin bool
	// OfsDelta permits OBJ_OFS_DELTA.
	OfsDelta bool
	// IncludeTag adds annotated tags that point at sent objects.
	IncludeTag bool
}

PackRequest is what fetch asks of the object store. Every id has already been validated as 40 lowercase hex digits by the protocol layer.

type ProtocolError

type ProtocolError struct{ Msg string }

ProtocolError is a refusal caused by the client's request. It is reported to the client as an "ERR <message>" pkt-line.

func (*ProtocolError) Error

func (e *ProtocolError) Error() string

type Ref

type Ref struct {
	// Name is the full ref name, or "HEAD".
	Name string
	// ID is the object id the ref resolves to (40 lowercase hex digits).
	// It is empty only for an unborn HEAD.
	ID string
	// Target is the name of the ref this symbolic ref points to, or "".
	Target string
	// Peeled is the fully peeled object id when ID is an annotated tag.
	Peeled string
}

Ref is one reference as ls-refs reports it.

type Repository

type Repository interface {
	// Refs lists HEAD (first, possibly unborn) and every ref, sorted by
	// name, with symbolic targets and peeled ids.
	Refs(ctx context.Context) ([]Ref, error)
	// CommonCommits returns, in input order, those of ids that are commits
	// present in the repository.
	CommonCommits(ctx context.Context, ids []string) ([]string, error)
	// WritePack writes a pack file for req to w.
	WritePack(ctx context.Context, req PackRequest, w io.Writer) error
}

Repository is the narrow interface between the protocol and an object store. The git-binary-backed implementation is GitRepo; a pure-Go store can implement it later without touching the protocol code.

type Request

type Request struct {
	// Command is the value of "command=".
	Command string
	// Agent is the client's agent string, if it sent one.
	Agent string
	// Args are the command-specific argument lines, LF stripped, after the
	// delim-pkt.
	Args []string
}

Request is a parsed command request (gitprotocol-v2: command-request).

func ParseRequest

func ParseRequest(r *pktline.Reader, lim Limits) (*Request, error)

ParseRequest reads one command request from r. It returns io.EOF for a clean end of session: end of input between requests, or the empty request (a lone flush-pkt). Every other malformed input is a *ProtocolError, except for transport failures, which are returned as read.

type Server

type Server struct {
	Repo   Repository
	Limits Limits
	// Agent is advertised as agent=<Agent>. Empty means "gitproto".
	Agent string
}

Server serves protocol v2 requests from Repo.

func (*Server) Advertise

func (s *Server) Advertise(w io.Writer) error

Advertise writes the capability advertisement: "version 2", the capabilities and a flush-pkt (gitprotocol-v2, "Capability Advertisement").

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, r io.Reader, w io.Writer) error

Serve is a stateful session: it advertises, then answers command requests until the client sends the empty request or closes the connection. It returns nil on a clean end, a *ProtocolError after refusing a request (the client has been sent the "ERR" line), or the transport / repository error.

func (*Server) ServeRequest

func (s *Server) ServeRequest(ctx context.Context, r io.Reader, w io.Writer) error

ServeRequest answers one command request read from r (the stateless-rpc case: no advertisement, no loop). It returns io.EOF when r holds the empty request or nothing.

Directories

Path Synopsis
cmd
gitproto-upload-pack command
Command gitproto-upload-pack serves git-upload-pack over stdio using gitproto: protocol v2 only, fetch side.
Command gitproto-upload-pack serves git-upload-pack over stdio using gitproto: protocol v2 only, fetch side.
internal
refusalcov command
Command refusalcov reads a Go cover profile and reports which refusal branches of a package were never executed: a coverage block whose source lines build a refusal (corrupt(, limitErr(, ErrMissingBase) and whose count is zero.
Command refusalcov reads a Go cover profile and reports which refusal branches of a package were never executed: a coverage block whose source lines build a refusal (corrupt(, limitErr(, ErrMissingBase) and whose count is zero.
Package packfile reads a pack stream as git-receive-pack does and builds the pack and its version 2 index: the equivalent of `git index-pack --stdin --strict --fix-thin`, bounded.
Package packfile reads a pack stream as git-receive-pack does and builds the pack and its version 2 index: the equivalent of `git index-pack --stdin --strict --fix-thin`, bounded.
Package pktline implements Git's pkt-line framing as specified by gitprotocol-common(5) and the protocol v2 special packets of gitprotocol-v2(5): flush-pkt "0000", delim-pkt "0001" and response-end-pkt "0002".
Package pktline implements Git's pkt-line framing as specified by gitprotocol-common(5) and the protocol v2 special packets of gitprotocol-v2(5): flush-pkt "0000", delim-pkt "0001" and response-end-pkt "0002".
Package receivepack parses the client side of git-receive-pack and writes its reply, as specified by gitprotocol-pack(5) ("Reference Update Request and Packfile Transfer", "Report Status") and gitprotocol-capabilities(5).
Package receivepack parses the client side of git-receive-pack and writes its reply, as specified by gitprotocol-pack(5) ("Reference Update Request and Packfile Transfer", "Report Status") and gitprotocol-capabilities(5).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL