deb

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 36 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
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, ParseRelease, SignRelease, Trust (InRelease and Release.gpg verification policy)
apt client apt.Update, apt.Load, (*apt.Cache): Lookup, ResolveVirtual, ResolveDeps, Download, DownloadClosure

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

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.

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); 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.

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.

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 (
	// 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.
	MaxControlFileSize = 1 << 20
)
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 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 (
	// MaxReleaseBytes bounds a Release or InRelease document.
	MaxReleaseBytes = 16 << 20
)
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.

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")
	// 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 (
	// 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 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 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 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 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 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 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 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 InReleasePath

func InReleasePath(dist string) string

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

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 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 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 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 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 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 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. The md5sums file and, when Spec.InstalledSize is zero, the Installed-Size are computed from the payload.

Example
package main

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

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

func main() {
	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:      []string{"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 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 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 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 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 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
	// 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.

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 and the type: fs.ModeDir for a
	// directory, fs.ModeSymlink for a symlink; any other type is rejected.
	Mode fs.FileMode
	// Linkname is the target of a symlink.
	Linkname 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 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 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.

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 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
	// 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) 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) Marshal

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

Marshal renders the Release. 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) 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 lists the paths of the Packages index of component comp and architecture arch that the Release lists, best compression first.

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 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
}

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 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

	// Relationship fields. Entries are in control-file syntax (see
	// NormalizeDependency to convert PKGBUILD syntax) and are joined with ", ".
	Provides   []string
	PreDepends []string
	Depends    []string
	Conflicts  []string
	Breaks     []string
	Replaces   []string
	Recommends []string
	Suggests   []string
	Enhances   []string
	BuiltUsing []string

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

	// 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

	// 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 for reproducible output.
	ModTime time.Time
}

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 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.

Jump to

Keyboard shortcuts

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