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 ¶
- Constants
- Variables
- func ArchMatches(arch, pattern string) bool
- func ArchRestrictionApplies(hostArch string, terms []Restriction) bool
- func CompareVersions(a, b string) int
- func ControlFieldsToStore(fields map[string]string) map[string]string
- func DependencyNames(field string) []string
- func FileName(name, version, arch string) string
- func FindStatus(root string) (string, error)
- func FormatPackagesEntry(e IndexEntry) string
- func FormatRelations(rels []Alternatives) string
- func InReleasePath(dist string) string
- func NormalizeDependency(dep string) string
- func OpenIndex(r io.Reader, name string) (io.ReadCloser, error)
- func PackagesPath(dist, component, arch, ext string) string
- func PoolPath(component, packageName, filename string) string
- func ProfileRestrictionApplies(profiles []string, groups [][]Restriction) bool
- func ReadInfoList(fsys fs.FS, name, arch string, opts StatusOptions) ([]string, error)
- func ReleaseGPGPath(dist string) string
- func ReleasePath(dist string) string
- func ScanControl(r io.Reader, fn func(*ControlFile) error) error
- func ScanPackages(r io.Reader, fn func(Stanza) error) error
- func StripClearsign(data []byte) []byte
- func StripEpoch(v string) string
- func ValidVersion(v string) bool
- func Write(w io.Writer, spec *Spec, payload []Entry, opts WriteOptions) error
- func WriteFile(filePath string, spec *Spec, payload []Entry, opts WriteOptions) error
- type ARHeader
- type Alternatives
- type Compression
- type ControlFile
- func (cf *ControlFile) Get(field string) string
- func (cf *ControlFile) GetRequired(field string) (string, error)
- func (cf *ControlFile) Lookup(field string) (string, bool)
- func (cf *ControlFile) ParsePackage() (*Package, error)
- func (cf *ControlFile) Set(field, value string)
- func (cf *ControlFile) String() string
- type DebFile
- type Entry
- type ExtractOptions
- type FileInfo
- type Flag
- type Index
- type IndexEntry
- type Package
- type ParseOptions
- type Relation
- type Release
- func (r *Release) AddFile(fi FileInfo)
- func (r *Release) CheckValidity(now time.Time) error
- func (r *Release) HasIndex(comp, arch string) bool
- func (r *Release) Marshal() []byte
- func (r *Release) PackagesCandidates(comp, arch string) []string
- func (r *Release) PackagesVariants(comp, arch string) []string
- type Restriction
- type Scripts
- type SignedRelease
- type Spec
- type Stanza
- type State
- type Status
- type StatusDB
- func (db *StatusDB) Close() error
- func (db *StatusDB) Entries(ctx context.Context) iter.Seq2[*StatusEntry, error]
- func (db *StatusDB) InstalledNames(ctx context.Context) ([]string, error)
- func (db *StatusDB) InstalledProvides(ctx context.Context) ([]string, error)
- func (db *StatusDB) List(ctx context.Context) ([]*StatusEntry, error)
- type StatusEntry
- type StatusOptions
- type Trust
- type Want
- type WriteOptions
Examples ¶
Constants ¶
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.
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 )
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 )
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 )
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.
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.
const (
// MaxReleaseBytes bounds a Release or InRelease document.
MaxReleaseBytes = 16 << 20
)
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 ¶
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.
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.
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 )
var ErrNoSigner = errors.New("deb: no signer configured")
ErrNoSigner is returned by SignRelease when no signer is given.
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
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
InReleasePath is the location of the clear-signed InRelease file.
func NormalizeDependency ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
ReleaseGPGPath is the location of the detached Release signature.
func ReleasePath ¶
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 ¶
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 ¶
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 ¶
StripEpoch returns v without its numeric epoch ("1:2.0-1" is "2.0-1"), the form a package file name carries.
func ValidVersion ¶
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 ¶
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
Types ¶
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 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 ¶
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 ¶
ParseDebFileAt parses a .deb file with the default limits. See ParseDebFile.
func (*DebFile) Conffiles ¶
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.
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 ¶
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 ¶
HashBytes returns the FileInfo of data stored under path, with every digest computed.
func HashReader ¶
HashReader reads r to its end and returns its FileInfo with every digest computed.
type Flag ¶ added in v0.3.1
type Flag string
Flag is the second word of a dpkg Status field: the error flag.
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) AddText ¶
AddText appends a stanza as is, such as Stanza.Text. A stanza without a final blank line gets one.
func (*Index) Compressed ¶
func (ix *Index) Compressed(c Compression) ([]byte, error)
Compressed renders the index compressed with c.
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
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 ¶
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 ¶
String renders the relation in canonical control-file syntax: "name[:arch] (op version) [architectures] <profiles> <profiles>".
func (Relation) TargetArch ¶ added in v0.3.1
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 ¶
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) CheckValidity ¶
CheckValidity returns ErrReleaseExpired when the Release has a Valid-Until date that lies before now. A Release without one never expires.
func (*Release) HasIndex ¶
HasIndex reports whether the Release lists a Packages index for comp and arch in any compression.
func (*Release) Marshal ¶
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 ¶
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 ¶
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 ¶
FileName is the conventional file name of the package, name_version_arch.deb.
func (*Spec) FullVersion ¶
FullVersion returns the version as the Version field spells it.
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
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
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
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".
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
Close releases the file of a database opened with OpenStatus.
func (*StatusDB) Entries ¶ added in v0.3.1
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
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
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 ¶
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 ¶
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.
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.
Source Files
¶
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. |