gitproto

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. The pack side of
a push (the packfile indexer and the connectivity check) is not yet released.
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).
Connectivity
packfile.CheckConnectivity(ctx, res, store, tips) is the check a receiving
server runs before it publishes refs: every link of every object of the pack
(commit tree and parents, tag target, tree entries other than gitlinks) must
resolve to an object of the pack or of the Store, with the type the referrer
requires, and every tip must exist with the type its ref requires. It refuses
a missing object with ErrNotConnected, a type mismatch as ErrCorrupt.
The Store invariant: every object the store holds is connected, that is, its
whole closure is in the store (what git assumes of the objects its refs reach).
An object found in the store is trusted and not walked. Two differences from
git, one each way. It is stricter: it checks the links of every object the pack
carries, not only those a tip reaches. It is laxer in one case: git walks from
the tip down to what the refs reach (rev-list --objects <tip> --not --all), so
it also finds the hole of a dangling object of the repository (one that no ref
reaches and whose closure is incomplete, such as a commit whose tree is missing)
and refuses the push with "bad tree object"; this check accepts a push that
links to it. A store that keeps unreachable objects it did not verify must
verify them itself or not report them; walking the whole store on every push
is not done. TestConnectivityTrustsADanglingStoreObject holds both sides.
packfile.CheckReferenced is the other
direction: it refuses with ErrUnreferenced a pack carrying an object that no
tip reaches (the bases a thin pack was completed with excepted), so a push
cannot fill a store with unrelated objects. Result.Bases lists those bases.
Store lookups are made once per distinct id.
Migrating go-vcs/agentd
agentd's ParsePack becomes: Index into a scratch directory with a Store
supplying its lookups for thin bases, then Result.Walk to stream the
verified objects, then delete the scratch directory. Caveat: ParsePack
supports sha256 and this package is sha1-only, so a sha256 repository cannot
migrate until that is added here.
Measured against git index-pack on small packs, Index takes 0.47 to 0.66
of its time, the range of the runs with SHA-1DC (see
BENCHMARK.md).
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.
Object decoding: objects
Step 1 of #23 (no git
binary): the inflated content of an object, decoded.
c, err := objects.DecodeCommit(data) // Tree, Parents, Author, Committer (Name,
// Email, When, TZ as written), Headers
// (gpgsig, mergetag, encoding, verbatim),
// Message
t, err := objects.DecodeTag(data) // Target, TargetType, Name, Tagger (nil on
// an old tag), Message, Signature
tr, err := objects.DecodeTree(data) // Entries: Mode, Name, ID
id, err := objects.ComputeHash(objects.SHA1, objects.Blob, data) // "blob <len>\0"
h, err := objects.NewHasher(objects.SHA1, objects.Blob, size) // streamed
Modes are ModeRegular, ModeExecutable, ModeSymlink, ModeDir,
ModeSubmodule and the legacy ModeDeprecated (100664); Mode.Canonical gives
what git writes today, and IsDir, IsRegular, IsSymlink, IsGitlink tell
the kind. A tree name that is empty, ., .. or holds / or NUL is refused.
The decoders keep one invariant: DecodeX(b) either fails or returns a value
whose Encode() is b, byte for byte (a fuzz property of all three). Two
different objects, which are two different ids, never decode to the same value,
and re-encoding a decoded object never hashes another one. The price: what git
reads but would not write is refused with ErrNonCanonical (which also wraps
ErrCorrupt): a zero-padded mode (040000) or date, a commit or tag without
the blank line after its headers, a header with no space, an identity with no
space before <. Such an object stays readable as bytes, and ComputeHash gives
its id. Encode returns an error and refuses what the decoders refuse (LF, <
or > in a name or email, a bad zone, a header key with a space or LF, a bad
tree mode or name, a signature that does not split back), so it only emits what
Decode reads back as the same value. A tag's signature starts at the LAST line
that begins a PGP, SSH or X.509 block, as git's parse_signed_buffer does. The
tests check Encode against git cat-file -p on this repository and on a
synthetic one with -0130 zones, a gpgsig, a mergetag, an encoding header
and an old tag with no tagger. The strict fsck rules (entry order, .git
spellings) stay in packfile.ParseObject; sharing its name check is a follow-up
once the packfile pull request lands. ComputeHash refuses a type that is not
commit, tree, blob or tag (ErrType).
Bounds: an object over MaxObjectBytes (64 MiB), a tree over MaxTreeEntries
(2^20), or more than MaxHeaders extra commit headers, is refused with
ErrLimit; malformed input is ErrCorrupt (both wrap the packfile errors).
ComputeHash uses SHA-1DC and reports packfile.ErrCollision. Algo is the
hook for SHA-256: it will come with a wider id type. Every decoder has a fuzz
target (FuzzDecodeCommit, FuzzDecodeTag, FuzzDecodeTree,
FuzzComputeHash) with a committed corpus, and the Bomb tests assert the
refusals under GOMEMLIMIT in CI. BenchmarkDecode reads
GITPROTO_BENCH_REPO.
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.