deb

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 41 Imported by: 3 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

deb

Debian packages and apt repositories, in pure Go. No dpkg, ar or apt is needed.

github.com/M0Rf30/pkgformat/deb        packages, control files, versions, indexes, Release, signing
github.com/M0Rf30/pkgformat/deb/apt    apt client: update, load, resolve, download

What it does

Area API
Write a .deb Write, WriteFile with a plain Spec and []Entry (or FSEntries over an fs.FS)
Read a .deb ParseDebFileAt, ParseDebFile, (*DebFile).Extract, OpenData, Conffiles, Triggers, Shlibs, Symbols, Signatures
Sign a .deb SignPackage (debsigs _gpgorigin for debsig-verify, dpkg-sig _gpgbuilder manifests), (*DebFile).VerifySignatures, DebsigPolicy (policy file for debsig-verify)
deb822 ParseControlFile (strict, one paragraph), ScanControl (lenient, every paragraph), ControlFile
Versions CompareVersions (the dpkg algorithm), ValidVersion, StripEpoch
Relations ParseRelations (keeps :any/:native qualifiers, [arch] and <profile> restrictions), FormatRelations, Relation.AppliesTo, ActiveRelations, ArchMatches (architecture wildcards), DependencyNames, NormalizeDependency
Installed packages FindStatus, OpenStatus, (*StatusDB): Entries, List, InstalledNames, InstalledProvides; ParseStatus; ReadInfoList for /var/lib/dpkg/info/*.list
Repository indexes Index (Packages writer, plain and compressed), ScanPackages, OpenIndex (gz, bz2, xz, lz4, zst)
Release Release (every field, Debian and apt-ftparchive layouts), ParseRelease, SignRelease, Trust (InRelease and Release.gpg verification policy)
by-hash, Contents, Translations WriteByHash, PruneByHash; ContentsBuilder, ScanContents; TranslationBuilder, ScanTranslation, I18nIndex (see REPOSITORY.md)
Packages.diff ParsePDiffIndex, ApplyPDiffChain, GeneratePDiff, MergePDiffs, PDiffIndexBuilder (see PDIFF.md)
apt client apt.Update (by-hash, pdiffs, translations, Contents, Sources; http, https, file, copy, mirror+ sources), apt.Load, (*apt.Cache): Lookup, Candidate, ResolveVirtual, ResolveDeps, Plan, Download, DownloadClosure
apt sources and policy apt.ParseSourcesList, ParseSources822 (every option, Signed-By forms), apt.ParsePreferences, NewPolicy (pins, phased updates, apt's priorities)

Compression of written packages: gzip, xz, zstd (default) or none. Index decoders also read bzip2 and lz4.

Source packages, .dsc, .changes, .buildinfo and Sources indexes are in the deb/source package.

The apt client

srcs, err := apt.LoadSources("/etc/apt/sources.list", "/etc/apt/sources.list.d") // every sources.list and deb822 option
n, err := apt.Update(ctx, srcs, apt.UpdateOptions{ListsDir: lists, DefaultArch: "amd64"})

cache, err := apt.Load(apt.LoadOptions{ListsDir: lists, StatusFile: "/var/lib/dpkg/status", Sources: srcs})
prefs, err := apt.LoadPreferences("/etc/apt/preferences", "/etc/apt/preferences.d")
policy := apt.NewPolicy(prefs, apt.PolicyOptions{DefaultRelease: "stable", MachineID: id})

plan, err := cache.Plan(apt.PlanRequest{Install: []string{"nginx"}}, apt.PlanOptions{Policy: policy})
err = cache.Download(ctx, dir, names, apt.DownloadOptions{})

Update follows what apt does for a source: it verifies the Release (Signed-By as a key file, a keyring directory or an inline block; Trusted, Allow-Insecure, Check-Valid-Until, Valid-Until-Min/Max, Check-Date), fetches the indexes by hash when the Release offers it, patches Packages with Packages.diff when that is cheaper than the whole file, and reads Translation-*, Contents-* and Sources as the source's Languages and Targets ask. file:, copy: and mirror+ sources work; cdrom: is a typed ErrUnsupportedScheme. Pins, -t releases and phased updates follow apt exactly and were checked against recorded apt 2.6, 3.0 and 3.3 output (deb/apt/testdata/policy, deb/apt/testdata/phased); Plan was checked against apt-get -s (deb/apt/testdata/diff); Update against a real apt-get update (deb/apt/testdata/e2e-update).

Design

  • The writer takes plain structs. Spec carries the control fields, scripts, conffiles, Multi-Arch, debconf and the compression. Nothing in the package knows any build recipe format.
  • Output is deterministic. Entries are written in the order given, modification times come from Spec.ModTime and Entry.ModTime, owners are root:root, and a given input gives the same bytes. dpkg-deb -I, -c, -x and md5sum -c accept the result.
  • Untrusted input is bounded. Package size, control archive, control file, lines, paragraphs, indexes (decompressed), Releases, extraction size and entry count each have a limit, exported as a constant. Hitting one gives a typed error (ErrDebFileTooLarge, ErrTooLarge, ...). Parsers do not panic; every entry point has a fuzz target.
  • Extraction cannot escape. Extract resolves every path under the target directory, including symlink chains (see the safepath package).
  • Errors are values. fmt.Errorf("deb: ...: %w") with exported sentinels; errors.Is works.
  • No globals, no host paths. The apt client takes the lists directory, the dpkg status file, the keyring paths and the HTTP client as options. *slog.Logger is optional.

The installed database

OpenStatus (or NewStatusDB over an io.ReaderAt) reads a dpkg status file read-only, in bounded memory, one stanza at a time. FindStatus("/") gives the path under a root. Each StatusEntry has the parsed Package, the Status split into want, flag and state (install ok installed), and the ControlFile with every field, which ControlFile.String writes back as dpkg wrote it (a Conffiles: list included).

Status.Installed() is true only when the state is installed, as in apt's and dpkg's own notion of an installed package: a package that is unpacked, half-configured, half-installed, triggers-awaited, triggers-pending or config-files (removed, configuration kept) is not. The want does not matter, so a package on hold is installed. InstalledNames and InstalledProvides count those only; the provides include the names of versioned provides (Provides: foo (= 1) gives foo) and the name of the package itself, and names carry no architecture qualifier. ReadInfoList reads the file list <name>:<arch>.list (or <name>.list) from an fs.FS rooted at /var/lib/dpkg/info. A stanza with no Package is skipped and logged at debug level; the file size and the number of stanzas are limits (StatusOptions.MaxBytes, MaxEntries).

Verification policy

Trust implements what apt does, with one strict rule:

  • a signature that exists and does not verify (altered data, expired or revoked key) is always an error, even with AllowUnverified;
  • no keys, an unknown signer, or no signature at all are errors unless AllowUnverified is set, which accepts the document and logs a warning;
  • Valid-Until is checked separately by Release.CheckValidity; apt.Update calls it with UpdateOptions.Now.

apt.IsVerificationError separates these trust failures from network ones in the joined error Update returns.

Package signatures

SignPackage copies a package and appends one signature member; it takes any gpg.Signer, so the key can live in a KMS or an agent.

  • SchemeDebsigs (default, role origin): _gpgorigin holds a detached signature of debian-binary, the control archive and the data archive concatenated. DebsigPolicy.Marshal renders the .pol file debsig-verify needs next to a keyring of the public key.
  • SchemeDpkgSig (role builder by default): _gpgbuilder holds a clear-signed manifest with the size, MD5 and SHA-1 of each core member, as dpkg-sig writes it. Signing again picks the suffixes 0-9, A-Z like dpkg-sig.

(*DebFile).VerifySignatures(keyring) checks every _gpg* member and returns one PackageSignature each. A member that does not verify fails with ErrInvalidPackageSignature (and gpg.ErrUnknownSigner for a key outside the keyring); no member at all is ErrNoPackageSignature. The caller decides which keys to trust.

dpkg-sig and debsig-verify reject what they cannot read: dpkg-sig --verify knows only gzip, xz and bzip2 members, and debsig-verify rejects SHA-1 signatures, which gpg.Signer implementations here do not make. testdata/sign holds packages signed by the reference tools and generate.sh rebuilds them in a Debian container; the tests also hand packages signed by this module to debsig-verify and dpkg-sig there.

Behaviour to know

  • deb822 values are logical: the continuation marker is removed and a " ." line is an empty line. ControlFile.String and the Packages writer re-encode them.
  • The writer rejects field values containing a newline (it would inject fields).
  • Control files and tar entries use ./ prefixes, as dpkg-deb does. Installed-Size is computed from the payload.
  • Package names must match ^[a-z0-9][a-z0-9+.-]+$.
  • Release.PackagesVariants lists the variants a Release declares, best compression first (.xz, .zst, .gz, .bz2, .lz4, plain); apt.Update only fetches a variant whose SHA-256 the verified Release lists.
  • The apt cache keys entries by name:arch; architecture all lives under the bare name. Every version the indexes carry is kept, the highest is the candidate (Lookup), Versions lists them all.
  • ResolveDeps honours version constraints, alternatives, versioned and unversioned Provides, Pre-Depends, Conflicts/Breaks in both directions (ConflictError) and Multi-Arch (foreign, allowed, same, :any, :native, :arch). A dependency nothing satisfies is an UnsatisfiedError. Installed packages are never removed (apt would remove one a candidate conflicts with); an installed package whose exact-version dependency an upgrade breaks (binutils on binutils-common (= v)) is upgraded along, as apt does; apt/testdata/diff compares the result with apt-get install -s for a set of real packages.
  • A plain-http transfer that fails transiently is retried once over https.

Not included

Writing the dpkg status database and running maintainer scripts are the installer's job and live outside this module. The status reader is read only.

Documentation

Overview

Package deb reads, writes and indexes Debian binary packages and the metadata of apt repositories.

Writing packages

A Spec describes the package (name, version, relationships, maintainer scripts, conffiles, copyright data) and a list of Entry values describes its payload. Write streams the package to an io.Writer and WriteFile replaces a file atomically. The payload is staged in a temporary file, so a package of any size is written in bounded memory; set WriteOptions.TempDir to choose where. Entries carry their content as bytes or as an Open function, and FSEntries lists an fs.FS as entries. Output is reproducible: nothing but the Spec, the entries and their modification times goes into the package, and Spec.ModTime overrides the time of entries that have none.

Reading packages

ParseDebFileAt and ParseDebFile read the ar container and the control archive of a package given as an io.ReaderAt, in gzip, xz, zstd, bzip2 or uncompressed form, and return a DebFile with the parsed control file, the maintainer scripts and the md5sums. Reading is bounded: the size of the package, of the control archive and of its files are limited, and ParseOptions adjusts the limits. DebFile.OpenData streams the payload and DebFile.Extract unpacks it into a directory; Extract refuses entries that would be written outside the directory, whether by their name, by a link or by writing through a link it created earlier, and bounds the number of entries and the number of bytes.

Control files, versions and relations

ControlFile is a parsed deb822 paragraph that keeps the order of its fields. ParseControlFile is strict and reads the first paragraph; ScanControl is lenient and visits every paragraph. Package extracts the common fields. CompareVersions orders versions as dpkg does, ValidVersion and StripEpoch help with their syntax, and ParseRelations reads a dependency field into alternatives with an optional architecture qualifier ("foo:any", "foo:native"), version constraint, architecture restriction ("[amd64 !i386 linux-any]") and build-profile restrictions ("<!nocheck> <stage1 cross>"). Relation.Satisfied checks the constraint against a version, Relation.AppliesTo and ActiveRelations evaluate the restrictions for a host architecture and a set of build profiles the way dpkg-checkbuilddeps does, ArchMatches matches architecture wildcards ("linux-any", "any-amd64") as dpkg-architecture does, and Relation.String and FormatRelations write the canonical control-file syntax back. NormalizeDependency converts a "name>=version" dependency to control-file syntax.

Installed packages

OpenStatus and NewStatusDB read a dpkg status file, bounded and read-only. StatusDB.Entries yields each stanza as a StatusEntry: the parsed Package, the Status (want, flag and state, as in "install ok installed") and the ControlFile with every field. Status.Installed is true only for the state "installed", so packages that are unpacked, half-configured or removed with their configuration kept are not installed. StatusDB.InstalledNames and StatusDB.InstalledProvides list the installed names and capabilities, and ReadInfoList reads a package's file list from /var/lib/dpkg/info.

Repository indexes and Release files

Index builds a Packages file from IndexEntry values (EntryFromControl makes one from a control file and the file facts HashReader computes) or from ready-made stanzas, and renders it plain or compressed with gzip, xz or zstd. ScanPackages and OpenIndex read an index back in any of the formats apt uses, with the size of the decompressed data bounded. Release lists the files of a distribution with their digests; Marshal renders it and ParseRelease reads a Release or an InRelease document, rejecting digests of the wrong length, paths that are not plain relative paths and contradicting sizes. Release.CheckValidity applies Valid-Until. The path helpers (PoolPath, PackagesPath, ReleasePath, ...) give the conventional locations.

Release reads and writes every field apt knows (Acquire-By-Hash, NotAutomatic, ButAutomaticUpgrades, Signed-By, No-Support-for-Architecture-All, Changelogs, Snapshots, ...), in the layout of Debian's archive or of apt-ftparchive (MarshalStyle). WriteByHash lays out the by-hash tree next to the indexes, PlanByHashPrune and PruneByHash apply a retention policy to it, and Release.ByHashRefs gives the by-hash path of a listed file. ContentsBuilder and ScanContents write and read Contents files, and TranslationBuilder, ScanTranslation and I18nIndex the Translation files with their i18n/Index. See REPOSITORY.md.

Packages.diff

ParsePDiffIndex reads a Packages.diff/Index, PDiffIndex.Chain finds the patches that lead from a file by its SHA-256 to the current one, and ApplyPDiffChain downloads and applies them, checking every digest on the way. GeneratePDiff makes the ed-style patch between two files, MergePDiffs collapses a series into one, and PDiffIndexBuilder maintains the whole Packages.diff directory of a repository the way dak does. See PDIFF.md.

Signing and verification

SignRelease signs a Release document with a gpg.Signer and returns the three files apt fetches: Release, InRelease and Release.gpg. Trust holds the policy for the other direction, VerifyInRelease and VerifyReleaseGPG:

  • a signature that exists and does not verify is always an error, even with AllowUnverified, because it points to tampering or a broken mirror;
  • no keyring, a signature by a key outside the keyring, and no signature at all are errors unless AllowUnverified is set, in which case the document is accepted and a warning goes to Logger.

Packages are signed with SignPackage: SchemeDebsigs appends the _gpgorigin member debsig-verify checks (DebsigPolicy renders its policy file), SchemeDpkgSig the clear-signed manifest dpkg-sig writes. DebFile.Signatures holds the members of a parsed package and DebFile.VerifySignatures checks them against a gpg.Keyring.

Nothing in this package reads keys from the host: the caller supplies the gpg.Keyring and decides what to trust.

The subpackage deb/apt resolves and downloads packages from such repositories.

Index

Examples

Constants

View Source
const (
	// ArchAny is the wildcard that matches every architecture, and the ":any"
	// qualifier of a relation.
	ArchAny = "any"
	// ArchNative is the ":native" qualifier of a relation: the architecture
	// of the system that runs the build.
	ArchNative = "native"
	// ArchAll is the Architecture value of a package that is the same on
	// every architecture.
	ArchAll = "all"
)

Wildcard and qualifier spellings of Debian architectures.

View Source
const (
	// MaxGzipLevel is the best (slowest) gzip level; the lowest is 1.
	MaxGzipLevel = 9
	// MaxXZLevel is the best xz level; the lowest is 1.
	MaxXZLevel = 9
	// MaxZstdLevel is the highest zstd level; the lowest is 1. The encoder
	// groups the levels into four speed classes, like zstd's own presets.
	MaxZstdLevel = 22
)

Valid compression levels of each method. Level 0 always selects the default of the method.

View Source
const (
	// MaxContentsFiles bounds the files ParseContents and
	// ContentsBuilder.AddReader accept. The Contents index of a large Debian
	// architecture lists some ten million.
	MaxContentsFiles = 1 << 25
	// MaxContentsLocations bounds the packages that one file of a Contents
	// index lists.
	MaxContentsLocations = 1 << 16
)
View Source
const (
	// MaxLineBytes bounds one line of a deb822 document; a hostile index could
	// otherwise send one enormous line.
	MaxLineBytes = 4 << 20
	// MaxParagraphBytes bounds one paragraph (one package entry).
	MaxParagraphBytes = 16 << 20
)
View Source
const (
	// DefaultMaxExtractBytes is the default limit on the bytes Extract writes.
	DefaultMaxExtractBytes int64 = 16 << 30
	// DefaultMaxExtractEntries is the default limit on the archive entries
	// Extract processes.
	DefaultMaxExtractEntries = 1 << 20
)
View Source
const (
	// MaxDebFileSize is the default limit on the size of a .deb file read by
	// ParseDebFileAt.
	MaxDebFileSize = 500 << 20

	// MaxControlArchiveSize caps the decompressed size of a control archive
	// (control.tar.{gz,xz,zst}). Without a cap, reading the decompressor to the
	// end lets a small compressed payload exhaust memory.
	MaxControlArchiveSize = 64 << 20

	// MaxControlFileSize caps one file of the control archive. md5sums grows
	// with the file count: Ubuntu's libboost1.74-dev ships a 1.2 MiB one and
	// the largest archive packages reach several MiB.
	MaxControlFileSize = 32 << 20

	// MaxSignatureSize caps one package signature member.
	MaxSignatureSize = 1 << 20
)
View Source
const (
	// DefaultMaxPDiffPatchBytes is the default bound on a decompressed patch.
	DefaultMaxPDiffPatchBytes int64 = 256 << 20
	// DefaultMaxPDiffCommands is the default bound on the commands of a patch.
	DefaultMaxPDiffCommands = 1 << 21
)

Default limits of PDiffApplyOptions.

View Source
const (
	// DefaultMaxPDiffLines is the default bound on the lines of either file.
	DefaultMaxPDiffLines = 1 << 24
	// DefaultMaxPDiffEditDistance is the default bound on the edit distance
	// GeneratePDiff searches for.
	DefaultMaxPDiffEditDistance = 1 << 16
)

Default limits of PDiffGenerateOptions.

View Source
const (
	// IndexPackages is the Packages index of the binary packages of an
	// architecture: <comp>/binary-<arch>/Packages.
	IndexPackages = "Packages"
	// IndexPackagesUdeb is the Packages index of the udebs of an architecture:
	// <comp>/debian-installer/binary-<arch>/Packages.
	IndexPackagesUdeb = "Packages-udeb"
	// IndexSources is the Sources index of a component: <comp>/source/Sources.
	IndexSources = "Sources"
	// IndexContents is the Contents index of an architecture: <comp>/Contents-<arch>,
	// or Contents-<arch> for the whole distribution when comp is empty.
	IndexContents = "Contents"
	// IndexContentsUdeb is the Contents index of the udebs: Contents-udeb-<arch>.
	IndexContentsUdeb = "Contents-udeb"
	// IndexTranslationPrefix starts the kind of a Translation index:
	// IndexTranslationPrefix+"de" is <comp>/i18n/Translation-de.
	IndexTranslationPrefix = "Translation-"
)

The kinds of index a Release lists, as IndexPath and Release.IndexPaths take them. Translation indexes are named by language: "Translation-de".

View Source
const (
	// DefaultMaxStatusEntries bounds the stanzas of a status file.
	DefaultMaxStatusEntries = 1 << 20
	// DefaultMaxStatusBytes bounds the size of a status file, and of one
	// package's list file. A system with thousands of packages has a few
	// megabytes.
	DefaultMaxStatusBytes int64 = 256 << 20
)

Default limits of the status reader, applied where a StatusOptions field is zero.

View Source
const DebsigPolicyKeyring = "debsig.gpg"

DebsigPolicyKeyring is the keyring file name a DebsigPolicy refers to when none is given.

View Source
const (
	// DefaultPDiffMaxPatches is how many patches dak keeps in a series.
	DefaultPDiffMaxPatches = 56
)

Defaults of PDiffBuilderOptions.

View Source
const MaxIndexBytes int64 = 4 << 30

MaxIndexBytes bounds the decompressed size of one Packages (or Sources) index. The largest real ones are a few hundred MiB.

View Source
const (
	// MaxPDiffIndexBytes bounds the size of a Packages.diff/Index document. Real
	// ones are tens of kilobytes.
	MaxPDiffIndexBytes = 8 << 20
)

Limits of the Packages.diff/Index parser.

View Source
const (
	// MaxReleaseBytes bounds a Release or InRelease document.
	MaxReleaseBytes = 16 << 20
)
View Source
const MaxTranslationEntries = 1 << 22

MaxTranslationEntries bounds the descriptions ParseTranslation reads.

View Source
const RemoveScriptHeader = `#!/bin/bash
case $1 in
    purge|remove|abort-install) ;;
    *) exit;;
esac
`

RemoveScriptHeader is prepended to the prerm and postrm scripts: it makes them return at once unless dpkg runs them for a removal, a purge or an aborted installation.

View Source
const SourceDateEpochVar = "SOURCE_DATE_EPOCH"

SourceDateEpochVar is the environment variable of the reproducible-builds convention that carries the time packages are stamped with.

Variables

View Source
var (
	// ErrInvalidPackage wraps every structural problem found in a .deb file.
	ErrInvalidPackage = errors.New("deb: invalid package")

	// ErrInvalidARMagic is returned when a file does not start with the ar magic.
	ErrInvalidARMagic = errors.New("deb: invalid ar archive magic")
	// ErrInvalidHeaderSize is returned for an ar member header that is not 60 bytes.
	ErrInvalidHeaderSize = errors.New("deb: invalid ar header size")
	// ErrInvalidModTime is returned for an unparsable ar modification time.
	ErrInvalidModTime = errors.New("deb: invalid ar modification time")
	// ErrInvalidOwnerID is returned for an unparsable ar owner id.
	ErrInvalidOwnerID = errors.New("deb: invalid ar owner id")
	// ErrInvalidGroupID is returned for an unparsable ar group id.
	ErrInvalidGroupID = errors.New("deb: invalid ar group id")
	// ErrInvalidMode is returned for an unparsable ar mode.
	ErrInvalidMode = errors.New("deb: invalid ar mode")
	// ErrInvalidSize is returned for an unparsable or negative ar member size.
	ErrInvalidSize = errors.New("deb: invalid ar member size")
	// ErrARMemberTooLarge is returned for a member that is larger than the file
	// holding it or than the limit for its kind.
	ErrARMemberTooLarge = errors.New("deb: ar member size exceeds maximum allowed")
	// ErrInvalidARHeaderEnd is returned when an ar header lacks its "`\n" trailer.
	ErrInvalidARHeaderEnd = errors.New("deb: invalid ar header ending marker")
	// ErrTooManyMembers is returned for an ar archive with more members than a .deb needs.
	ErrTooManyMembers = errors.New("deb: too many ar members")

	// ErrInvalidControlFormat is returned for a malformed deb822 paragraph.
	ErrInvalidControlFormat = errors.New("deb: invalid control file format")
	// ErrMissingRequiredField is returned when a mandatory control field is absent or empty.
	ErrMissingRequiredField = errors.New("deb: required field not found in control file")

	// ErrControlArchiveNotFound is returned when a .deb has no control.tar member.
	ErrControlArchiveNotFound = errors.New("deb: control archive not found in deb file")
	// ErrDataArchiveNotFound is returned when a .deb has no data.tar member.
	ErrDataArchiveNotFound = errors.New("deb: data archive not found in deb file")
	// ErrUnsupportedArchiveFormat is returned for a member with an unknown compression suffix.
	ErrUnsupportedArchiveFormat = errors.New("deb: unsupported archive compression")
	// ErrFileNotFoundInTar is returned when a wanted file is not in a tar archive.
	ErrFileNotFoundInTar = errors.New("deb: file not found in tar archive")

	// ErrDebFileTooLarge is returned for a .deb over MaxDebFileSize.
	ErrDebFileTooLarge = errors.New("deb: deb file exceeds max size")
	// ErrControlArchiveTooLarge is returned for a control archive that
	// decompresses to more than MaxControlArchiveSize.
	ErrControlArchiveTooLarge = errors.New("deb: control archive exceeds max decompressed size")
	// ErrControlFileTooLarge is returned for a control file over MaxControlFileSize.
	ErrControlFileTooLarge = errors.New("deb: control file exceeds max size")
	// ErrTooLarge is returned when a text input (a line, a paragraph, an index,
	// a Release file) is over its size limit.
	ErrTooLarge = errors.New("deb: input exceeds size limit")
	// ErrDataTooLarge is returned when extracting a data archive would exceed the
	// configured byte or entry limit.
	ErrDataTooLarge = errors.New("deb: data archive exceeds extraction limit")
	// ErrUnsafeEntry is returned for a data archive entry that would be written
	// outside the extraction directory.
	ErrUnsafeEntry = errors.New("deb: unsafe archive entry")

	// ErrInvalidRelease is returned for a malformed Release file.
	ErrInvalidRelease = errors.New("deb: invalid release file")

	// ErrInvalidSpec is returned by the package writer for a Spec that cannot
	// be turned into a valid .deb.
	ErrInvalidSpec = errors.New("deb: invalid package spec")
	// ErrUnsupportedEntryType is returned by the package writer for a payload
	// entry of a type a tar archive cannot hold, such as a socket.
	ErrUnsupportedEntryType = errors.New("deb: unsupported entry type")
	// ErrUnsupportedCompression is returned for a compression name the writer
	// does not know.
	ErrUnsupportedCompression = errors.New("deb: unsupported compression")
)

Sentinel errors. Functions wrap them with context, so match with errors.Is.

View Source
var (
	// ErrPDiffIndex is wrapped by every error ParsePDiffIndex returns, and by
	// PDiffIndex methods that find the Index unusable.
	ErrPDiffIndex = errors.New("deb: invalid pdiff index")
	// ErrPDiffNoPath is returned by PDiffIndex.Chain for a file that is neither
	// the current one nor listed in the history: no patch series leads from it
	// to the current file, and the full index must be fetched instead.
	ErrPDiffNoPath = errors.New("deb: no pdiff path from the local file to the current one")
	// ErrPDiffScript is wrapped by the *PDiffError of a malformed edit script
	// or of one that does not fit the file it is applied to.
	ErrPDiffScript = errors.New("deb: invalid pdiff edit script")
	// ErrPDiffLimit is wrapped by the *PDiffError of a script or result that
	// exceeds a limit of PDiffApplyOptions.
	ErrPDiffLimit = errors.New("deb: pdiff limit exceeded")
	// ErrPDiffHash is returned when a patch, a patched file or a downloaded
	// patch does not have the digest the Index lists for it.
	ErrPDiffHash = errors.New("deb: pdiff digest mismatch")
	// ErrPDiffUnrepresentable is returned by GeneratePDiff for a change an
	// ed-script patch cannot express: new text with a line that is just "." or
	// without a final newline.
	ErrPDiffUnrepresentable = errors.New("deb: change cannot be expressed as a pdiff")
)

Errors of the pdiff (Packages.diff) support. Malformed edit scripts are reported as a *PDiffError that wraps ErrPDiffScript or ErrPDiffLimit.

View Source
var (
	// ErrNoPackageSignature is returned by VerifySignatures for a package that
	// carries no signature member.
	ErrNoPackageSignature = errors.New("deb: package carries no signature")
	// ErrInvalidPackageSignature is returned when a signature member does not
	// match the package or is malformed. The cause stays in the chain.
	ErrInvalidPackageSignature = errors.New("deb: invalid package signature")
	// ErrSignatureExists is returned when the package already holds a
	// signature member of the requested name.
	ErrSignatureExists = errors.New("deb: package already carries this signature")
	// ErrInvalidSignRole is returned for a signing role that cannot form a
	// member name.
	ErrInvalidSignRole = errors.New("deb: invalid signing role")
)

Sentinel errors of package signing. Test with errors.Is.

View Source
var (
	// ErrStatusNotFound means [FindStatus] met no dpkg status database under
	// the root.
	ErrStatusNotFound = errors.New("deb: no dpkg status database found")
	// ErrInvalidStatus means a Status field, or a status file, is not what
	// dpkg writes.
	ErrInvalidStatus = errors.New("deb: invalid dpkg status")
)

Errors of the dpkg status reader, besides ErrTooLarge. Test with errors.Is.

View Source
var (
	// ErrNoTrustAnchor is returned when there is no keyring to verify a Release
	// with. The caller decides whether to treat it as fatal or, with
	// Trust.AllowUnverified, to go on.
	ErrNoTrustAnchor = errors.New("deb: no usable trust anchor for source")
	// ErrUnsigned is returned when a Release carries no signature at all.
	ErrUnsigned = fmt.Errorf("deb: release file is not signed: %w", gpg.ErrUnsigned)
	// ErrUnknownSigner is returned when a Release is signed by a key outside the
	// keyring. It is gpg.ErrUnknownSigner.
	ErrUnknownSigner = gpg.ErrUnknownSigner
)
View Source
var ErrByHashMismatch = errors.New("deb: by-hash file does not match its listed digest")

ErrByHashMismatch is returned by WriteByHash for an index whose content does not match the digest the Release lists for it: publishing it would put a file under a hash it does not have.

View Source
var ErrInvalidContents = errors.New("deb: invalid contents entry")

ErrInvalidContents is returned for a file or package name that cannot be written to a Contents index, such as a package name that holds a blank or a comma.

View Source
var ErrInvalidTranslation = errors.New("deb: invalid translation")

ErrInvalidTranslation is returned for a language or entry that cannot be written to a Translation file.

View Source
var ErrNoSigner = errors.New("deb: no signer configured")

ErrNoSigner is returned by SignRelease when no signer is given.

View Source
var ErrReleaseExpired = errors.New("deb: release file has expired")

ErrReleaseExpired is returned by Release.CheckValidity for a Release whose Valid-Until date is in the past.

Functions

func ApplyPDiff added in v0.4.0

func ApplyPDiff(base, patch []byte) ([]byte, error)

ApplyPDiff applies the ed script patch to base, as apt's rred does for a Packages.diff patch, and returns the patched file. It is ApplyPDiffWith with the default limits.

Example
package main

import (
	"fmt"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	base := []byte("Package: a\nPackage: b\nPackage: c\n")
	patch := []byte("3c\nPackage: C\n.\n1a\nPackage: a2\n.\n")

	out, err := deb.ApplyPDiff(base, patch)
	if err != nil {
		panic(err)
	}

	fmt.Print(string(out))
}
Output:
Package: a
Package: a2
Package: b
Package: C

func ApplyPDiffChain added in v0.4.0

func ApplyPDiffChain(base []byte, chain []PDiffPatch, fetch PDiffFetcher, opts PDiffApplyOptions) ([]byte, error)

ApplyPDiffChain turns base into the file at the end of chain, the result of PDiffIndex.Chain. For each patch it fetches the gzip download, checks its size and SHA-256 against the Index, decompresses it within the patch size limit, checks the script's size and SHA-256, applies it, and checks the patched file against the patch's To digest, so every intermediate file is verified and a poisoned patch is never carried forward. A mismatch is a *PDiffHashError (errors.Is ErrPDiffHash). An empty chain returns base.

func ApplyPDiffTo added in v0.4.0

func ApplyPDiffTo(dst io.Writer, base, patch io.Reader, opts PDiffApplyOptions) (int64, error)

ApplyPDiffTo applies the ed script read from patch to base and writes the result to dst, returning the bytes written. The script is read whole, up to MaxPatchSize; the base is streamed line by line, so memory stays bounded by the script plus a buffer however large the file is. dst may hold a partial result when an error is returned.

Malformed scripts, scripts whose commands address lines beyond the end of base, and scripts or results over a limit fail with a *PDiffError.

func ApplyPDiffWith added in v0.4.0

func ApplyPDiffWith(base, patch []byte, opts PDiffApplyOptions) ([]byte, error)

ApplyPDiffWith is ApplyPDiff with explicit limits.

func ArchMatches added in v0.3.1

func ArchMatches(arch, pattern string) bool

ArchMatches reports whether the Debian architecture arch ("amd64", "armhf") is the architecture pattern names, or belongs to the wildcard it is: "any", "linux-any", "any-amd64", "gnu-linux-any" and so on, with the semantics of dpkg-architecture -i. An architecture matches itself even when it is not one dpkg knows.

func ArchRestrictionApplies added in v0.3.1

func ArchRestrictionApplies(hostArch string, terms []Restriction) bool

ArchRestrictionApplies reports whether the architecture list of a relation ("[amd64 !i386]") selects hostArch. No restriction selects every architecture. The terms are read as dpkg reads them: the first positive term that matches selects the architecture, a negative term that matches rejects it, and a list of only negative terms selects what none of them matches. Names are compared without regard to case.

func ByHashPath added in v0.4.0

func ByHashPath(indexPath string, alg ByHashAlgorithm, digest string) string

ByHashPath returns where the by-hash copy of an index lives: next to the index, under by-hash/<algorithm>/<digest>. indexPath is relative to a dists/<dist> directory ("main/binary-amd64/Packages.xz"), and so is the result ("main/binary-amd64/by-hash/SHA256/<digest>"). digest is lowercased.

func CompareVersions

func CompareVersions(a, b string) int

CompareVersions compares two Debian version strings the way dpkg does (see deb-version(7)) and returns -1, 0 or +1. The versions are split into [epoch:]upstream[-revision], then upstream and revision are compared by alternating non-digit and digit chunks. In a non-digit chunk '~' sorts before everything, even the end of the chunk, then letters, then other characters. An empty version sorts lowest.

Example
package main

import (
	"fmt"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	fmt.Println(deb.CompareVersions("1.0~rc1", "1.0"))
	fmt.Println(deb.CompareVersions("1:0.9", "2.0"))
	fmt.Println(deb.CompareVersions("1.10", "1.9"))
	fmt.Println(deb.CompareVersions("2.0-1", "2.0-1"))
}
Output:
-1
1
1
0

func ContentsFileName added in v0.4.0

func ContentsFileName(arch string, udeb bool, ext string) string

ContentsFileName is the file name of a Contents index: "Contents-amd64" for the packages of an architecture, "Contents-udeb-amd64" for its udebs, with ext (".gz", ".xz", "") appended. In a repository it lives in dists/<dist> and in each component directory (main/Contents-amd64.gz).

func ContentsLocation added in v0.4.0

func ContentsLocation(cf *ControlFile) string

ContentsLocation is the name a package goes by in a Contents file: "section/name", or just the name for a package without a Section, as apt-ftparchive generate and dak write it.

func ControlFieldsToStore

func ControlFieldsToStore(fields map[string]string) map[string]string

ControlFieldsToStore returns the subset of control fields worth keeping to render an index entry later: everything but the fields the repository derives from the file (the description is kept).

func DebContentsFiles added in v0.4.0

func DebContentsFiles(d *DebFile) ([]string, error)

DebContentsFiles lists the files a package contains: the regular files, symbolic and hard links and special files of its data archive, not the directories, without the leading "./". It fails with ErrTooLarge for a package with an absurd number of members.

func DependencyNames

func DependencyNames(field string) []string

DependencyNames returns the package names of a dependency field the way a resolver that ignores versions needs them: the first alternative of every entry, without version constraint or architecture qualifier.

func DescriptionMD5 added in v0.4.0

func DescriptionMD5(description string) string

DescriptionMD5 returns the Description-md5 of a description: the MD5 of the description as it is written in a Packages stanza, that is the short description, a newline, and every extended line with its leading blank and a newline ("short\n long\n .\n more\n"). description is the logical value, as ControlFile.Get returns it.

func FileName

func FileName(name, version, arch string) string

FileName is the file name of a binary package, name_version_arch.deb. The epoch is not part of it: "1:2.0-1" is written "2.0-1".

func FindStatus added in v0.3.1

func FindStatus(root string) (string, error)

FindStatus looks for the dpkg status file under root, the directory that holds the system's /var: "/" for the running host, or the root of an image or an install directory. Symbolic links are followed only inside root. It returns ErrStatusNotFound when there is no regular file.

func FormatPackagesEntry

func FormatPackagesEntry(e IndexEntry) string

FormatPackagesEntry renders a complete Packages stanza, terminated by a blank line, for the entry.

func FormatPackagesEntryShort added in v0.4.0

func FormatPackagesEntryShort(e IndexEntry) string

FormatPackagesEntryShort renders the stanza the way a repository that publishes Translation files does (apt-ftparchive with LongDescription false): the Description field holds the short description only, and a Description-md5 field keys the full one, which IndexEntry.TranslationEntry puts in Translation-en. An entry without a description is rendered as by FormatPackagesEntry.

func FormatRelations added in v0.3.1

func FormatRelations(rels []Alternatives) string

FormatRelations renders a dependency field the way ParseRelations reads it: entries separated by ", ", alternatives by " | ".

func FormatShlibs added in v0.4.0

func FormatShlibs(shlibs []Shlib) string

FormatShlibs renders shlibs as the content of a shlibs control file.

func FormatSymbols added in v0.4.0

func FormatSymbols(libs []SymbolsLibrary) string

FormatSymbols renders libraries as the content of a symbols control file.

func FormatTriggers added in v0.4.0

func FormatTriggers(triggers []Trigger) string

FormatTriggers renders triggers as the content of a triggers control file.

func GeneratePDiff added in v0.4.0

func GeneratePDiff(old, newData []byte) ([]byte, error)

GeneratePDiff returns the ed script that turns old into new, in the dialect apt's rred reads: "Na", "Nc", "N,Mc", "Nd" and "N,Md" commands from the end of the file to its start, as diff --ed writes them. The script is built from a shortest edit script over lines (Myers' O(ND) algorithm), so it is as small as the line-based edit distance allows unless the files differ by more than DefaultMaxPDiffEditDistance, where the stretches that differ are replaced whole. Identical files give an empty script.

New text a script cannot carry fails with ErrPDiffUnrepresentable: a line that is just ".", which would end the text of a command, and a final line without a newline.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	oldFile := []byte("a\nb\nc\nd\n")
	newFile := []byte("a\nB\nc\nd\ne\n")

	patch, err := deb.GeneratePDiff(oldFile, newFile)
	if err != nil {
		panic(err)
	}

	fmt.Print(string(patch))

	got, _ := deb.ApplyPDiff(oldFile, patch)
	fmt.Println(bytes.Equal(got, newFile))
}
Output:
4a
e
.
2c
B
.
true

func GeneratePDiffWith added in v0.4.0

func GeneratePDiffWith(old, newData []byte, opts PDiffGenerateOptions) ([]byte, error)

GeneratePDiffWith is GeneratePDiff with explicit limits.

func I18nIndexName added in v0.4.0

func I18nIndexName(comp string) string

I18nIndexName is the path of the index of the translations of a component, relative to dists/<dist>: "main/i18n/Index".

func InReleasePath

func InReleasePath(dist string) string

InReleasePath is the location of the clear-signed InRelease file.

func IndexPath added in v0.4.0

func IndexPath(comp, arch, kind string) string

IndexPath returns the path, relative to dists/<dist> and without a compression suffix, of the index of the given kind for a component and an architecture ("main/binary-amd64/Packages"). arch is ignored for the kinds that have none (Sources, Translation) and comp may be empty for Contents. It returns "" for an unknown kind, a missing component or architecture, or a language that is not a plain name.

func IsByHashPath added in v0.4.0

func IsByHashPath(p string) bool

IsByHashPath reports whether p is a path inside a by-hash tree.

func MarshalTranslation added in v0.4.0

func MarshalTranslation(lang string, entries []TranslationEntry) []byte

MarshalTranslation renders a Translation-<lang> file for the entries, in the order given: a paragraph per package with Package, Description-md5 and Description-<lang>. An entry without a DescriptionMD5 gets the md5 of its own description, which is the key only for English.

func MergePDiffs added in v0.4.0

func MergePDiffs(patches ...[]byte) ([]byte, error)

MergePDiffs combines patches into one that does the work of all of them: applying the result to a file gives what applying the patches in turn would. The first patch is the one applied first. This is what apt's rred does to merge the patches of a series, and what a server does to publish merged patches (X-Patch-Precedence: merged). It is MergePDiffsWith with the default limits.

Example
package main

import (
	"fmt"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	v0 := []byte("1\n2\n3\n")
	v1 := []byte("1\nx\n3\n")
	v2 := []byte("0\n1\nx\n")

	p1, _ := deb.GeneratePDiff(v0, v1)
	p2, _ := deb.GeneratePDiff(v1, v2)

	merged, err := deb.MergePDiffs(p1, p2)
	if err != nil {
		panic(err)
	}

	got, _ := deb.ApplyPDiff(v0, merged)
	fmt.Printf("%q\n", got)
}
Output:
"0\n1\nx\n"

func MergePDiffsWith added in v0.4.0

func MergePDiffsWith(opts PDiffApplyOptions, patches ...[]byte) ([]byte, error)

MergePDiffsWith is MergePDiffs with explicit limits; only MaxPatchSize and MaxCommands apply. The patches need not fit any particular file, but must fit each other: a patch that deletes or keeps lines the earlier ones did not leave there is not noticed here, only when the merged patch is applied.

func NormalizeDependency

func NormalizeDependency(dep string) string

NormalizeDependency rewrites a dependency written the way a PKGBUILD does ("gcc>=11", "libfoo>2.0") into control-file syntax ("gcc (>= 11)", "libfoo (>> 2.0)"). The obsolete bare ">" and "<" are spelled ">>" and "<<", as dpkg means "<=" and ">=" by them. A dependency that already has the "name (op version)" form, or has no operator, is returned unchanged.

func OpenIndex

func OpenIndex(r io.Reader, name string) (io.ReadCloser, error)

OpenIndex decompresses an apt index (Packages, Sources, Contents) read from r according to the extension of name: .gz, .bz2, .xz, .lz4, .zst or none. Reading more than MaxIndexBytes of decompressed data fails with ErrTooLarge. Closing the result closes r when it is an io.Closer.

func PDiffSHA256 added in v0.4.0

func PDiffSHA256(data []byte) string

PDiffSHA256 returns the lowercase hex SHA-256 of a file, the digest PDiffIndex.Chain is keyed by.

func PackagesPath

func PackagesPath(dist, component, arch, ext string) string

PackagesPath is the location of a Packages index relative to the repository root: dists/<dist>/<component>/binary-<arch>/Packages<ext>, where ext is "", ".gz", ".xz", ...

func ParseBool added in v0.4.0

func ParseBool(s string) (value, ok bool)

ParseBool reads the boolean spellings apt accepts in Release files and configuration: yes, true, with, on, enable and 1 are true; no, false, without, off, disable and 0 are false. ok is false for anything else.

func ParseTranslation added in v0.4.0

func ParseTranslation(r io.Reader, lang string) (map[string]TranslationEntry, error)

ParseTranslation reads a whole Translation file into a map from Description-md5 to the description in the language, which is how apt looks translations up. An entry without a Description-md5 is keyed by the md5 of its description, which only matches when the file is in English. More than MaxTranslationEntries entries fail with ErrTooLarge.

func PoolPath

func PoolPath(component, packageName, filename string) string

PoolPath renders the pool location of a package file inside a repository: pool/<component>/<prefix>/<package>/<filename>. The prefix is the first letter of the package name, or "lib" plus the fourth letter for lib* names (the layout apt expects). It is "" for an empty package name.

func ProfileRestrictionApplies added in v0.3.1

func ProfileRestrictionApplies(profiles []string, groups [][]Restriction) bool

ProfileRestrictionApplies reports whether the build-profile groups of a relation ("<!nocheck> <stage1 cross>") hold for the active profiles. The groups are alternatives and the terms of a group are all required; a term holds when its profile is active, or, negated, when it is not. No group holds always.

func PruneByHash added in v0.4.0

func PruneByHash(distDir string, current *Release, pol ByHashRetention) ([]string, error)

PruneByHash removes the by-hash files under distDir that the current Release does not list and that the retention policy does not keep, see PlanByHashPrune for the decision and ByHashRetention for the policy. current must be the Release being published. It returns the removed paths, relative to distDir, sorted.

func ReadInfoList added in v0.3.1

func ReadInfoList(fsys fs.FS, name, arch string, opts StatusOptions) ([]string, error)

ReadInfoList returns the paths dpkg recorded for an installed package, from its "<name>.list" file in fsys, which is the directory /var/lib/dpkg/info (os.DirFS of it, or of a root's copy). dpkg qualifies the file name with the architecture for a package that is installed for several, "<name>:<arch>.list"; that name is tried first when arch is not empty. The paths are as dpkg writes them, absolute ("/usr/bin/tool"), directories included, and in file order. The file is bounded by StatusOptions.MaxBytes, and its paths by an entry limit; a larger list fails with ErrTooLarge. A package without a list returns an error that matches fs.ErrNotExist.

func ReleaseGPGPath

func ReleaseGPGPath(dist string) string

ReleaseGPGPath is the location of the detached Release signature.

func ReleasePath

func ReleasePath(dist string) string

ReleasePath is the location of the Release file of a distribution relative to the repository root.

func ScanContents added in v0.4.0

func ScanContents(r io.Reader) iter.Seq2[ContentsEntry, error]

ScanContents yields the files of a Contents index (read decompressed), with the packages that contain them, in file order. A header line ("FILE LOCATION"), blank lines and lines without a package column are skipped. The path may contain blanks: the package column is the last blank-separated word of the line, as apt-file reads it. A line over MaxLineBytes or with more than MaxContentsLocations packages ends the scan with ErrTooLarge. Reading is streaming; stopping the loop stops the read.

func ScanControl

func ScanControl(r io.Reader, fn func(*ControlFile) error) error

ScanControl calls fn for every paragraph of a deb822 document (an apt Packages index, a dpkg status file) in order. It is lenient: a line that is not a field is skipped, and a paragraph without fields is not reported. An error from fn stops the scan and is returned as is.

func ScanPackages

func ScanPackages(r io.Reader, fn func(Stanza) error) error

ScanPackages calls fn for every stanza of a Packages file in order. Field names are matched case-insensitively (apt does). A stanza without a Package field is skipped; fn returning an error stops the scan with it. Limits apply as for ScanControl.

func ScanTranslation added in v0.4.0

func ScanTranslation(r io.Reader, lang string) iter.Seq2[TranslationEntry, error]

ScanTranslation yields each entry of a Translation-<lang> file (read decompressed), in order. Entries without a Package or without a description in the language are skipped. The limits of ScanControl apply.

func ShortDescription added in v0.4.0

func ShortDescription(description string) string

ShortDescription returns the first line of a description.

func SignPackage added in v0.4.0

func SignPackage(w io.Writer, r io.ReaderAt, size int64, signer gpg.Signer, opts SignOptions) error

SignPackage copies the package read from r (size bytes) to w and appends a signature member made with signer, in the layout opts selects. Signatures the package already carries are kept; signing the same package again under the same role fails with ErrSignatureExists, except for dpkg-sig where the member name gets the suffix 0-9, A-Z that dpkg-sig itself picks. Every failure to read the package wraps ErrInvalidPackage.

Example
package main

import (
	"bytes"
	"fmt"
	"log"
	"time"

	"github.com/M0Rf30/pkgformat/deb"
	"github.com/M0Rf30/pkgformat/gpg"
)

func main() {
	entity, err := gpg.GenerateEntity("Release Bot", "", "bot@example.org", gpg.AlgorithmED25519)
	if err != nil {
		log.Fatal(err)
	}

	signer, err := gpg.NewLocalSignerFromEntity(entity)
	if err != nil {
		log.Fatal(err)
	}

	keyring, err := signer.Keyring()
	if err != nil {
		log.Fatal(err)
	}

	spec := &deb.Spec{
		Name: "hello", Version: "1.0", Release: "1", Architecture: "all",
		Maintainer: "Jane Doe <jane@example.org>", Description: "Say hello",
		ModTime: time.Unix(1700000000, 0),
	}

	var plain bytes.Buffer
	if err := deb.Write(&plain, spec, nil, deb.WriteOptions{}); err != nil {
		log.Fatal(err)
	}

	var signed bytes.Buffer
	if err := deb.SignPackage(&signed, bytes.NewReader(plain.Bytes()), int64(plain.Len()), signer, deb.SignOptions{}); err != nil {
		log.Fatal(err)
	}

	pkg, err := deb.ParseDebFileAt(bytes.NewReader(signed.Bytes()), int64(signed.Len()))
	if err != nil {
		log.Fatal(err)
	}

	results, err := pkg.VerifySignatures(keyring)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(results[0].Member, results[0].Role, results[0].Err == nil)
}
Output:
_gpgorigin origin true

func SourceDateEpoch added in v0.4.0

func SourceDateEpoch() (t time.Time, ok bool, err error)

SourceDateEpoch reads SOURCE_DATE_EPOCH, the number of seconds since the Unix epoch, as the time for Spec.ModTime. ok is false when the variable is unset or empty; a value that is not a non-negative integer fails with ErrInvalidSpec.

func StripClearsign

func StripClearsign(data []byte) []byte

StripClearsign returns the signed text of a clear-signed document, with the dash-escaping removed, or data unchanged when it is not one. It does not verify the signature.

func StripEpoch

func StripEpoch(v string) string

StripEpoch returns v without its numeric epoch ("1:2.0-1" is "2.0-1"), the form a package file name carries.

func TranslationFileName added in v0.4.0

func TranslationFileName(lang, ext string) string

TranslationFileName is the name of a Translation file in the i18n directory of a component: "Translation-de.xz".

func ValidVersion

func ValidVersion(v string) bool

ValidVersion reports whether v is a version dpkg accepts: an optional numeric epoch followed by a colon, then letters, digits and . + - ~ :. It does not require the upstream version to start with a digit, which dpkg only warns about.

func Write

func Write(w io.Writer, spec *Spec, payload []Entry, opts WriteOptions) error

Write writes the package described by spec, with payload as the files it installs, to w as a .deb: the ar archive made of debian-binary, the control archive and the data archive. Entries are written in the given order; the missing parent directories of an entry are added before it, and so is the root "./". Owners are root:root unless an entry names others, which is what "dpkg-deb --root-owner-group" produces for a tree of root-owned files. The md5sums file and, when Spec.InstalledSize is zero, the Installed-Size are computed from the payload.

Example
spec := &deb.Spec{
	Name:         "hello",
	Version:      "1.0",
	Release:      "1",
	Architecture: "amd64",
	Maintainer:   "Jane Doe <jane@example.org>",
	Description:  "Say hello\nA friendly greeter.",
	Depends:      rels("libc6 (>= 2.31)"),
	ModTime:      time.Unix(1700000000, 0),
}

payload := []deb.Entry{
	{Path: "usr/bin/hello", Mode: 0o755, Data: []byte("#!/bin/sh\necho hello\n")},
}

var buf bytes.Buffer
if err := deb.Write(&buf, spec, payload, deb.WriteOptions{}); err != nil {
	log.Fatal(err)
}

pkg, err := deb.ParseDebFileAt(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
	log.Fatal(err)
}

fmt.Println(pkg.Package.Package, pkg.Package.Version, pkg.Package.Architecture)
fmt.Println(pkg.Package.Depends)
fmt.Println(spec.FileName())
Output:
hello 1.0-1 amd64
libc6 (>= 2.31)
hello_1.0-1_amd64.deb

func WriteByHash added in v0.4.0

func WriteByHash(distDir string, rel *Release, opts ByHashOptions) ([]string, error)

WriteByHash lays out the by-hash tree for the indexes of a Release stored in distDir (the dists/<dist> directory): for every file the Release lists, it makes the file available as by-hash/<algorithm>/<digest> next to itself, for each algorithm, in the way opts.Mode says. Existing by-hash files of the right size are left alone (their name is their content), so repeated runs are no-ops and runs for several Releases accumulate the tree that clients fetching an older Release still need; see PruneByHash. A by-hash file of the wrong size (a torn write of an older tool) is replaced.

Every file is published atomically: a client never sees a partial by-hash file. Directories are created with opts.DirMode (0755) and copies get opts.FileMode (0644). The tree is the one apt-ftparchive release writes with APT::FTPArchive::DoByHash=true (same paths, same SHA256 and SHA512 set, copies with mode 0644 in 0755 directories); set Release.AcquireByHash when publishing the Release itself, after the tree is laid out.

Files the Release lists but that are not in distDir are skipped (a Release lists the uncompressed index of a repository that only keeps the compressed ones), as are by-hash entries themselves. A file whose size or digest is not the listed one fails with ErrByHashMismatch before anything is published for it. It returns the by-hash paths now present for the Release, sorted, relative to distDir.

Example
package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	dist, err := os.MkdirTemp("", "dists")
	if err != nil {
		log.Fatal(err)
	}

	defer func() { _ = os.RemoveAll(dist) }()

	packages := []byte("Package: hello\n\n")
	if err := os.MkdirAll(filepath.Join(dist, "main", "binary-amd64"), 0o755); err != nil {
		log.Fatal(err)
	}

	if err := os.WriteFile(filepath.Join(dist, "main", "binary-amd64", "Packages"), packages, 0o644); err != nil {
		log.Fatal(err)
	}

	rel := &deb.Release{AcquireByHash: true}
	rel.AddFile(deb.HashBytes("main/binary-amd64/Packages", packages))

	written, err := deb.WriteByHash(dist, rel, deb.ByHashOptions{Algorithms: []deb.ByHashAlgorithm{deb.ByHashSHA256}})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(len(written), strings.HasPrefix(written[0], "main/binary-amd64/by-hash/SHA256/"))

	// Later, once the Release lists other files, the old ones are pruned
	// after a day (a dry run first).
	next := &deb.Release{}
	plan, err := deb.PlanByHashPrune(dist, next, deb.ByHashRetention{MaxAge: 24 * time.Hour, Now: time.Now().Add(48 * time.Hour)})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(len(plan.Keep), len(plan.Remove))

	removed, err := plan.Apply(dist)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(len(removed))
}
Output:
1 true
0 1
1

func WriteByHashFS added in v0.4.0

func WriteByHashFS(src fs.FS, dest string, rel *Release, opts ByHashOptions) ([]string, error)

WriteByHashFS is WriteByHash for an index tree that is not a directory: src holds the dists/<dist> tree (an embedded or in-memory file system, an archive) and the by-hash files are written, as copies, under the directory dest. dest may be the directory the Release is published from.

func WriteFile

func WriteFile(filePath string, spec *Spec, payload []Entry, opts WriteOptions) error

WriteFile writes the package to path through a temporary file in the same directory, renamed into place when complete.

Types

type ARHeader

type ARHeader struct {
	Name    string
	ModTime time.Time
	OwnerID int
	GroupID int
	Mode    int
	Size    int64
}

ARHeader is the header of one member of an ar archive.

type Alternatives

type Alternatives []Relation

Alternatives is a group of relations separated by "|": any one of them satisfies the dependency.

func ActiveRelations added in v0.3.1

func ActiveRelations(rels []Alternatives, hostArch string, profiles []string) []Alternatives

ActiveRelations evaluates the restrictions of a parsed dependency field for a build on hostArch with the given build profiles: the relations that do not apply are dropped, and so is a dependency left without any alternative. What remains has no restrictions, so it is what a resolver has to satisfy.

Example
package main

import (
	"fmt"
	"log"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	const field = "debhelper-compat (= 13), dh-golang <!nocheck>, libhurd-dev [hurd-any], gcc-for-host <cross>, libgtk-3-dev [linux-any] | libgtk-dev"

	rels, err := deb.ParseRelations(field)
	if err != nil {
		log.Fatal(err)
	}

	// What a native build of an amd64 package, running the tests, needs.
	fmt.Println(deb.FormatRelations(deb.ActiveRelations(rels, "amd64", nil)))
	// And a cross build for hurd-i386 that skips the tests.
	fmt.Println(deb.FormatRelations(deb.ActiveRelations(rels, "hurd-i386", []string{"nocheck", "cross"})))
}
Output:
debhelper-compat (= 13), dh-golang, libgtk-3-dev | libgtk-dev
debhelper-compat (= 13), libhurd-dev, gcc-for-host, libgtk-dev

func ParseRelationList added in v0.4.0

func ParseRelationList(entries ...string) ([]Alternatives, error)

ParseRelationList parses entries, each a control-file dependency or several joined by commas ("libc6 (>= 2.31)", "a | b, c"), into the typed form the relationship fields of Spec take. It keeps restrictions on the relations; Spec.Validate then rejects those, which are not valid in a binary package.

func ParseRelations

func ParseRelations(field string) ([]Alternatives, error)

ParseRelations parses a dependency field (Depends, Pre-Depends, Conflicts, Provides, Build-Depends, ...) into its comma-separated entries, each a list of alternatives. Architecture restrictions ("[amd64 !i386]") and build profile restrictions ("<!nocheck> <stage1 cross>") are kept on the relation; Relation.AppliesTo and ActiveRelations evaluate them. A malformed entry fails with ErrInvalidControlFormat.

Example
package main

import (
	"fmt"
	"log"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	const field = "libc6 (>= 2.31), bash | dash"

	alternatives, err := deb.ParseRelations(field)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(len(alternatives), deb.DependencyNames(field))
}
Output:
2 [libc6 bash]

func (Alternatives) Active added in v0.3.1

func (a Alternatives) Active(hostArch string, profiles []string) Alternatives

Active returns the alternatives that apply (see Relation.AppliesTo), in order, without the restrictions on them. It returns nil when none applies, which means the whole dependency does not.

func (Alternatives) String added in v0.3.1

func (a Alternatives) String() string

String renders the group with " | " between the relations.

type ByHashAlgorithm added in v0.4.0

type ByHashAlgorithm string

ByHashAlgorithm names a digest of the by-hash tree of a repository: the name is the directory under by-hash/ ("SHA256") and the name of the Release section that lists it.

const (
	ByHashSHA512 ByHashAlgorithm = "SHA512"
	ByHashSHA256 ByHashAlgorithm = "SHA256"
	ByHashSHA1   ByHashAlgorithm = "SHA1"
	ByHashMD5    ByHashAlgorithm = "MD5Sum"
)

The digests a by-hash tree is laid out by, strongest first, the order a client prefers.

func ByHashAlgorithms added in v0.4.0

func ByHashAlgorithms() []ByHashAlgorithm

ByHashAlgorithms lists every ByHashAlgorithm, strongest first.

func (ByHashAlgorithm) Digest added in v0.4.0

func (a ByHashAlgorithm) Digest(f FileInfo) string

Digest returns the hex digest of f for the algorithm, or "" when f has none.

type ByHashFile added in v0.4.0

type ByHashFile struct {
	// Path is relative to the dists/<dist> directory.
	Path string
	// ModTime is the modification time of the file.
	ModTime time.Time
	// Generation is 1 for the newest generation the current Release does not
	// list, 2 for the one before, and so on; 0 for a leftover temporary file.
	Generation int
	// Reason says why the file is kept or removed.
	Reason string
}

ByHashFile is one by-hash file the prune plan decides on.

type ByHashMode added in v0.4.0

type ByHashMode int

ByHashMode is how WriteByHash makes a file available under its digest.

const (
	// ByHashCopy copies the file, atomically (a temporary file renamed into
	// place), keeping its modification time. This is the zero value and what
	// apt-ftparchive does: the copy is safe even when the index is later
	// rewritten in place.
	ByHashCopy ByHashMode = iota
	// ByHashHardlink hard-links the by-hash name to the index: no disk space,
	// and the name keeps the content it had as long as the index is replaced
	// by a new file (a new inode) rather than rewritten in place. It falls
	// back to a copy when the file system refuses a link.
	ByHashHardlink
	// ByHashSymlink writes a relative symbolic link to the index. The link
	// follows the index, not its content: when the index is replaced in place
	// the link serves the new content under the old digest. Use it only when
	// indexes are published once and not rewritten.
	ByHashSymlink
)

type ByHashOptions added in v0.4.0

type ByHashOptions struct {
	// Algorithms are the digests to lay the tree out by. Empty selects
	// SHA256 and SHA512: MD5 and SHA1 are obsolete and clients prefer the
	// stronger ones, which every Release written by this package lists.
	Algorithms []ByHashAlgorithm
	// Mode selects how the files are made available; the zero value is
	// ByHashCopy. WriteByHashFS can only copy and ignores it.
	Mode ByHashMode
	// FileMode is the permission of copied files; zero means 0644, a
	// repository is world readable.
	FileMode fs.FileMode
	// DirMode is the permission of the directories created; zero means 0755.
	DirMode fs.FileMode
}

ByHashOptions configures WriteByHash and WriteByHashFS.

type ByHashPlan added in v0.4.0

type ByHashPlan struct {
	// Keep lists the unlisted files the retention policy keeps, sorted by path.
	Keep []ByHashFile
	// Remove lists the files to remove, sorted by path.
	Remove []ByHashFile
}

ByHashPlan is what PruneByHash would do: the files it keeps although the current Release does not list them and the files it removes.

func PlanByHashPrune added in v0.4.0

func PlanByHashPrune(distDir string, current *Release, pol ByHashRetention) (*ByHashPlan, error)

PlanByHashPrune decides what PruneByHash would do, without touching anything. current must be the Release being published; a file it lists is never in the plan. Files in a by-hash directory that do not look like a digest of their algorithm are left alone, except leftover temporary files of an interrupted write older than an hour.

func (*ByHashPlan) Apply added in v0.4.0

func (p *ByHashPlan) Apply(distDir string) ([]string, error)

Apply removes the files of the plan under distDir, then the by-hash directories that this leaves empty. It returns the removed paths. A file that is already gone is not an error.

func (*ByHashPlan) Paths added in v0.4.0

func (p *ByHashPlan) Paths() []string

Paths returns the paths to remove.

type ByHashRef added in v0.4.0

type ByHashRef struct {
	// Algorithm and Digest identify the file.
	Algorithm ByHashAlgorithm
	Digest    string
	// Path is the by-hash path, relative to dists/<dist>.
	Path string
}

ByHashRef is one way to fetch an index by its digest.

type ByHashRetention added in v0.4.0

type ByHashRetention struct {
	// KeepGenerations is the number of unlisted generations kept in each
	// directory regardless of their age. Zero keeps none (subject to MaxAge).
	KeepGenerations int
	// MaxAge keeps a generation for that long after it was superseded. Zero
	// removes it at once (subject to KeepGenerations).
	MaxAge time.Duration
	// GenerationGap separates generations: files whose modification times are
	// further apart belong to different ones. Zero means one minute.
	GenerationGap time.Duration
	// Now is the reference of MaxAge; the zero value is time.Now().
	Now time.Time
}

ByHashRetention is the policy of PruneByHash for the by-hash files the current Release no longer lists. A client that fetched an older Release may still be downloading them, so they stay for a while.

The files of a by-hash directory (one per index directory and algorithm) are grouped into generations by their modification time: the files of one publication share one (a hard link or a copy keeps the time of the index it was made from), and files whose times lie within GenerationGap of each other are one generation. Generation 1 is the newest the Release does not list. A generation is superseded when the next one appeared: the modification time of the newest file of that next generation, or, for generation 1, of the files the current Release lists in the same directory.

type Compression

type Compression int

Compression selects how a tar member of a package or an index is compressed.

const (
	CompressionNone Compression = iota
	CompressionGzip
	CompressionXZ
	CompressionZstd
)

The supported compressions. The zero value is CompressionNone.

func ParseCompression

func ParseCompression(name string) (Compression, error)

ParseCompression maps a name ("gzip", "gz", "xz", "zstd", "zst", "none") to a Compression. The empty name selects CompressionZstd, the default of the package writer.

func (Compression) Extension

func (c Compression) Extension() string

Extension is the file suffix of the compression: ".gz", ".xz", ".zst" or "".

type ContentsBuilder added in v0.4.0

type ContentsBuilder struct {
	// contains filtered or unexported fields
}

ContentsBuilder accumulates the files of packages and renders them as a Contents index, the way apt-ftparchive does: one line per file, sorted by path, the path padded with tabs and spaces to the package column, the packages after it, sorted and comma separated. The zero value is empty and ready to use.

Example
package main

import (
	"fmt"
	"log"
	"strings"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	var b deb.ContentsBuilder

	_ = b.Add("utils/hello", "usr/bin/hello", "usr/share/doc/hello/copyright")
	_ = b.Add("utils/hello-extras", "usr/bin/hello")

	fmt.Print(strings.ReplaceAll(string(b.Bytes()), "\t", "~"))

	for e, err := range deb.ScanContents(strings.NewReader(string(b.Bytes()))) {
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println(e.Path, e.Locations)
	}
}
Output:
usr/bin/hello~~~~~~    utils/hello,utils/hello-extras
usr/share/doc/hello/copyright~~~~    utils/hello
usr/bin/hello [utils/hello utils/hello-extras]
usr/share/doc/hello/copyright [utils/hello]

func (*ContentsBuilder) Add added in v0.4.0

func (b *ContentsBuilder) Add(location string, paths ...string) error

Add records that the package at location (see ContentsLocation) contains paths. Paths are stored without leading "./" or "/"; empty ones, directory names (a trailing "/") and names with a line break or NUL, which a Contents file cannot hold, are ignored. A location that is empty or holds a blank, a comma or a line break fails with ErrInvalidContents.

func (*ContentsBuilder) AddDeb added in v0.4.0

func (b *ContentsBuilder) AddDeb(d *DebFile) error

AddDeb records the files of a package under its own name: Section/Package from its control file, see ContentsLocation.

func (*ContentsBuilder) AddDebAs added in v0.4.0

func (b *ContentsBuilder) AddDebAs(d *DebFile, location string) error

AddDebAs records the files of a package under location instead of the name its control file gives, such as the qualified name an override file assigns.

func (*ContentsBuilder) AddEntry added in v0.4.0

func (b *ContentsBuilder) AddEntry(e ContentsEntry) error

AddEntry records a ContentsEntry, such as ScanContents yields.

func (*ContentsBuilder) AddReader added in v0.4.0

func (b *ContentsBuilder) AddReader(r io.Reader) error

AddReader merges a Contents index read from r (decompressed; wrap a compressed one with OpenIndex) into the builder. It fails with ErrTooLarge when the builder would hold more than MaxContentsFiles files.

func (*ContentsBuilder) Bytes added in v0.4.0

func (b *ContentsBuilder) Bytes() []byte

Bytes renders the index, deterministically: the same files and packages give the same bytes however they were added.

func (*ContentsBuilder) Compressed added in v0.4.0

func (b *ContentsBuilder) Compressed(c Compression) ([]byte, error)

Compressed renders the index compressed with c.

func (*ContentsBuilder) Entries added in v0.4.0

func (b *ContentsBuilder) Entries() iter.Seq[ContentsEntry]

Entries yields the files in path order, with their packages sorted.

func (*ContentsBuilder) Len added in v0.4.0

func (b *ContentsBuilder) Len() int

Len is the number of distinct file paths.

func (*ContentsBuilder) Locations added in v0.4.0

func (b *ContentsBuilder) Locations(path string) []string

Locations returns the packages that contain the file, sorted.

func (*ContentsBuilder) WriteTo added in v0.4.0

func (b *ContentsBuilder) WriteTo(w io.Writer, c Compression) (int64, error)

WriteTo writes the index compressed with c to w and returns the number of bytes written to w. It streams: the index is not rendered in memory first.

type ContentsEntry added in v0.4.0

type ContentsEntry struct {
	// Path is the file, without a leading "./" or "/".
	Path string
	// Locations lists the packages as "section/name" (see ContentsLocation).
	Locations []string
}

ContentsEntry is one line of a Contents index: a file and the packages that contain it.

type ContentsIndex added in v0.4.0

type ContentsIndex struct {
	// contains filtered or unexported fields
}

ContentsIndex is a parsed Contents index: which packages contain a file, which is what apt-file searches. Build one with ParseContents.

func ParseContents added in v0.4.0

func ParseContents(r io.Reader) (*ContentsIndex, error)

ParseContents reads a whole Contents index (see ScanContents). The input is expected decompressed; wrap a compressed one with OpenIndex. A file listed twice has its packages merged. More than MaxContentsFiles files fail with ErrTooLarge.

func (*ContentsIndex) Entries added in v0.4.0

func (c *ContentsIndex) Entries() iter.Seq[ContentsEntry]

Entries yields the files in path order.

func (*ContentsIndex) Find added in v0.4.0

func (c *ContentsIndex) Find(match func(path string) bool) map[string][]string

Find returns the paths for which match is true, with their packages.

func (*ContentsIndex) Len added in v0.4.0

func (c *ContentsIndex) Len() int

Len is the number of distinct file paths.

func (*ContentsIndex) Locations added in v0.4.0

func (c *ContentsIndex) Locations(path string) []string

Locations returns the packages that contain the file, sorted.

type ControlFile

type ControlFile struct {
	// Fields maps a field name, as written in the document, to its value.
	Fields map[string]string
	// Order lists the field names in document order.
	Order []string
}

ControlFile is one deb822 paragraph: a binary package's control file, a Packages or dpkg status entry. Field names are matched case-insensitively (apt does), values are logical: the single space or tab that introduces a continuation line is removed and a " ." line is an empty line.

func NewControlFile

func NewControlFile() *ControlFile

NewControlFile returns an empty paragraph.

func ParseControlFile

func ParseControlFile(r io.Reader) (*ControlFile, error)

ParseControlFile parses the first paragraph of a deb822 document, such as the control file of a package. Unlike ScanControl it is strict: a line that is not a field, a continuation or a comment fails with ErrInvalidControlFormat.

func (*ControlFile) Get

func (cf *ControlFile) Get(field string) string

Get returns the value of a field, or "" when it is absent.

func (*ControlFile) GetRequired

func (cf *ControlFile) GetRequired(field string) (string, error)

GetRequired returns the value of a field that must be present and not empty.

func (*ControlFile) Lookup

func (cf *ControlFile) Lookup(field string) (string, bool)

Lookup returns the value of a field and whether it is present. The exact spelling is tried first, then any case variant.

func (*ControlFile) ParsePackage

func (cf *ControlFile) ParsePackage() (*Package, error)

ParsePackage extracts the package fields. Package, Version and Architecture are required.

func (*ControlFile) Set

func (cf *ControlFile) Set(field, value string)

Set sets a field, replacing the value of any case variant of the name in place, or appending the field.

func (*ControlFile) String

func (cf *ControlFile) String() string

String renders the paragraph in document order, ending with a newline, and no blank line.

type ControlMember added in v0.4.0

type ControlMember struct {
	// Name is the file name in the control archive: one path element made of
	// letters, digits and ". _ + -".
	Name string
	// Mode holds the permission bits; zero means 0644.
	Mode fs.FileMode
	// Data is the content, at most MaxControlFileSize bytes.
	Data []byte
}

ControlMember is a file of the control archive that Spec has no member for.

type DebFile

type DebFile struct {
	Package     *Package
	ControlFile *ControlFile
	// ControlTarGz is the raw control archive member, whatever its compression.
	ControlTarGz []byte
	// Control holds the files of the control archive (control, md5sums,
	// conffiles, preinst, postinst, prerm, postrm, config, templates, ...) by
	// name, without a leading "./".
	Control map[string][]byte
	// Signatures are the package signature members (debsigs' _gpgorigin and
	// dpkg-sig's _gpgbuilder, _gpgmaint, ...) in archive order. They are not
	// verified here; see VerifySignatures.
	Signatures []SignatureMember
	// contains filtered or unexported fields
}

DebFile is a parsed .deb file. It keeps the reader it was parsed from, which must stay valid for OpenData and Extract.

func ParseDebFile

func ParseDebFile(r io.ReaderAt, size int64, opts ParseOptions) (*DebFile, error)

ParseDebFile parses a .deb file by walking the ar headers with ReadAt and reading only the control archive, so memory use does not depend on the size of the package. Every failure wraps ErrInvalidPackage.

func ParseDebFileAt

func ParseDebFileAt(r io.ReaderAt, size int64) (*DebFile, error)

ParseDebFileAt parses a .deb file with the default limits. See ParseDebFile.

func (*DebFile) Conffiles

func (d *DebFile) Conffiles() []string

Conffiles returns the configuration files the package declares, one path per line of the conffiles member.

func (*DebFile) Extract

func (d *DebFile) Extract(dir string, opts ExtractOptions) error

Extract unpacks the data archive of the package into dir, which must exist. Entry paths are confined to dir, symlinks that point outside it are rejected, and device nodes and FIFOs are skipped. Owners are not applied and the setuid, setgid and sticky bits are dropped. Reaching a limit fails with ErrDataTooLarge; an entry that would leave dir fails with ErrUnsafeEntry.

func (*DebFile) OpenData

func (d *DebFile) OpenData() (io.ReadCloser, error)

OpenData returns the decompressed data archive (a tar stream) of the package. The size of the output is not limited here; Extract bounds it.

func (*DebFile) Shlibs added in v0.4.0

func (d *DebFile) Shlibs() ([]Shlib, error)

Shlibs parses the shlibs control member.

func (*DebFile) Symbols added in v0.4.0

func (d *DebFile) Symbols() ([]SymbolsLibrary, error)

Symbols parses the symbols control member.

func (*DebFile) Triggers added in v0.4.0

func (d *DebFile) Triggers() ([]Trigger, error)

Triggers parses the triggers control member. A package without one has no triggers.

func (*DebFile) VerifySignatures added in v0.4.0

func (d *DebFile) VerifySignatures(kr *gpg.Keyring) ([]PackageSignature, error)

VerifySignatures checks every signature member of the package against kr and returns one result per member, in archive order. The error is ErrNoPackageSignature for an unsigned package, and a join of the failures of the members that do not verify; the results are returned in both cases.

A member that holds a clear-signed manifest is read as dpkg-sig's, any other as debsigs'. A debsigs signature covers the three core members; a dpkg-sig one covers the members its manifest lists, which must include debian-binary, the control archive and the data archive.

type DebsigPolicy added in v0.4.0

type DebsigPolicy struct {
	// Name and Description label the origin.
	Name        string
	Description string
	// KeyID is the 16-digit key id (or 40-digit fingerprint) of the signing
	// key.
	KeyID string
	// Keyring is the keyring file name under /usr/share/debsig/keyrings/<ID>.
	// Empty means DebsigPolicyKeyring.
	Keyring string
}

DebsigPolicy describes the policy debsig-verify applies to packages signed under the "origin" role: the signature must come from one key.

Install the result as /etc/debsig/policies/<ID>/<name>.pol and the binary keyring holding the public key (gpg --export) as /usr/share/debsig/keyrings/<ID>/<Keyring>, where <ID> is the long key id.

func (DebsigPolicy) Marshal added in v0.4.0

func (p DebsigPolicy) Marshal() ([]byte, error)

Marshal renders the policy file. It fails with ErrInvalidSpec for a missing name or a malformed key id.

type Entry

type Entry struct {
	// Path is the slash-separated path inside the package, relative to the
	// root: "usr/bin/tool". A leading "./" or "/" is ignored.
	Path string
	// Mode holds the permission bits, with fs.ModeSetuid, fs.ModeSetgid and
	// fs.ModeSticky, and the type: fs.ModeDir for a directory, fs.ModeSymlink
	// for a symlink, fs.ModeNamedPipe for a FIFO, fs.ModeDevice for a block
	// device and fs.ModeDevice|fs.ModeCharDevice for a character device; no
	// type is a regular file. A socket cannot be stored in a tar archive and
	// fails with ErrUnsupportedEntryType, as does any other type.
	Mode fs.FileMode
	// Linkname is the target of a symlink: stored as given.
	Linkname string
	// Hardlink, when not empty, makes the entry a hard link to the regular
	// file of that path, which must be an earlier entry of the payload (or
	// itself a hard link to one). The entry has no content of its own; Mode is
	// recorded as given and should repeat the mode of the target, which is what
	// dpkg applies.
	Hardlink string
	// DevMajor and DevMinor are the device numbers of a device node.
	DevMajor int64
	DevMinor int64

	// UID and GID are the numeric owner and group, zero (root) by default.
	// User and Group are their names; when empty they are "root" for id zero
	// and absent otherwise. dpkg installs by name when the system knows it and
	// falls back to the numbers.
	UID, GID    int
	User, Group string

	// ModTime is the modification time; zero means the Spec's ModTime.
	ModTime time.Time
	// Data is the content of a regular file. When nil, Open provides it.
	Data []byte
	// Open returns the content of a regular file that is not in Data. It may
	// be called once. Size must be set with it.
	Open func() (io.ReadCloser, error)
	// Size is the length of the content Open returns.
	Size int64
}

Entry is one member of the data archive of a package.

func FSEntries

func FSEntries(fsys fs.FS, modTime time.Time) ([]Entry, error)

FSEntries lists the content of fsys as payload entries in lexical order: directories, regular files and symlinks. Other file types (devices, FIFOs, sockets) fail the call, as they cannot be part of a package built this way. The tree of a directory is os.DirFS(dir). Files are opened when Write reaches them, so the tree must stay unchanged until then.

Entries get the modification time of their file, or modTime when it is not zero (use it for reproducible packages).

type ExtractOptions

type ExtractOptions struct {
	// MaxBytes bounds the total size of the regular files written. Zero means
	// DefaultMaxExtractBytes.
	MaxBytes int64
	// MaxEntries bounds the number of archive entries. Zero means
	// DefaultMaxExtractEntries.
	MaxEntries int
}

ExtractOptions tunes DebFile.Extract. The zero value applies the defaults.

type Field added in v0.4.0

type Field struct {
	// Name is the field name as it is written: "Rules-Requires-Root",
	// "X-Packager".
	Name string
	// Value is the logical value. A multi-line value (a Tag list, say) is
	// written with continuation lines; a blank line in it is encoded as " .".
	Value string
}

Field is a control field with an arbitrary name, written after the fields a Spec has a member for. The order of Spec.Fields is the order in the control file.

type FileInfo

type FileInfo struct {
	// Path is relative to the directory the listing belongs to (the dists/<dist>
	// directory for a Release) or to the repository root for a package file.
	Path string
	Size int64
	// Hex digests; empty when unknown.
	MD5sum, SHA1, SHA256, SHA512 string
}

FileInfo describes one file of a repository: its path, size and digests.

func HashBytes

func HashBytes(path string, data []byte) FileInfo

HashBytes returns the FileInfo of data stored under path, with every digest computed.

func HashReader

func HashReader(path string, r io.Reader) (FileInfo, error)

HashReader reads r to its end and returns its FileInfo with every digest computed.

func (FileInfo) Complete

func (f FileInfo) Complete() bool

Complete reports whether MD5sum, SHA1 and SHA256 are all set.

type Flag added in v0.3.1

type Flag string

Flag is the second word of a dpkg Status field: the error flag.

const (
	FlagOK            Flag = "ok"
	FlagReinstReq     Flag = "reinstreq"
	FlagHold          Flag = "hold"
	FlagHoldReinstReq Flag = "hold-reinstreq"
)

The values dpkg writes.

type I18nIndex added in v0.4.0

type I18nIndex struct {
	// Files lists the Translation files by name, relative to the i18n directory
	// ("Translation-en.xz").
	Files map[string]FileInfo
}

I18nIndex is the content of the i18n/Index file of a component: the checksums of the Translation files next to it, so that a client can tell a translation it has is current without fetching the Release again.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	var ix deb.I18nIndex

	ix.AddFile(deb.FileInfo{Path: "Translation-en.xz", Size: 100, SHA1: strings.Repeat("a", 40)})
	ix.AddFile(deb.FileInfo{Path: "Translation-de", Size: 5, SHA1: strings.Repeat("b", 40)})

	fmt.Print(string(ix.Marshal()))
	fmt.Println(ix.Languages(), deb.I18nIndexName("main"))
}
Output:
SHA1:
 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb       5 Translation-de
 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa     100 Translation-en.xz
[de en] main/i18n/Index

func ParseI18nIndex added in v0.4.0

func ParseI18nIndex(data []byte) (*I18nIndex, error)

ParseI18nIndex parses an i18n/Index file. A clear-signed one is accepted, its signature not verified.

func (*I18nIndex) AddFile added in v0.4.0

func (ix *I18nIndex) AddFile(fi FileInfo)

AddFile records a Translation file in the index.

func (*I18nIndex) Languages added in v0.4.0

func (ix *I18nIndex) Languages() []string

Languages lists the languages the index has a Translation file for, sorted and without duplicates.

func (*I18nIndex) Marshal added in v0.4.0

func (ix *I18nIndex) Marshal() []byte

Marshal renders the index: the checksum sections of a Release (MD5Sum, SHA1, SHA256, SHA512), each with the digests the files have. A file with only a SHA1 digest renders the SHA1 section alone, as the Ubuntu archive does.

func (*I18nIndex) Variants added in v0.4.0

func (ix *I18nIndex) Variants(lang string) []IndexVariant

Variants returns the files of one language the index lists, best compression first (.xz, .zst, .gz, .bz2, .lz4, plain).

type Index

type Index struct {
	// contains filtered or unexported fields
}

Index accumulates the entries of a Packages index and renders it plain or compressed. The zero value is an empty index.

Example
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	var index deb.Index

	index.Add(deb.IndexEntry{
		Name: "hello", Version: "1.0-1", Arch: "amd64",
		Filename: deb.PoolPath("main", "hello", "hello_1.0-1_amd64.deb"),
		Size:     1234, SHA256: "abc123",
		Control: map[string]string{"Maintainer": "Jane Doe <jane@example.org>", "Description": "Say hello"},
	})

	fmt.Print(string(index.Bytes()))

	err := deb.ScanPackages(bytes.NewReader(index.Bytes()), func(s deb.Stanza) error {
		fmt.Println("scanned:", s.Package, s.Version, s.Filename)

		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}
Output:
Package: hello
Version: 1.0-1
Architecture: amd64
Maintainer: Jane Doe <jane@example.org>
Filename: pool/main/h/hello/hello_1.0-1_amd64.deb
Size: 1234
SHA256: abc123
Description: Say hello

scanned: hello 1.0-1 pool/main/h/hello/hello_1.0-1_amd64.deb

func (*Index) Add

func (ix *Index) Add(e IndexEntry)

Add appends the stanza of e.

func (*Index) AddText

func (ix *Index) AddText(stanza string)

AddText appends a stanza as is, such as Stanza.Text. A stanza without a final blank line gets one.

func (*Index) Bytes

func (ix *Index) Bytes() []byte

Bytes renders the index. The result is shared; do not modify it.

func (*Index) Compressed

func (ix *Index) Compressed(c Compression) ([]byte, error)

Compressed renders the index compressed with c.

func (*Index) Len

func (ix *Index) Len() int

Len is the number of stanzas.

func (*Index) WriteTo

func (ix *Index) WriteTo(w io.Writer, c Compression) (int64, error)

WriteTo writes the index compressed with c to w and returns the number of bytes written to w.

type IndexEntry

type IndexEntry struct {
	Name    string
	Version string
	Arch    string
	// InstalledSize is the Installed-Size in KiB; zero omits the field.
	InstalledSize int64
	// Filename is the path of the .deb relative to the repository root, such as
	// PoolPath returns.
	Filename string
	// Size is the size of the .deb in bytes.
	Size int64
	// MD5sum, SHA1, SHA256 and SHA512 are the hex digests of the .deb; empty
	// ones are omitted.
	MD5sum, SHA1, SHA256, SHA512 string
	// Control holds the other control fields of the package (Depends, Section,
	// Description, ...). Fields the repository owns (Package, Version,
	// Architecture, Installed-Size, Filename, Size and the digests) are ignored
	// when present.
	Control map[string]string
}

IndexEntry is a binary package as it is listed in a Packages index.

func EntryFromControl

func EntryFromControl(cf *ControlFile, file FileInfo) (IndexEntry, error)

EntryFromControl builds the index entry of a package file from its control fields and the facts about the file: path in the repository, size and digests. Fields of cf the index owns are taken from cf (name, version, architecture, installed size) or from the file facts, never copied through.

func (IndexEntry) TranslationEntry added in v0.4.0

func (e IndexEntry) TranslationEntry() TranslationEntry

TranslationEntry returns the Translation entry of the package: its description under its Description-md5. The language is that of the Translation file it is written to; an index carrying English descriptions writes Translation-en.

type IndexVariant added in v0.4.0

type IndexVariant struct {
	// Path is relative to dists/<dist>, with the suffix.
	Path string
	// Extension is the compression suffix: ".xz", ".zst", ".gz", ".bz2", ".lz4"
	// or "" for the plain file.
	Extension string
	// Info is the listing of the file.
	Info FileInfo
}

IndexVariant is one compression of an index the Release lists.

type PDiffApplyOptions added in v0.4.0

type PDiffApplyOptions struct {
	// MaxPatchSize bounds the (decompressed) ed script; DefaultMaxPDiffPatchBytes
	// when zero.
	MaxPatchSize int64
	// MaxResultSize bounds the patched file; MaxIndexBytes when zero.
	MaxResultSize int64
	// MaxCommands bounds the a, c and d commands of the script;
	// DefaultMaxPDiffCommands when zero.
	MaxCommands int
}

PDiffApplyOptions bounds the application of a patch. The zero value selects the defaults.

type PDiffBuilderOptions added in v0.4.0

type PDiffBuilderOptions struct {
	// IndexName is the file the patches lead to, relative to the PDiffFS root:
	// "Packages", "Sources", "Contents-amd64", "Translation-en". The patches
	// live in the directory IndexName+".diff". Default "Packages".
	IndexName string
	// MaxPatches bounds the history; older patches are pruned and their files
	// removed. DefaultPDiffMaxPatches when zero.
	MaxPatches int
	// Merge publishes merged patches (X-Patch-Precedence: merged): every patch
	// of the history leads to the current file in one step, so a client fetches
	// one file however far behind it is. The cost is that all patches are
	// rewritten on each update. The one-step patches are kept in the
	// X-Unmerged-* lists, and the merged files of the two previous updates are
	// kept for clients that read an older Index.
	Merge bool
	// SHA1 also lists the legacy SHA1 digests, as dak does. Digests of
	// entries that were published without them stay missing.
	SHA1 bool
	// XZ also publishes each patch as <name>.xz next to the gzip file and lists
	// it in the Download section. apt reads gzip patches only; the xz files are
	// for other clients.
	XZ bool
	// Generate limits the patch generator.
	Generate PDiffGenerateOptions
	// Apply limits the merging and the verification of existing patches.
	Apply PDiffApplyOptions
}

PDiffBuilderOptions configures a PDiffIndexBuilder. The zero value maintains the Packages.diff of a "Packages" file with unmerged patches, SHA-256 only, 56 patches deep.

type PDiffDirFS added in v0.4.0

type PDiffDirFS struct {
	// contains filtered or unexported fields
}

PDiffDirFS is a PDiffFS on a directory of the file system. All access goes through an os.Root, so no name can reach outside the directory, whatever it contains.

func NewPDiffDirFS added in v0.4.0

func NewPDiffDirFS(dir string) (*PDiffDirFS, error)

NewPDiffDirFS opens dir, creating it when it does not exist, as a PDiffFS. Close it when done.

func (*PDiffDirFS) Close added in v0.4.0

func (d *PDiffDirFS) Close() error

Close releases the directory.

func (*PDiffDirFS) ReadDir added in v0.4.0

func (d *PDiffDirFS) ReadDir(dir string) ([]string, error)

ReadDir implements PDiffFS.

func (*PDiffDirFS) ReadFile added in v0.4.0

func (d *PDiffDirFS) ReadFile(name string) ([]byte, error)

ReadFile implements PDiffFS.

func (*PDiffDirFS) Remove added in v0.4.0

func (d *PDiffDirFS) Remove(name string) error

Remove implements PDiffFS.

func (*PDiffDirFS) WriteFile added in v0.4.0

func (d *PDiffDirFS) WriteFile(name string, data []byte) error

WriteFile implements PDiffFS: the content goes to a temporary file in the same directory that is renamed over the target.

type PDiffError added in v0.4.0

type PDiffError struct {
	// Line is the 1-based line of the script the error is about; 0 when it is
	// not tied to a line (a limit, a command that does not fit the file).
	Line int
	// Reason says what is wrong.
	Reason string
	// Err is ErrPDiffScript or ErrPDiffLimit.
	Err error
}

PDiffError reports a malformed or misfitting edit script. It wraps ErrPDiffScript, or ErrPDiffLimit for a script or result over a limit, so errors.Is tells the two apart and errors.As recovers the position.

func (*PDiffError) Error added in v0.4.0

func (e *PDiffError) Error() string

func (*PDiffError) Unwrap added in v0.4.0

func (e *PDiffError) Unwrap() error

Unwrap returns the sentinel the error belongs to.

type PDiffFS added in v0.4.0

type PDiffFS interface {
	// ReadFile returns the content of the named file.
	ReadFile(name string) ([]byte, error)
	// WriteFile replaces the named file.
	WriteFile(name string, data []byte) error
	// Remove deletes the named file; a file that is already gone is not an error.
	Remove(name string) error
	// ReadDir lists the names (not paths) of the regular files directly inside
	// dir; a directory that does not exist has none.
	ReadDir(dir string) ([]string, error)
}

PDiffFS is the storage a PDiffIndexBuilder maintains a Packages.diff directory in. It is rooted at the directory that holds the index file (dists/<dist>/<component>/binary-<arch>) and addresses files by slash-separated names relative to it: "Packages.diff/Index", "Packages.diff/<patch>.gz", "Packages.xz".

Implementations must make WriteFile atomic (readers see the old or the new content, never a partial file), create missing directories, and report a missing file as an error that wraps fs.ErrNotExist.

type PDiffFetcher added in v0.4.0

type PDiffFetcher func(p PDiffPatch) ([]byte, error)

PDiffFetcher returns the bytes of the gzip file Packages.diff/<p.Name>.gz for a patch; ApplyPDiffChain calls it once per patch, in order.

type PDiffGenerateOptions added in v0.4.0

type PDiffGenerateOptions struct {
	// MaxLines bounds the number of lines of either file;
	// DefaultMaxPDiffLines when zero. Larger files fail with ErrPDiffLimit.
	MaxLines int
	// MaxEditDistance bounds the number of inserted plus deleted lines the
	// search looks for: its cost grows with the square of it. Where two
	// stretches of the files differ by more, the stretch is replaced as a
	// whole instead of being compared line by line, which stays correct but is
	// larger. DefaultMaxPDiffEditDistance when zero.
	MaxEditDistance int
}

PDiffGenerateOptions bounds GeneratePDiff. The zero value selects the defaults.

type PDiffHash added in v0.4.0

type PDiffHash struct {
	Size   int64
	SHA256 string
	SHA1   string
}

PDiffHash is a size and the digests of one file an Index lists. SHA1 is legacy and may be empty; SHA256 is what clients verify.

func (PDiffHash) IsZero added in v0.4.0

func (h PDiffHash) IsZero() bool

IsZero reports whether h carries no digest and no size.

type PDiffHashError added in v0.4.0

type PDiffHashError struct {
	// Patch is the patch being processed ("" for the base file).
	Patch string
	// What is the object checked: "base", "download", "patch" or "result".
	What string
	// Want and Got are the expected and the computed SHA-256 digests, or sizes
	// formatted as "<n> bytes" when the size disagreed.
	Want, Got string
}

PDiffHashError reports a digest or size that does not match the Index. It wraps ErrPDiffHash.

func (*PDiffHashError) Error added in v0.4.0

func (e *PDiffHashError) Error() string

func (*PDiffHashError) Unwrap added in v0.4.0

func (e *PDiffHashError) Unwrap() error

Unwrap returns ErrPDiffHash.

type PDiffIndex added in v0.4.0

type PDiffIndex struct {
	// Current describes the file the patches lead to.
	Current PDiffHash
	// Patches is the History in the order of the Index, oldest first. Each
	// patch's From is the file it applies to. For a Merged index each patch
	// leads to Current by itself; otherwise patch i leads to patch i+1's file
	// and the last one to Current.
	Patches []PDiffPatch
	// Merged reports "X-Patch-Precedence: merged": the server merged the
	// patches, so every entry of Patches reaches Current in one step.
	Merged bool
	// Unmerged lists, for a Merged index, the one-step patches the merged ones
	// were built from (the X-Unmerged-* sections); empty otherwise.
	Unmerged []PDiffPatch
	// OlderPatches is X-DAK-Older-Patches: the targets of earlier merged
	// series whose patch files are kept for clients holding an older Index.
	OlderPatches []string
	// CanonicalPath is Canonical-Path, when present.
	CanonicalPath string
	// Extra holds the fields the parser does not interpret, by name.
	Extra map[string]string
}

PDiffIndex is a parsed Packages.diff/Index: the digest of the current file and the series of patches that lead to it.

func ParsePDiffIndex added in v0.4.0

func ParsePDiffIndex(data []byte) (*PDiffIndex, error)

ParsePDiffIndex parses the Packages.diff/Index of an apt repository. It reads the SHA256 and SHA1 variants of the Current, History, Patches and Download fields (and their X-Unmerged-* counterparts), X-Patch-Precedence, X-DAK-Older-Patches and Canonical-Path; other fields are kept in Extra. The history order of the first digest present (SHA256, else SHA1) is authoritative: entries of other lists that are not in it are ignored, as apt does. Documents over MaxPDiffIndexBytes and series over 16384 patches are refused. A hash or size that is malformed fails the parse; an Index without any Current digest or history is an error as well.

Example

A client that holds an old Packages file asks the Index for the patches that lead to the current one, fetches them and applies them, every file checked against the digests of the Index.

package main

import (
	"fmt"
	"time"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	versions := [][]byte{[]byte("a\n"), []byte("a\nb\n"), []byte("a\nb\nc\n")}

	// The server side: an in-memory directory and a builder.
	dir := deb.NewPDiffMemFS()

	builder, err := deb.NewPDiffIndexBuilder(dir, deb.PDiffBuilderOptions{})
	if err != nil {
		panic(err)
	}

	at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)

	for i := 1; i < len(versions); i++ {
		if _, err := builder.UpdateFrom(versions[i-1], versions[i], at.Add(time.Duration(i)*time.Hour)); err != nil {
			panic(err)
		}
	}

	// The client side.
	indexData, _ := dir.ReadFile("Packages.diff/Index")

	idx, err := deb.ParsePDiffIndex(indexData)
	if err != nil {
		panic(err)
	}

	chain, err := idx.Chain(deb.PDiffSHA256(versions[0]))
	if err != nil {
		panic(err)
	}

	fetch := func(p deb.PDiffPatch) ([]byte, error) { return dir.ReadFile("Packages.diff/" + p.DownloadName()) }

	got, err := deb.ApplyPDiffChain(versions[0], chain, fetch, deb.PDiffApplyOptions{})
	if err != nil {
		panic(err)
	}

	for _, p := range chain {
		fmt.Println(p.Name)
	}

	fmt.Printf("%q\n", got)
}
Output:
2026-01-02-0404.05
2026-01-02-0504.05
"a\nb\nc\n"

func (*PDiffIndex) Chain added in v0.4.0

func (idx *PDiffIndex) Chain(fromSHA256 string) ([]PDiffPatch, error)

Chain returns the patches to fetch and apply, in order, to turn a local file with the SHA-256 fromSHA256 into the current file.

A local file that already is the current one needs no patch: Chain returns an empty chain and no error. A file that is not in the history yields ErrPDiffNoPath: the caller fetches the whole index. A history entry matches by digest; where several do, the newest wins, which is the shortest chain. For a Merged index the chain is the single merged patch of the entry.

The chain's patches have To filled in. A patch without a usable digest of itself, of its download or of its source makes the Index unusable for the chain (ErrPDiffIndex).

Example
package main

import (
	"fmt"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	idx, err := deb.ParsePDiffIndex([]byte(`SHA256-Current: ` + deb.PDiffSHA256([]byte("c\n")) + ` 2
SHA256-History:
 ` + deb.PDiffSHA256([]byte("a\n")) + ` 2 p1
 ` + deb.PDiffSHA256([]byte("b\n")) + ` 2 p2
SHA256-Patches:
 ` + deb.PDiffSHA256([]byte("1c\nb\n.\n")) + ` 7 p1
 ` + deb.PDiffSHA256([]byte("1c\nc\n.\n")) + ` 7 p2
SHA256-Download:
 ` + deb.PDiffSHA256(nil) + ` 20 p1.gz
 ` + deb.PDiffSHA256(nil) + ` 20 p2.gz
`))
	if err != nil {
		panic(err)
	}

	chain, _ := idx.Chain(deb.PDiffSHA256([]byte("a\n")))
	for _, p := range chain {
		fmt.Println(p.DownloadName())
	}

	_, err = idx.Chain(deb.PDiffSHA256([]byte("unknown\n")))
	fmt.Println(err != nil)
}
Output:
p1.gz
p2.gz
true

func (*PDiffIndex) Marshal added in v0.4.0

func (idx *PDiffIndex) Marshal() []byte

Marshal renders the Index in the layout dak writes: the Current digests, the History, Patches and Download lists with SHA1 before SHA256 (a digest kind no patch carries is left out), the X-Unmerged-* lists of a Merged index, X-Patch-Precedence, X-DAK-Older-Patches, and the Extra fields sorted by name. ParsePDiffIndex reads the result back.

type PDiffIndexBuilder added in v0.4.0

type PDiffIndexBuilder struct {
	// contains filtered or unexported fields
}

PDiffIndexBuilder maintains the Packages.diff directory of one index file of a repository, as dak's generate-index-diffs does: on each publication it diffs the file being replaced against the new one, adds the patch to the history, prunes it, rewrites the Index and removes the patch files that fell out of it.

Call Update before the new index files replace the old ones, since it reads the old one from the same PDiffFS; or call UpdateFrom with the old content. A builder is not safe for concurrent use, and neither is two builders on one directory.

Example
package main

import (
	"fmt"
	"time"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	dir := deb.NewPDiffMemFS()

	builder, err := deb.NewPDiffIndexBuilder(dir, deb.PDiffBuilderOptions{MaxPatches: 2})
	if err != nil {
		panic(err)
	}

	now := time.Date(2026, 5, 6, 7, 8, 9, 0, time.UTC)
	content := []string{"a\n", "a\nb\n", "a\nb\nc\n", "a\nb\nc\nd\n"}

	// The publisher stores each new Packages file after the builder has seen
	// the one it replaces.
	_ = dir.WriteFile("Packages", []byte(content[0]))

	for i, c := range content[1:] {
		res, err := builder.Update([]byte(c), now.Add(time.Duration(i)*time.Minute))
		if err != nil {
			panic(err)
		}

		fmt.Println("added", res.Patch.Name, "removed", len(res.Removed))

		_ = dir.WriteFile("Packages", []byte(c))
	}

	fmt.Println(dir.Names())
}
Output:
added 2026-05-06-0708.09 removed 0
added 2026-05-06-0709.09 removed 0
added 2026-05-06-0710.09 removed 1
[Packages Packages.diff/2026-05-06-0709.09.gz Packages.diff/2026-05-06-0710.09.gz Packages.diff/Index]

func NewPDiffIndexBuilder added in v0.4.0

func NewPDiffIndexBuilder(fsys PDiffFS, opts PDiffBuilderOptions) (*PDiffIndexBuilder, error)

NewPDiffIndexBuilder returns the builder of the directory in fsys, picking up the history of the Index published there. A missing or unparsable Index starts an empty history: the first Update then rebuilds the directory, and clients that are behind fetch the whole file once.

func (*PDiffIndexBuilder) Index added in v0.4.0

func (b *PDiffIndexBuilder) Index() *PDiffIndex

Index returns the Index the builder currently describes, nil when there is no history.

func (*PDiffIndexBuilder) Update added in v0.4.0

func (b *PDiffIndexBuilder) Update(newPackages []byte, now time.Time) (*PDiffUpdate, error)

Update adds the change from the index file now in the PDiffFS to newPackages (the uncompressed content of the file that is about to replace it) to the history. The old file is read as IndexName or with a .gz, .xz, .zst, .bz2 or .lz4 suffix. now names the patch (see UpdateFrom).

When there is no old file, nothing can be diffed: Update only discards a history that does not lead to newPackages.

func (*PDiffIndexBuilder) UpdateFrom added in v0.4.0

func (b *PDiffIndexBuilder) UpdateFrom(oldPackages, newPackages []byte, now time.Time) (*PDiffUpdate, error)

UpdateFrom is Update with the content of the old file given. now names the new patch, "2006-01-02-1504.05" in UTC (2024-05-01-1234.56); where that name is taken by an earlier patch, the next free second is used.

Nothing is written when the two files are the same. A history that does not end at oldPackages, or whose patch files cannot be read back and verified, is discarded and started over with the new patch. A change a patch cannot express, or one over the generator's limits, discards the history and publishes no patch (PDiffUpdate.Skipped), which is always safe: clients that find no patch fetch the whole file.

type PDiffMemFS added in v0.4.0

type PDiffMemFS struct {
	// contains filtered or unexported fields
}

PDiffMemFS is an in-memory PDiffFS.

func NewPDiffMemFS added in v0.4.0

func NewPDiffMemFS() *PDiffMemFS

NewPDiffMemFS returns an empty in-memory PDiffFS.

func (*PDiffMemFS) Names added in v0.4.0

func (m *PDiffMemFS) Names() []string

Names returns the names of all files, sorted.

func (*PDiffMemFS) ReadDir added in v0.4.0

func (m *PDiffMemFS) ReadDir(dir string) ([]string, error)

ReadDir implements PDiffFS.

func (*PDiffMemFS) ReadFile added in v0.4.0

func (m *PDiffMemFS) ReadFile(name string) ([]byte, error)

ReadFile implements PDiffFS.

func (*PDiffMemFS) Remove added in v0.4.0

func (m *PDiffMemFS) Remove(name string) error

Remove implements PDiffFS.

func (*PDiffMemFS) WriteFile added in v0.4.0

func (m *PDiffMemFS) WriteFile(name string, data []byte) error

WriteFile implements PDiffFS.

type PDiffPatch added in v0.4.0

type PDiffPatch struct {
	// Name is the name of the patch without extension, such as
	// "2024-05-01-1234.56" or "T-2024-05-01-1234.56-F-2024-04-30-0801.12".
	Name string
	// From describes the file the patch applies to (the Index History entry).
	From PDiffHash
	// To describes the file the patch yields. PDiffIndex.Chain fills it in; it
	// is the Current file for a merged patch and the next patch's From
	// otherwise. It is zero in PDiffIndex.Patches.
	To PDiffHash
	// Patch describes the decompressed ed script.
	Patch PDiffHash
	// Download describes the gzip file Packages.diff/<Name>.gz.
	Download PDiffHash
	// DownloadXZ describes the optional xz file Packages.diff/<Name>.xz; it is
	// zero when the Index lists none. Clients that only know gzip ignore it.
	DownloadXZ PDiffHash
}

PDiffPatch is one patch of a Packages.diff series.

The patch is fetched as Packages.diff/<Name>.gz (see DownloadName), which is Download.Size bytes with the digest Download.SHA256; decompressed it is the ed script of Patch. Applying it to the file with digest From.SHA256 gives the file with digest To.SHA256.

func (PDiffPatch) DownloadName added in v0.4.0

func (p PDiffPatch) DownloadName() string

DownloadName is the file name of the gzip download, relative to the Packages.diff directory.

type PDiffUpdate added in v0.4.0

type PDiffUpdate struct {
	// Changed reports that a patch was added to the history. It is false when
	// the new file is the file already published or when no patch could be made.
	Changed bool
	// Reset reports that the existing history was discarded: the file the
	// builder diffed from was not the one the old Index describes, the old
	// patches were unreadable, or no patch could be made.
	Reset bool
	// Skipped is why no patch was made for a change (ErrPDiffUnrepresentable or
	// ErrPDiffLimit); the history is then discarded and clients fetch the whole
	// file. It is nil otherwise.
	Skipped error
	// Patch is the one-step patch added, nil unless Changed.
	Patch *PDiffPatch
	// Index is the Index now published; nil when the directory holds no patches.
	Index *PDiffIndex
	// IndexData is the content written to Packages.diff/Index, for the hashes
	// of the Release; nil with Index.
	IndexData []byte
	// Written and Removed list the files (relative to the PDiffFS root) the
	// update created or replaced and deleted.
	Written, Removed []string
}

PDiffUpdate is the outcome of PDiffIndexBuilder.Update.

type Package

type Package struct {
	Package       string
	Version       string
	Architecture  string
	Maintainer    string
	Description   string
	Depends       string
	PreDepends    string
	Recommends    string
	Suggests      string
	Enhances      string
	Conflicts     string
	Breaks        string
	Replaces      string
	Provides      string
	Section       string
	Priority      string
	Homepage      string
	Bugs          string
	Size          int64
	InstalledSize int64
	MD5sum        string
	SHA1          string
	SHA256        string
	SHA512        string
	Filename      string
	Source        string
	SourceVersion string
	Essential     bool
	MultiArch     string
	BuiltUsing    string
	// Custom holds every field not listed above, by its spelling in the document.
	Custom map[string]string
}

Package holds the fields of a binary package that repositories and installers care about, read from a control file or a Packages entry.

type PackageSignature added in v0.4.0

type PackageSignature struct {
	// Member is the ar member name, such as "_gpgorigin".
	Member string
	// Scheme is the layout the member was read as.
	Scheme SignScheme
	// Role is the role the member name carries ("origin", "builder", ...).
	Role string
	// Signer describes the key that made a valid signature.
	Signer gpg.Verified
	// Err is nil for a valid signature, else the reason it is not, wrapping
	// ErrInvalidPackageSignature or, for a key outside the keyring,
	// gpg.ErrUnknownSigner.
	Err error
}

PackageSignature is the outcome of checking one signature member.

type ParseOptions

type ParseOptions struct {
	// MaxFileSize is the largest .deb accepted, in bytes. Zero means
	// MaxDebFileSize.
	MaxFileSize int64
}

ParseOptions tunes ParseDebFile. The zero value applies the defaults.

type Relation

type Relation struct {
	// Name is the package name.
	Name string
	// Arch is the ":arch" qualifier ("any", "native" or an architecture), or "".
	Arch string
	// Op is the version operator: "<<", "<=", "=", ">=", ">>" or the obsolete
	// "<" and ">" (which dpkg reads as "<=" and ">="). It is "" when the
	// relation has no version constraint.
	Op string
	// Version is the version the operator compares with.
	Version string
	// ArchRestrictions is the "[amd64 !i386 linux-any]" list: the relation is
	// in force only for the host architectures it selects (see
	// [Relation.AppliesTo]). Nil when there is none.
	ArchRestrictions []Restriction
	// ProfileGroups are the "<!nocheck> <stage1 cross>" groups: the relation
	// is in force when every term of at least one group holds for the active
	// build profiles. Nil when there is none.
	ProfileGroups [][]Restriction
}

Relation is one package reference of a dependency field: name, optional architecture qualifier, optional version constraint, and the architecture and build-profile restrictions of a source package's Build-Depends.

func (Relation) AppliesTo added in v0.3.1

func (r Relation) AppliesTo(hostArch string, profiles []string) bool

AppliesTo reports whether the relation is in force for a build on hostArch with the given active build profiles: both its architecture restriction and its profile restrictions must select it. A relation without restrictions always applies. This is the evaluation dpkg-checkbuilddeps does.

func (Relation) Satisfied

func (r Relation) Satisfied(version string) bool

Satisfied reports whether version meets the constraint of the relation. A relation without an operator is met by any version. The obsolete operators "<" and ">" mean "<=" and ">=", as they do for dpkg. An unknown operator is met by no version.

func (Relation) String

func (r Relation) String() string

String renders the relation in canonical control-file syntax: "name[:arch] (op version) [architectures] <profiles> <profiles>".

func (Relation) TargetArch added in v0.3.1

func (r Relation) TargetArch(dependerArch, nativeArch string) (arch string, anyArch bool)

TargetArch resolves the architecture qualifier of a relation. dependerArch is the architecture of the package that holds the relation and nativeArch the architecture of the system. It returns the architecture the relation names, and any=true for ":any", which names every architecture. A relation without qualifier names the architecture of its package, ":native" the one of the system, and an architecture qualifier itself. An architecture "all" depender counts as the system's.

type Release

type Release struct {
	Origin        string
	Label         string
	Suite         string
	Version       string
	Codename      string
	Date          time.Time
	ValidUntil    time.Time
	Architectures []string
	Components    []string
	Description   string
	// NotAutomatic ("NotAutomatic: yes") marks a repository whose packages must
	// not be installed or upgraded to without an explicit request (pin
	// priority 1); with ButAutomaticUpgrades the installed ones are upgraded
	// (pin priority 100).
	NotAutomatic, ButAutomaticUpgrades bool
	// AcquireByHash ("Acquire-By-Hash: yes") says the by-hash tree (see
	// ByHashPath) of the repository is complete: a client fetches the indexes
	// by their digest and is immune to a repository that is updated while it
	// downloads.
	AcquireByHash bool
	// SignedBy is the Signed-By field: the fingerprints of the keys that may
	// sign the repository, which a client may enforce. It may span lines.
	SignedBy string
	// NoSupportForArchitectureAll is the "No-Support-for-Architecture-all"
	// field: "Packages" says the architecture-specific Packages indexes do not
	// carry the architecture all packages and apt must fetch the
	// binary-all index.
	NoSupportForArchitectureAll string
	// Changelogs is the Changelogs field: the URL template of the changelog
	// server, or "no".
	Changelogs string
	// Snapshots is the Snapshots field: the URL template of the snapshot
	// service of the archive.
	Snapshots string
	// Extra holds the fields the type has no member for, by name as written,
	// so that a Release read and marshalled again loses none.
	Extra map[string]string
	// Files lists the index files by Path, relative to dists/<dist>/.
	Files map[string]FileInfo
}

Release is the content of a Release file: the description of a distribution and the checksums of its index files.

func ParseRelease

func ParseRelease(data []byte) (*Release, error)

ParseRelease parses a Release or InRelease document. A clear-signed document is unwrapped without verifying its signature; verify first (see VerifyInRelease) when the source is not trusted. Malformed checksum lines are skipped; a checksum that is not a hex digest of the right length, a listed path that is not a plain relative path, or two sections disagreeing on a file's size fail with ErrInvalidRelease.

Example
package main

import (
	"fmt"
	"log"
	"time"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	packages := []byte("Package: hello\nVersion: 1.0\nArchitecture: amd64\n\n")

	release := &deb.Release{
		Suite:         "stable",
		Codename:      "bookworm",
		Date:          time.Date(2025, 3, 4, 5, 6, 7, 0, time.UTC),
		Architectures: []string{"amd64"},
		Components:    []string{"main"},
	}
	release.AddFile(deb.HashBytes("main/binary-amd64/Packages", packages))

	parsed, err := deb.ParseRelease(release.Marshal())
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(parsed.Codename, parsed.Date.Format(time.RFC3339))
	fmt.Println(parsed.HasIndex("main", "amd64"), parsed.HasIndex("main", "arm64"))
	fmt.Println(parsed.PackagesVariants("main", "amd64"))
	fmt.Println(parsed.Files["main/binary-amd64/Packages"].Size)
}
Output:
bookworm 2025-03-04T05:06:07Z
true false
[main/binary-amd64/Packages]
49

func (*Release) AddFile

func (r *Release) AddFile(fi FileInfo)

AddFile records a file in the listing.

func (*Release) ByHashRefs added in v0.4.0

func (r *Release) ByHashRefs(indexPath string) []ByHashRef

ByHashRefs lists the by-hash paths of a file the Release lists, strongest digest first. A Release lists the digests of an index in its checksum sections; one without any digest of the file yields nothing.

func (*Release) CheckValidity

func (r *Release) CheckValidity(now time.Time) error

CheckValidity returns ErrReleaseExpired when the Release has a Valid-Until date that lies before now. A Release without one never expires.

func (*Release) HasIndex

func (r *Release) HasIndex(comp, arch string) bool

HasIndex reports whether the Release lists a Packages index for comp and arch in any compression.

func (*Release) IndexPaths added in v0.4.0

func (r *Release) IndexPaths(comp, arch, kind string) []string

IndexPaths lists the paths of the index of the given kind (see IndexPath and the IndexPackages... constants) that the Release lists, best compression first. It is empty when the Release lists none.

Example
package main

import (
	"fmt"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	rel := &deb.Release{}
	for _, p := range []string{
		"main/binary-amd64/Packages", "main/binary-amd64/Packages.gz", "main/binary-amd64/Packages.xz",
		"main/Contents-amd64.gz", "main/i18n/Translation-de.bz2", "main/i18n/Translation-en",
	} {
		rel.AddFile(deb.FileInfo{Path: p, Size: 1})
	}

	// Best compression first.
	fmt.Println(rel.IndexPaths("main", "amd64", deb.IndexPackages))
	fmt.Println(rel.IndexPaths("main", "amd64", deb.IndexContents))
	fmt.Println(rel.IndexPaths("main", "", deb.IndexTranslationPrefix+"de"))
	fmt.Println(rel.TranslationLanguages("main"))
	fmt.Println(deb.IndexPath("main", "arm64", deb.IndexContentsUdeb))
}
Output:
[main/binary-amd64/Packages.xz main/binary-amd64/Packages.gz main/binary-amd64/Packages]
[main/Contents-amd64.gz]
[main/i18n/Translation-de.bz2]
[de en]
main/Contents-udeb-arm64

func (*Release) IndexVariants added in v0.4.0

func (r *Release) IndexVariants(base string) []IndexVariant

IndexVariants returns the compressions of the index base (a path without suffix, see IndexPath) that the Release lists, best first: .xz, .zst, .gz, .bz2, .lz4, then the plain file.

func (*Release) Marshal

func (r *Release) Marshal() []byte

Marshal renders the Release in the layout of the Debian archive, see ReleaseStyleDebian. Files are listed by path, in the MD5Sum, SHA1, SHA256 and SHA512 sections, and only with the digests they have. Empty header fields and zero dates are omitted.

func (*Release) MarshalStyle added in v0.4.0

func (r *Release) MarshalStyle(style ReleaseStyle) []byte

MarshalStyle renders the Release in the given layout.

Example
package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	rel := &deb.Release{
		Origin:        "Example",
		Suite:         "stable",
		Codename:      "bookworm",
		Date:          time.Date(2025, 3, 4, 5, 6, 7, 0, time.UTC),
		AcquireByHash: true,
		Architectures: []string{"amd64"},
		Components:    []string{"main"},
	}

	// The layout of the Debian archive...
	fmt.Print(strings.Join(strings.Split(string(rel.Marshal()), "\n")[:5], "\n"), "\n")
	// ...and the one apt-ftparchive release writes: fields sorted by name, a
	// numeric time zone.
	fmt.Print(strings.Join(strings.Split(string(rel.MarshalStyle(deb.ReleaseStyleAptFTPArchive)), "\n")[:5], "\n"), "\n")
}
Output:
Origin: Example
Suite: stable
Codename: bookworm
Date: Tue, 04 Mar 2025 05:06:07 UTC
Acquire-By-Hash: yes
Acquire-By-Hash: yes
Architectures: amd64
Codename: bookworm
Components: main
Date: Tue, 04 Mar 2025 05:06:07 +0000

func (*Release) PackagesCandidates

func (r *Release) PackagesCandidates(comp, arch string) []string

PackagesCandidates is PackagesVariants, except that a Release listing none of them (one that only carries by-hash entries) yields the usual .xz, .gz and plain paths to try.

func (*Release) PackagesVariants

func (r *Release) PackagesVariants(comp, arch string) []string

PackagesVariants is IndexPaths for the Packages index of component comp and architecture arch.

func (*Release) TranslationLanguages added in v0.4.0

func (r *Release) TranslationLanguages(comp string) []string

TranslationLanguages lists the languages of the Translation files the Release lists for component comp, sorted.

type ReleaseStyle added in v0.4.0

type ReleaseStyle int

ReleaseStyle selects the layout Release.MarshalStyle writes. Both are valid for every client; they differ in the order of the header fields and in the width of the size column, which is what makes a rendered Release byte-identical to the one the matching tool writes.

const (
	// ReleaseStyleDebian is the layout of the Debian archive (dak): the fields
	// in the conventional order (Origin, Label, Suite, Version, Codename,
	// Changelogs, Snapshots, Date, Valid-Until, NotAutomatic,
	// ButAutomaticUpgrades, Acquire-By-Hash, Signed-By,
	// No-Support-for-Architecture-all, Architectures, Components, Description,
	// then unknown fields by name) and sizes right-aligned in 8 columns.
	ReleaseStyleDebian ReleaseStyle = iota
	// ReleaseStyleAptFTPArchive is the layout of apt-ftparchive release (apt
	// 2.6): the header fields sorted by name, dates with a numeric zone
	// ("+0000") and sizes right-aligned in 16 columns. apt-ftparchive writes
	// only the fields Origin, Label, Suite, Version, Codename, Date,
	// Valid-Until, NotAutomatic, ButAutomaticUpgrades, Acquire-By-Hash,
	// Architectures, Components and Description; the other fields of the type
	// are rendered too, in name order.
	ReleaseStyleAptFTPArchive
)

type Restriction added in v0.3.1

type Restriction struct {
	// Name is the architecture, architecture wildcard ("linux-any",
	// "any-arm64") or build profile, as written without the "!".
	Name string
	// Negated is true when the term was written with a "!".
	Negated bool
}

Restriction is one term of an architecture restriction ("[amd64 !i386]") or of a build-profile restriction ("<!nocheck>"): a name, optionally negated.

func (Restriction) String added in v0.3.1

func (t Restriction) String() string

String renders the term as written.

type ScriptModes added in v0.4.0

type ScriptModes struct {
	Preinst   fs.FileMode
	Postinst  fs.FileMode
	Prerm     fs.FileMode
	Postrm    fs.FileMode
	Config    fs.FileMode
	Templates fs.FileMode
}

ScriptModes holds the permission bits of the script members of the control archive. See Scripts.Modes.

type Scripts

type Scripts struct {
	Preinst  string
	Postinst string
	Prerm    string
	Postrm   string
	// Config is the debconf config script and Templates the debconf templates.
	Config    string
	Templates string

	// Modes are the permissions of the members; zero selects 0755 for the
	// scripts and Config and 0644 for Templates. dpkg refuses a maintainer
	// script (Preinst, Postinst, Prerm, Postrm) whose mode is not between 0555
	// and 0775 with no special bits, which Validate checks.
	Modes ScriptModes
}

Scripts holds the maintainer scripts and debconf files of a package. An empty field is not written. The scripts are written as given, except that RemoveScriptHeader is put in front of Prerm and Postrm.

type Shlib added in v0.4.0

type Shlib struct {
	// Type is the package type the line is for: "" for a deb, "udeb" for
	// udebs ("udeb: libfoo 1 libfoo-udeb").
	Type string
	// Library is the name of the library as in its soname without ".so.N":
	// "libfoo" for libfoo.so.1.
	Library string
	// Version is the soname version, "1" for libfoo.so.1.
	Version string
	// Dependencies is the dependency a package linking with the library gets:
	// "libfoo1 (>= 1.2)".
	Dependencies []Alternatives
}

Shlib is one line of the shlibs control file, deb-shlibs(5): the shared library the package provides and the dependency a package linking with it needs.

func ParseShlibs added in v0.4.0

func ParseShlibs(r io.Reader) ([]Shlib, error)

ParseShlibs parses a shlibs control file. Blank lines and "#" comments are skipped. A malformed line fails with ErrInvalidControlFormat.

func (Shlib) String added in v0.4.0

func (s Shlib) String() string

String renders the line of the shlibs file, without the final newline.

type SignOptions added in v0.4.0

type SignOptions struct {
	// Scheme selects the signature layout.
	Scheme SignScheme
	// Role is the signing role: "origin" (default), "maint" or "archive" for
	// debsigs, and "builder" (default), "uploader", "maint" ... for dpkg-sig.
	// It becomes the member name "_gpg" + Role.
	Role string
	// Signer is the identity recorded in a dpkg-sig manifest. Empty means the
	// key fingerprint.
	Signer string
	// Time is the date recorded in the member header and in a dpkg-sig
	// manifest. Zero means time.Now().
	Time time.Time
}

SignOptions tunes SignPackage. The zero value signs with the debsigs scheme and the default role of that scheme.

type SignScheme added in v0.4.0

type SignScheme int

SignScheme selects the layout of a package signature.

const (
	// SchemeDebsigs is the debsigs layout, checked by debsig-verify: a binary
	// or armored detached signature, in the member "_gpg" + role, over the
	// concatenation of the content of debian-binary, the control archive and the
	// data archive.
	SchemeDebsigs SignScheme = iota
	// SchemeDpkgSig is the dpkg-sig layout: a clear-signed manifest listing the
	// size, MD5 and SHA-1 of the members, in the member "_gpg" + role.
	SchemeDpkgSig
)

func (SignScheme) String added in v0.4.0

func (s SignScheme) String() string

String returns the scheme name.

type SignatureMember added in v0.4.0

type SignatureMember struct {
	// Name is the member name, such as "_gpgorigin".
	Name string
	// Data is the raw content of the member.
	Data []byte
}

SignatureMember is one package signature member of the ar archive.

type SignedRelease

type SignedRelease struct {
	// Release is the document as signed, published as dists/<dist>/Release.
	Release []byte
	// InRelease is the clear-signed document, dists/<dist>/InRelease.
	InRelease []byte
	// ReleaseGPG is the armored detached signature, dists/<dist>/Release.gpg.
	ReleaseGPG []byte
	// Fingerprint is the fingerprint of the signing key.
	Fingerprint string
}

SignedRelease is a Release document with the signatures a repository publishes next to it.

func SignRelease

func SignRelease(signer gpg.Signer, release []byte) (*SignedRelease, error)

SignRelease signs a Release document with signer and returns the three files apt reads: Release, InRelease and Release.gpg.

type Spec

type Spec struct {
	// Name is the package name. Required.
	Name string
	// Epoch, Version and Release make the version "[epoch:]version[-release]".
	// Epoch and Release are optional; Version is required.
	Epoch   string
	Version string
	Release string

	// Architecture is the Architecture field ("amd64", "all", ...). Required.
	Architecture string
	// MultiArch is the Multi-Arch field. When empty and Architecture is "all" it
	// is "foreign".
	MultiArch string

	Section  string
	Priority string

	Maintainer string
	// SourcePkg is the Source field.
	SourcePkg string
	// URL is the Homepage field.
	URL  string
	Bugs string
	// Description is the synopsis on its first line, the long description on the
	// following ones. A blank line in it is encoded as " .".
	Description string

	// InstalledSize is the Installed-Size field in KiB. When zero it is computed
	// from the payload.
	InstalledSize int64

	// Essential and Protected set the fields of that name to "yes".
	Essential bool
	Protected bool

	// Relationship fields, typed as ParseRelations returns them (see
	// ParseRelationList to build them from control-file syntax and
	// NormalizeDependency to convert PKGBUILD syntax). A binary package may not
	// carry architecture or profile restrictions, Provides and Built-Using
	// take only "=", and only Depends, Pre-Depends, Recommends, Suggests and
	// Enhances take alternatives; Validate enforces it.
	Provides   []Alternatives
	PreDepends []Alternatives
	Depends    []Alternatives
	Conflicts  []Alternatives
	Breaks     []Alternatives
	Replaces   []Alternatives
	Recommends []Alternatives
	Suggests   []Alternatives
	Enhances   []Alternatives
	BuiltUsing []Alternatives
	// StaticBuiltUsing is the Static-Built-Using field: like BuiltUsing, for
	// the sources of what a statically linked binary embeds.
	StaticBuiltUsing []Alternatives

	// Fields are further control fields, written in their order after the
	// fields above and before Description: Rules-Requires-Root, Important,
	// Build-Essential, Origin, Original-Maintainer, Tag, Description-md5,
	// Vcs-*, X-* and any other well-formed name. The fields the members of
	// Spec write are rejected here. Fields with a defined syntax are checked.
	Fields []Field

	// Conffiles lists the configuration files; a leading "/" is added when
	// missing.
	Conffiles []string

	// Triggers, Shlibs and Symbols fill the triggers, shlibs and symbols
	// members of the control archive; a member is written when its list is
	// not empty.
	Triggers []Trigger
	Shlibs   []Shlib
	Symbols  []SymbolsLibrary

	// ExtraControl holds further members of the control archive, in order.
	ExtraControl []ControlMember

	// Licenses and Copyrights fill the copyright file of the control archive. The
	// file is written when Licenses is not empty.
	Licenses   []string
	Copyrights []string

	Scripts Scripts

	// Changelog, when not empty, is stored gzip-compressed as
	// usr/share/doc/<name>/changelog.Debian.gz.
	Changelog []byte

	// Compression is the compression of the control and data archives: "zstd"
	// (the default when empty), "gzip", "xz" or "none".
	Compression string
	// CompressionLevel is the level of the data archive compression: 1 is the
	// fastest, MaxGzipLevel, MaxXZLevel and MaxZstdLevel the smallest output;
	// zero is the default of the method. "none" takes only zero.
	CompressionLevel int

	// ControlCompression and ControlCompressionLevel choose the compression of
	// the control archive on its own. An empty ControlCompression is
	// Compression, and the level is then CompressionLevel; set a level only
	// together with a method.
	ControlCompression      string
	ControlCompressionLevel int

	// ModTime is the modification time of the ar members, of the control
	// archive entries and of the generated changelog; zero is the Unix epoch.
	// Set it from SOURCE_DATE_EPOCH (see SourceDateEpoch) for reproducible
	// output.
	ModTime time.Time
	// ClampMTime limits the modification time of every data entry to ModTime,
	// as "dpkg-deb --clamp-mtime" does: an entry that is older keeps its time,
	// a newer one gets ModTime. It is what makes a build from a source tree
	// reproducible when files are newer than SOURCE_DATE_EPOCH.
	ClampMTime bool
}

Spec describes a binary package to write. It carries everything the control file, the control archive and the metadata files are made of; the payload goes with it to Write as a list of Entry values.

func (*Spec) FileName

func (s *Spec) FileName() string

FileName is the conventional file name of the package, name_version_arch.deb.

func (*Spec) FullVersion

func (s *Spec) FullVersion() string

FullVersion returns the version as the Version field spells it.

func (*Spec) Validate

func (s *Spec) Validate() error

Validate checks the spec and returns an error wrapping ErrInvalidSpec for a name, version or architecture dpkg would reject, or for a one-line field that holds a line break.

type Stanza

type Stanza struct {
	Package      string
	Version      string
	Architecture string
	// Filename is the pool-relative path the entry downloads from.
	Filename string
	SHA256   string
	// Text is the stanza as read (comments dropped), ending with a blank line.
	Text string
}

Stanza is one package entry of a Packages file read from an index: the identifying fields a merge keys on plus the verbatim text.

type State added in v0.3.1

type State string

State is the third word of a dpkg Status field: how far the package got.

const (
	StateNotInstalled    State = "not-installed"
	StateConfigFiles     State = "config-files"
	StateHalfInstalled   State = "half-installed"
	StateUnpacked        State = "unpacked"
	StateHalfConfigured  State = "half-configured"
	StateTriggersAwaited State = "triggers-awaited"
	StateTriggersPending State = "triggers-pending"
	StateInstalled       State = "installed"
)

The values dpkg writes.

type Status added in v0.3.1

type Status struct {
	Want  Want
	Flag  Flag
	State State
}

Status is a parsed dpkg Status field, "install ok installed". The zero value is the status of a stanza that has none.

func ParseStatus added in v0.3.1

func ParseStatus(value string) (Status, error)

ParseStatus parses the value of a Status field: three words, each one of the values dpkg writes. Anything else fails with ErrInvalidStatus.

func (Status) Installed added in v0.3.1

func (s Status) Installed() bool

Installed reports whether the package is installed: its state is "installed", whatever the administrator wants done with it (a held package, "hold ok installed", is installed, and so is one marked for removal).

The states before it are not counted: "unpacked" and "half-configured" are a package whose configuration did not finish, "half-installed" one whose unpacking did not, "config-files" a removed package whose configuration files remain, and "triggers-awaited" and "triggers-pending" one that waits for a trigger to run. dpkg-query lists the first and last of these with the abbreviations "iU", "iF", "iH", "rc", "iW" and "it".

func (Status) String added in v0.3.1

func (s Status) String() string

String renders the status as dpkg writes it, "install ok installed", or "" for the zero value.

type StatusDB added in v0.3.1

type StatusDB struct {
	// contains filtered or unexported fields
}

StatusDB is a dpkg status file. It is read-only and safe for concurrent use: every call reads the file again.

Example

Read the packages a dpkg status file records as installed. On a host, FindStatus("/") and OpenStatus give the real file.

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	const text = `Package: hello
Status: hold ok installed
Version: 2.10-5
Architecture: amd64
Provides: greeter (= 1)

Package: wget
Status: deinstall ok config-files
Version: 1.25.0-2
Architecture: amd64
`

	db := deb.NewStatusDB(strings.NewReader(text), int64(len(text)), deb.StatusOptions{})

	for entry, err := range db.Entries(context.Background()) {
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println(entry.Package.Package, entry.Package.Version, entry.Status, entry.Status.Installed())
	}

	names, _ := db.InstalledNames(context.Background())
	provides, _ := db.InstalledProvides(context.Background())
	fmt.Println(names, provides)
}
Output:
hello 2.10-5 hold ok installed true
wget 1.25.0-2 deinstall ok config-files false
[hello] [greeter hello]

func NewStatusDB added in v0.3.1

func NewStatusDB(r io.ReaderAt, size int64, opts StatusOptions) *StatusDB

NewStatusDB reads the status text that r holds, size bytes. Close does not close r. A size over StatusOptions.MaxBytes makes every read fail with ErrTooLarge.

func OpenStatus added in v0.3.1

func OpenStatus(path string, opts StatusOptions) (*StatusDB, error)

OpenStatus opens the dpkg status file at path. The file is only read, and not kept locked, so dpkg can run at the same time; a file that dpkg is rewriting is read as of the moment of each call.

func (*StatusDB) Close added in v0.3.1

func (db *StatusDB) Close() error

Close releases the file of a database opened with OpenStatus.

func (*StatusDB) Entries added in v0.3.1

func (db *StatusDB) Entries(ctx context.Context) iter.Seq2[*StatusEntry, error]

Entries iterates over the stanzas of the file in order, installed or not. A stanza without a Package field is skipped, and reported at debug level to StatusOptions.Logger; a Status field that is not valid leaves the entry's Status at its zero value. The iteration ends with an error when the file is over its limits, cannot be read, or when ctx is done; the error is the last pair it yields. Stopping early releases everything.

func (*StatusDB) InstalledNames added in v0.3.1

func (db *StatusDB) InstalledNames(ctx context.Context) ([]string, error)

InstalledNames returns the names of the installed packages (see Status.Installed), sorted and without duplicates. A name has no architecture qualifier and counts once however many architectures of the package are installed.

func (*StatusDB) InstalledProvides added in v0.3.1

func (db *StatusDB) InstalledProvides(ctx context.Context) ([]string, error)

InstalledProvides returns the capabilities the installed packages provide (see Status.Installed), as names without version constraint or architecture qualifier, sorted and without duplicates. The name of each package is included, as it provides itself.

func (*StatusDB) List added in v0.3.1

func (db *StatusDB) List(ctx context.Context) ([]*StatusEntry, error)

List returns every stanza: StatusDB.Entries collected into a slice.

type StatusEntry added in v0.3.1

type StatusEntry struct {
	// Status is the parsed Status field. It is the zero value when the stanza
	// has none or the field is not valid.
	Status Status
	// Package holds the typed fields of the stanza. Unlike a package read with
	// [ControlFile.ParsePackage], Version and Architecture may be empty: dpkg
	// keeps stanzas for packages that were purged, or that only have a
	// configuration.
	Package *Package
	// Control is the stanza as written: every field, in document order, with
	// logical values (see [ControlFile]). Rendering it with [ControlFile.String]
	// gives a stanza dpkg reads back.
	Control *ControlFile
}

StatusEntry is one stanza of the dpkg status file.

type StatusOptions added in v0.3.1

type StatusOptions struct {
	// Logger receives debug messages about skipped stanzas. Optional: nil
	// discards them.
	Logger *slog.Logger
	// MaxEntries bounds the stanzas read from a status file; reading more
	// fails with [ErrTooLarge]. Zero selects [DefaultMaxStatusEntries].
	MaxEntries int
	// MaxBytes bounds the size of the file read; a larger one fails with
	// [ErrTooLarge]. Zero selects [DefaultMaxStatusBytes].
	MaxBytes int64
}

StatusOptions configures OpenStatus, NewStatusDB and ReadInfoList. The zero value is usable.

type Symbol added in v0.4.0

type Symbol struct {
	// Name is the symbol as written, with its tags and quotes when it has
	// them: "foo@Base", `(c++|optional)"bar(int)@Base"`.
	Name string
	// MinVersion is the version of the library that introduced the symbol.
	MinVersion string
	// Template is the index of the alternative dependency template the symbol
	// refers to, or -1 for the main one (no third column).
	Template int
}

Symbol is one symbol line of a symbols file.

func (Symbol) String added in v0.4.0

func (s Symbol) String() string

type SymbolsLibrary added in v0.4.0

type SymbolsLibrary struct {
	// SOName is the soname of the library: "libfoo.so.1".
	SOName string
	// Dependency is the main dependency template: "libfoo1 #MINVER#".
	Dependency string
	// Alternatives are the alternative dependency templates, the "| ..."
	// lines.
	Alternatives []string
	// Fields are the "* Field: value" lines, such as Build-Depends-Package.
	Fields []Field
	// Symbols are the symbols the library exports.
	Symbols []Symbol
}

SymbolsLibrary is one library block of a symbols file, deb-symbols(5).

func ParseSymbols added in v0.4.0

func ParseSymbols(r io.Reader) ([]SymbolsLibrary, error)

ParseSymbols parses a symbols control file. Blank lines and "#" comments are skipped. A malformed line fails with ErrInvalidControlFormat.

type TranslationBuilder added in v0.4.0

type TranslationBuilder struct {
	// contains filtered or unexported fields
}

TranslationBuilder accumulates the descriptions of one language and renders them as a Translation-<lang> file the way a repository publishes it: one paragraph per distinct description (Description-md5), sorted by package name then md5, so the same input gives the same bytes. The zero value is not usable; create one with NewTranslationBuilder.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/M0Rf30/pkgformat/deb"
)

func main() {
	en := deb.NewTranslationBuilder("en")
	_ = en.Add(deb.TranslationEntry{Package: "hello", Description: "friendly greeter\nPrints a greeting."})

	md5sum := deb.DescriptionMD5("friendly greeter\nPrints a greeting.")

	de := deb.NewTranslationBuilder("de")
	// A translation is filed under the md5 of the English description.
	_ = de.Add(deb.TranslationEntry{Package: "hello", DescriptionMD5: md5sum, Description: "freundlicher Gruesser\nGibt einen Gruss aus."})

	fmt.Print(string(de.Bytes()))

	stanza := deb.FormatPackagesEntryShort(deb.IndexEntry{
		Name: "hello", Version: "1.0", Arch: "all", Filename: "pool/main/h/hello/hello_1.0_all.deb", Size: 1,
		Control: map[string]string{"Description": "friendly greeter\nPrints a greeting."},
	})
	fmt.Println(strings.Contains(stanza, "Description: friendly greeter\nDescription-md5: "+md5sum))
}
Output:
Package: hello
Description-md5: 40d9ed3e151e7006a11742c09a08ffa0
Description-de: freundlicher Gruesser
 Gibt einen Gruss aus.

true

func NewTranslationBuilder added in v0.4.0

func NewTranslationBuilder(lang string) *TranslationBuilder

NewTranslationBuilder returns a builder for the language: "en", "de", "pt_BR". A language that is not a plain code makes every Add fail with ErrInvalidTranslation.

func (*TranslationBuilder) Add added in v0.4.0

Add records a description. An entry that has no DescriptionMD5 is keyed by the md5 of its own description (right for English); one without a package name or a description fails with ErrInvalidTranslation. A description that is already there (same md5) is kept as first added: packages that share a description share one paragraph.

func (*TranslationBuilder) AddIndexEntry added in v0.4.0

func (b *TranslationBuilder) AddIndexEntry(e IndexEntry) error

AddIndexEntry records the description of a package of a Packages index (the English one, for a Translation-en builder). A package without a description is skipped.

func (*TranslationBuilder) Bytes added in v0.4.0

func (b *TranslationBuilder) Bytes() []byte

Bytes renders the Translation file.

func (*TranslationBuilder) Compressed added in v0.4.0

func (b *TranslationBuilder) Compressed(c Compression) ([]byte, error)

Compressed renders the file compressed with c.

func (*TranslationBuilder) Entries added in v0.4.0

func (b *TranslationBuilder) Entries() []TranslationEntry

Entries returns the descriptions in file order.

func (*TranslationBuilder) Language added in v0.4.0

func (b *TranslationBuilder) Language() string

Language is the language of the builder.

func (*TranslationBuilder) Len added in v0.4.0

func (b *TranslationBuilder) Len() int

Len is the number of descriptions.

func (*TranslationBuilder) WriteTo added in v0.4.0

func (b *TranslationBuilder) WriteTo(w io.Writer, c Compression) (int64, error)

WriteTo writes the file compressed with c to w and returns the number of bytes written to w.

type TranslationEntry added in v0.4.0

type TranslationEntry struct {
	// Package is the package name.
	Package string
	// DescriptionMD5 is the Description-md5 of the English description: the key
	// that ties the entry to the packages whose Packages stanza carries
	// Description-md5 instead of the description.
	DescriptionMD5 string
	// Description is the description in the language: the short description,
	// then the extended one on following lines, in the logical form the control
	// file reader returns (continuation lines without their leading blank).
	Description string
}

TranslationEntry is one package description of a Translation-<lang> file.

type Trigger added in v0.4.0

type Trigger struct {
	// Activate is true for "activate" lines and false for "interest" lines.
	Activate bool
	// Await is the "-await" or "-noawait" suffix of the directive, if any.
	Await TriggerAwait
	// Name is the trigger name: an absolute path for a file trigger, any
	// other word for an explicit trigger.
	Name string
}

Trigger is one line of the triggers control file, deb-triggers(5): a package declares an interest in a trigger name or activates one.

func ParseTriggers added in v0.4.0

func ParseTriggers(r io.Reader) ([]Trigger, error)

ParseTriggers parses a triggers control file. Blank lines and lines starting with "#" are skipped. A malformed line fails with ErrInvalidControlFormat.

func (Trigger) String added in v0.4.0

func (t Trigger) String() string

String renders the trigger as one line of the triggers file, without the final newline.

type TriggerAwait added in v0.4.0

type TriggerAwait int

TriggerAwait tells whether the package that activates a trigger waits for the triggered package, or whether a package that is interested in a trigger makes the activating one wait.

const (
	AwaitDefault TriggerAwait = iota
	AwaitYes
	AwaitNo
)

The values of TriggerAwait. The zero value writes no suffix: dpkg treats it as "await".

type Trust

type Trust struct {
	// Keyring holds the trusted public keys. Nil or empty means no trust anchor.
	Keyring *gpg.Keyring
	// KeyringErr is the reason Keyring is empty (an unreadable file, ...). It is
	// the error returned when no keyring is available and AllowUnverified is
	// not set; nil gives ErrNoTrustAnchor.
	KeyringErr error
	// AllowUnverified lets unsigned documents, unknown signers and a missing
	// keyring through.
	AllowUnverified bool
	// Logger receives the outcome of every verification. Nil is silent.
	Logger *slog.Logger
	// Source names the repository in log records, normally its base URL.
	Source string
}

Trust is the policy for accepting a Release or InRelease document.

  • A signature that exists and does not verify (altered data, expired or revoked key) is always an error, even with AllowUnverified: it points to an attack or a broken mirror, and ignoring it is worse than not verifying at all.
  • No keys, a signature by an unknown key, or no signature at all fail unless AllowUnverified is set, in which case the document is accepted unverified and a warning is logged.

func (Trust) VerifyInRelease

func (t Trust) VerifyInRelease(data []byte) ([]byte, error)

VerifyInRelease verifies a clear-signed InRelease document under the policy and returns its signed text.

Example
package main

import (
	"bytes"
	"fmt"
	"log"

	"github.com/M0Rf30/pkgformat/deb"
	"github.com/M0Rf30/pkgformat/gpg"
)

func main() {
	entity, err := gpg.GenerateEntity("Repo", "", "repo@example.org", gpg.AlgorithmED25519)
	if err != nil {
		log.Fatal(err)
	}

	signer, err := gpg.NewLocalSignerFromEntity(entity)
	if err != nil {
		log.Fatal(err)
	}

	signed, err := deb.SignRelease(signer, []byte("Suite: stable\nCodename: bookworm\n"))
	if err != nil {
		log.Fatal(err)
	}

	keyring, err := signer.Keyring()
	if err != nil {
		log.Fatal(err)
	}

	trust := deb.Trust{Keyring: keyring}

	body, err := trust.VerifyInRelease(signed.InRelease)
	fmt.Printf("signed by the trusted key: %q %v\n", bytes.TrimSpace(body), err)

	// The same document with its content changed is rejected, even by a Trust
	// that accepts unverified repositories.
	forged := bytes.Replace(signed.InRelease, []byte("bookworm"), []byte("trixie"), 1)
	lenient := deb.Trust{Keyring: keyring, AllowUnverified: true}
	_, err = lenient.VerifyInRelease(forged)
	fmt.Println("forged:", err != nil)

	// Without a trust anchor, verification fails unless explicitly allowed.
	_, err = deb.Trust{}.VerifyInRelease(signed.InRelease)
	fmt.Println(err)
}
Output:
signed by the trusted key: "Suite: stable\nCodename: bookworm" <nil>
forged: true
deb: no usable trust anchor for source

func (Trust) VerifyReleaseGPG

func (t Trust) VerifyReleaseGPG(body, sig []byte, sigErr error) ([]byte, error)

VerifyReleaseGPG verifies a plain Release document against its detached signature under the policy and returns the Release unchanged. sigErr is the error of fetching the signature: when not nil the signature is treated as missing.

type Want added in v0.3.1

type Want string

Want is the first word of a dpkg Status field: what the administrator wants done with the package.

const (
	WantUnknown   Want = "unknown"
	WantInstall   Want = "install"
	WantHold      Want = "hold"
	WantDeinstall Want = "deinstall"
	WantPurge     Want = "purge"
)

The values dpkg writes.

type WriteOptions

type WriteOptions struct {
	// TempDir is where the compressed data archive is staged, because its size
	// must be known before it is copied into the package. Empty means the
	// system temporary directory.
	TempDir string
}

WriteOptions tunes Write. The zero value is valid.

Directories

Path Synopsis
Package apt is a client for Debian apt repositories that needs no apt installation: it refreshes package indexes, reads them, resolves dependencies and downloads packages with their integrity enforced.
Package apt is a client for Debian apt repositories that needs no apt installation: it refreshes package indexes, reads them, resolves dependencies and downloads packages with their integrity enforced.
Package source reads, verifies, unpacks, builds and indexes Debian source packages.
Package source reads, verifies, unpacks, builds and indexes Debian source packages.

Jump to

Keyboard shortcuts

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