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 version constraint, which Relation.Satisfied checks against a version. NormalizeDependency converts a "name>=version" dependency to control-file syntax.
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 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 FormatPackagesEntry(e IndexEntry) 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 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 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 Scripts
- type SignedRelease
- type Spec
- type Stanza
- type Trust
- type WriteOptions
Examples ¶
Constants ¶
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 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 ( // 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 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 FormatPackagesEntry ¶
func FormatPackagesEntry(e IndexEntry) string
FormatPackagesEntry renders a complete Packages stanza, terminated by a blank line, for the entry.
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 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 ParseRelations ¶
func ParseRelations(field string) ([]Alternatives, error)
ParseRelations parses a dependency field (Depends, Pre-Depends, Conflicts, Provides, ...) into its comma-separated entries, each a list of alternatives. Architecture restrictions ("[amd64]") and build profiles ("<!nocheck>") are accepted and dropped. 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]
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 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 ">". It is "" when the relation has no version constraint.
Op string
// Version is the version the operator compares with.
Version string
}
Relation is one package reference of a dependency field: name, optional architecture qualifier and optional version constraint.
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 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 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 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. |