Documentation
¶
Overview ¶
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.
Sources ¶
ParseSourcesList and ParseSources822 turn the text of sources.list and deb822 .sources files into Source values; LoadSources reads them from a file and a directory the caller names. The package never looks at /etc/apt on its own: every path is an option.
Updating ¶
Update fetches the Release of every source (InRelease, or Release with Release.gpg), verifies its signature with deb.Trust against the keyring named by the source's Signed-By option or UpdateOptions.DefaultKeyrings, rejects an expired Release, then downloads the Packages index of each component and architecture, checking its size and SHA-256 against the verified Release. The indexes land in UpdateOptions.ListsDir under apt's own file names, so that apt itself can read them too. A signature that is present and wrong is always an error; a missing trust anchor, an unknown signer or an unsigned repository is accepted only with UpdateOptions.AllowUnverified.
Reading ¶
Load builds a Cache from a lists directory, and optionally a dpkg status file, whose path the caller gives. A Cache answers Lookup, ResolveVirtual and ResolveDeps, with Multi-Arch awareness: Multi-Arch: foreign packages are redirected to the host architecture and architecture-qualified names are inherited by dependencies. The highest Debian version wins when several repositories carry one package.
Downloading ¶
Cache.Download and Cache.DownloadClosure fetch .deb files into a directory. Each file is checked against the SHA-256 and size of the index while it is written, and a file that fails is not left behind. The result is a normal .deb for deb.ParseDebFileAt.
Transfers use the httpclient and download packages: size caps, retry with backoff, and a single retry over https when a plain http fetch fails transiently.
Index ¶
- Constants
- Variables
- func ArchFromGoarch(goarch string) string
- func BaseURLs(sources []Source) map[string]string
- func IsVerificationError(err error) bool
- func ListFileName(baseURL, suite, relPath string) string
- func LoadKeyring(signedBy string, defaults []string) (*gpg.Keyring, error)
- func Update(ctx context.Context, sources []Source, opts UpdateOptions) (int, error)
- type Cache
- func (c *Cache) AddEntry(info *PackageInfo)
- func (c *Cache) CapabilityCount() int
- func (c *Cache) Download(ctx context.Context, destDir string, pkgs []string, opts DownloadOptions) error
- func (c *Cache) DownloadClosure(ctx context.Context, destDir string, seeds []string, opts DownloadOptions) (resolved []*PackageInfo, unresolved []string, err error)
- func (c *Cache) HostArch() string
- func (c *Cache) InstalledNames() map[string]bool
- func (c *Cache) Lookup(name string) (PackageInfo, bool)
- func (c *Cache) PackageCount() int
- func (c *Cache) ResolveDeps(seeds []string) ([]*PackageInfo, []string, error)
- func (c *Cache) ResolveVirtual(name string) string
- type DownloadOptions
- type LoadOptions
- type PackageInfo
- type Source
- type UpdateError
- type UpdateOptions
Examples ¶
Constants ¶
const MaxDebBytes int64 = 2 << 30
MaxDebBytes caps one .deb download. Real packages top out around 500 MB; 2 GiB leaves room while still stopping an unbounded mirror stream.
const MaxSourcesFileBytes = 1 << 20
MaxSourcesFileBytes caps one sources.list or deb822 .sources file read by LoadSources.
Variables ¶
var ( // ErrTooLarge reports input over a size limit. ErrTooLarge = errors.New("apt: input too large") // ErrIntegrity reports a downloaded file whose size or digest differs from // what the verified Release or the package index declared. ErrIntegrity = errors.New("apt: integrity check failed") // ErrNoPackagesIndex reports a component and architecture that the Release // does not list. apt treats that as nothing to fetch. ErrNoPackagesIndex = errors.New("apt: no Packages index listed") // ErrNoSources reports an update without any source. ErrNoSources = errors.New("apt: no sources configured") // ErrNoListsDir reports an update without a lists directory. ErrNoListsDir = errors.New("apt: no lists directory given") // ErrPackageNotFound reports a package that is not in the index, or has no // downloadable file. ErrPackageNotFound = errors.New("apt: package not found in index") // ErrNoBaseURL reports an indexed package whose repository URL is unknown, // so it cannot be downloaded. ErrNoBaseURL = errors.New("apt: package has no repository URL") // ErrInvalidIndexEntry reports an index entry that cannot be downloaded // safely: a malformed SHA256, an out-of-range Size, or an unsafe Filename. ErrInvalidIndexEntry = errors.New("apt: invalid package index entry") )
var ErrDependencyDepth = errors.New("apt: dependency chain too deep")
ErrDependencyDepth is returned by ResolveDeps for a dependency chain deeper than maxResolveDepth, which only a hostile or corrupt index produces.
Functions ¶
func ArchFromGoarch ¶
ArchFromGoarch maps a runtime.GOARCH value to the Debian architecture name.
func BaseURLs ¶
BaseURLs maps the encoded host-and-path prefix of apt's list file names to the URL of the source. Of several sources with the same prefix the last wins.
func IsVerificationError ¶
IsVerificationError reports whether err is solely a signature verification failure (unknown signer or no trust anchor) and not a network or I/O error. A caller that already fetched enough indexes can downgrade such an error to a warning.
For the UpdateError that Update returns, "solely" means every failure in it is one: a network error next to a trust error is not downgraded.
func ListFileName ¶
ListFileName returns the name apt stores relPath of a repository under: ("https://archive.ubuntu.com/ubuntu/", "jammy", "main/binary-amd64/Packages.xz") gives "archive.ubuntu.com_ubuntu_dists_jammy_main_binary-amd64_Packages.xz". It returns "" for a URL that does not parse.
func LoadKeyring ¶
LoadKeyring returns the trust anchor of a source.
With a signedBy path (the Signed-By option) it loads exactly that keyring file or directory of keyrings. A path that is missing, or that holds no key, is an error that wraps deb.ErrNoTrustAnchor.
Without one it takes the union of every usable key found in defaults, which are keyring files or directories such as /etc/apt/trusted.gpg.d, in the same way apt trusts them. Paths that do not exist or cannot be parsed are skipped, as apt does; no key at all is deb.ErrNoTrustAnchor.
func Update ¶
Update fetches the binary Packages index of every component and architecture of every source, verifies the Release signature and every index's size and SHA-256 against it, and writes the indexes to opts.ListsDir.
Sources whose Release does not list an index for a component and architecture are skipped silently, as apt does. It returns how many (source, component, architecture) indexes are now in place, whether fetched or already current, and an *UpdateError holding everything that failed: a partial failure still reports the successes. Use IsVerificationError to tell trust failures from network ones.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache is an in-memory index of package metadata keyed by name and architecture, merged from apt package indexes and the dpkg status database. It is safe for concurrent use.
func Load ¶
func Load(opts LoadOptions) (*Cache, error)
Load reads the apt indexes of opts.ListsDir, then the dpkg status database of opts.StatusFile.
Like apt itself, Load tolerates what it cannot read: a missing directory, an unreadable or corrupt index. The returned Cache is never nil and holds everything that did load; the error, when not nil, joins one error per file that did not, so a caller can warn about them.
func NewCache ¶
NewCache returns an empty cache. hostArch is the architecture packages are looked up for when a name carries no qualifier; empty selects the one of the running program.
func (*Cache) AddEntry ¶
func (c *Cache) AddEntry(info *PackageInfo)
AddEntry inserts or replaces an entry. Use it to set a cache up by hand, before it is shared.
func (*Cache) CapabilityCount ¶
CapabilityCount is the number of virtual package names (Provides) known.
func (*Cache) Download ¶
func (c *Cache) Download(ctx context.Context, destDir string, pkgs []string, opts DownloadOptions) error
Download fetches the named packages into destDir, each as the base name of its index Filename. A name may carry an architecture qualifier. The size and SHA-256 of the index are enforced while the file is written, and a file that fails the check is not left behind.
Every package is resolved and validated before any transfer starts, so an unknown package, a package without a repository URL, or a malformed index entry (missing or invalid SHA256, Size out of range, unsafe Filename) fails the call at once. Transfers then run to completion; the error of the first failing package, in argument order, is returned.
A plain-http transfer that fails with a transient error is retried once over https.
func (*Cache) DownloadClosure ¶
func (c *Cache) DownloadClosure( ctx context.Context, destDir string, seeds []string, opts DownloadOptions, ) (resolved []*PackageInfo, unresolved []string, err error)
DownloadClosure resolves the transitive closure of the seed names with ResolveDeps, downloads every resulting .deb into destDir, and returns the resolved packages in dependency order (dependencies first) and the names that could not be resolved.
Installed packages are skipped, though their dependencies are still walked, so that runtime dependencies reachable only through an installed library are pulled in. This is what a cross build needs to find the transitive libraries of a dependency its recipe names only directly.
func (*Cache) InstalledNames ¶
InstalledNames returns the names, without architecture qualifier, of the packages the dpkg status database reports as installed. A name counts when at least one architecture of it is installed.
Cross-build extractors use it to avoid overlaying a foreign-architecture payload on host binaries whose path is shared between architectures (/usr/bin/sudo is one file, and may be in use).
func (*Cache) Lookup ¶
func (c *Cache) Lookup(name string) (PackageInfo, bool)
Lookup returns the entry of the named package. The name may carry an architecture qualifier ("gcc-11:arm64"). Without one, or when the qualified entry is missing, it tries the bare name (architecture all), the host architecture, then any architecture.
func (*Cache) PackageCount ¶
PackageCount is the number of entries in the cache.
func (*Cache) ResolveDeps ¶
func (c *Cache) ResolveDeps(seeds []string) ([]*PackageInfo, []string, error)
ResolveDeps resolves the transitive dependencies of seeds. It returns the packages to download in dependency order (dependencies before dependents), and the names that are not in the index.
Installed packages are not listed, but their dependencies are still walked. Virtual packages resolve to their first provider, alternatives to their first option, and version constraints are ignored. A seed may carry an architecture qualifier ("libc6-dev:arm64"); it is inherited by every dependency, so that resolution is consistent when several architectures' indexes are loaded. A chain deeper than a few thousand packages fails with ErrDependencyDepth.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
c := apt.NewCache("amd64")
for _, p := range []*apt.PackageInfo{
{Name: "app", Architecture: "amd64", HasCandidate: true, Version: "1.0",
Filename: "pool/main/a/app/app_1.0_amd64.deb", Depends: []string{"libfoo", "mta"}},
{Name: "libfoo", Architecture: "amd64", HasCandidate: true, Version: "2.1",
Filename: "pool/main/libf/libfoo/libfoo_2.1_amd64.deb"},
{Name: "exim4", Architecture: "amd64", HasCandidate: true, Version: "4.96",
Filename: "pool/main/e/exim4/exim4_4.96_amd64.deb"},
} {
c.AddEntry(p)
}
order, unresolved, err := c.ResolveDeps([]string{"app"})
if err != nil {
fmt.Println(err)
return
}
for _, p := range order {
fmt.Println(p.Name, p.Version)
}
fmt.Println("unresolved:", unresolved)
}
Output: libfoo 2.1 app 1.0 unresolved: [mta]
func (*Cache) ResolveVirtual ¶
ResolveVirtual returns the first concrete provider of a virtual package, or name itself when it is a real package (it has a candidate) or unknown.
type DownloadOptions ¶
type DownloadOptions struct {
// Client performs the transfers. Nil builds one without an overall timeout,
// which would abort a large package on a slow link.
Client *httpclient.Client
// Concurrency caps the parallel transfers. Zero selects 6.
Concurrency int
// Progress, when set, is called after each chunk of a package with its
// file name, the bytes on disk and the expected size. It must be safe for
// concurrent use.
Progress func(name string, done, total int64)
}
DownloadOptions configures Download and DownloadClosure. The zero value is valid.
type LoadOptions ¶
type LoadOptions struct {
// ListsDir is the directory holding the downloaded Packages indexes, named
// the way apt names them ("<host>_<path>_dists_<suite>_<comp>_binary-<arch>_Packages[.ext]").
// Empty loads no index.
ListsDir string
// StatusFile is the dpkg status database to overlay, to set Installed. Empty
// skips it.
StatusFile string
// Sources resolve the BaseURL of every index: an index file named after a
// source's host and path takes that source's URL.
Sources []Source
// HostArch is the architecture unqualified names resolve to. Empty selects
// the one of the running program.
HostArch string
// Logger receives one debug record per file loaded. Nil is silent.
Logger *slog.Logger
}
LoadOptions says where a Cache is read from. Every field is optional.
type PackageInfo ¶
type PackageInfo struct {
// Name is the package name ("gcc", "libssl-dev").
Name string
// Architecture is the Architecture field ("amd64", "all", "arm64").
Architecture string
// Essential is true for "Essential: yes".
Essential bool
// MultiArch is the Multi-Arch field ("same", "foreign", "allowed" or "").
MultiArch string
// Installed is true when the dpkg status database reports the package as
// "install ok installed".
Installed bool
// HasCandidate is true when the package has a version in an apt index, that
// is, it is a real installable package and not a pure virtual one.
HasCandidate bool
// Filename is the path of the .deb relative to the repository base URL
// ("pool/main/g/gcc/gcc_12.2.0-14_amd64.deb").
Filename string
// SHA256 is the expected SHA-256 of the .deb, hex encoded.
SHA256 string
// Size is the expected size of the .deb in bytes.
Size int64
// BaseURL is the repository URL Filename is relative to, such as
// "https://ports.ubuntu.com/ubuntu-ports/". Empty for packages that only
// come from the dpkg status database, which cannot be downloaded.
BaseURL string
// Depends lists the package names of the Depends field: the first
// alternative of every entry, without version constraint.
Depends []string
// PreDepends is the same for Pre-Depends.
PreDepends []string
// Version is the Version field. When one name and architecture comes from
// several repositories, the highest version wins.
Version string
}
PackageInfo is the subset of a package's control fields that dependency resolution and downloading need.
func (PackageInfo) ArchitectureAll ¶
func (p PackageInfo) ArchitectureAll() bool
ArchitectureAll reports whether the package is architecture-independent.
func (PackageInfo) MultiArchForeign ¶
func (p PackageInfo) MultiArchForeign() bool
MultiArchForeign reports whether one copy of the package on the host satisfies dependencies from any architecture (Multi-Arch: foreign or allowed): tools and daemons that run on the build host, which must not be qualified with a target architecture during cross-compilation. Multi-Arch: same, the -dev libraries, is deliberately excluded.
func (PackageInfo) MultiArchSame ¶
func (p PackageInfo) MultiArchSame() bool
MultiArchSame reports whether the package must be installed once per architecture (Multi-Arch: same).
type Source ¶
type Source struct {
// URL is the repository base URL with a trailing slash
// ("https://archive.ubuntu.com/ubuntu/").
URL string
// Suite is the distribution ("jammy", "bookworm-updates").
Suite string
// Components lists the archive areas ("main", "universe").
Components []string
// Architectures restricts the source to these architectures. Empty means
// the default architecture.
Architectures []string
// SignedBy is the Signed-By option: a path to a keyring file or directory,
// or "".
SignedBy string
}
Source is one apt repository: a base URL, a suite and its components.
func LoadSources ¶
LoadSources reads the configured sources. listFile is a sources.list style file and listDir a directory of *.list (one-line) and *.sources (deb822) files, read in name order. Either may be empty, and either may be missing: apt tolerates that, and so does LoadSources. A file that exists but cannot be read, or is larger than MaxSourcesFileBytes, is skipped and reported in the returned error, next to the sources that did load.
func ParseSources822 ¶
ParseSources822 parses the deb822 format of *.sources files. A paragraph yields one Source per URI and suite. Paragraphs that do not declare the binary "deb" type, that are disabled (Enabled: no), or that lack URIs, Suites or Components are skipped, as are non-http(s) URIs.
func ParseSourcesList ¶
ParseSourcesList parses the one-line format of /etc/apt/sources.list and *.list files:
deb [arch=amd64 signed-by=/path] https://archive.ubuntu.com/ubuntu/ jammy main universe
Comments, deb-src lines, non-http(s) URLs, and lines without a suite and a component are skipped.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/deb/apt"
)
func main() {
sources := apt.ParseSourcesList(`
# main archive
deb [arch=amd64] https://deb.debian.org/debian bookworm main contrib
deb-src https://deb.debian.org/debian bookworm main
`)
for _, s := range sources {
fmt.Println(s.URL, s.Suite, s.Components, s.Architectures)
}
}
Output: https://deb.debian.org/debian/ bookworm [main contrib] [amd64]
type UpdateError ¶
type UpdateError struct {
Errors []error
}
UpdateError is the error Update returns when sources fail: one error for each (source, architecture) or component that did not update. The indexes that did update are in place regardless.
func (*UpdateError) Error ¶
func (e *UpdateError) Error() string
Error lists the failures, one per line.
func (*UpdateError) Unwrap ¶
func (e *UpdateError) Unwrap() []error
Unwrap exposes the failures to errors.Is and errors.As.
type UpdateOptions ¶
type UpdateOptions struct {
// ListsDir is the directory the Packages indexes are written to, under the
// names apt gives them. Update creates it. A Cache reads it back through
// LoadOptions.ListsDir.
ListsDir string
// DefaultArch is the architecture of sources that name none. Empty selects
// the one of the running program.
DefaultArch string
// DefaultKeyrings are the keyring files and directories that trust sources
// without a Signed-By option (/etc/apt/trusted.gpg.d, /usr/share/keyrings,
// /etc/apt/keyrings, /etc/apt/trusted.gpg on a Debian host). See LoadKeyring.
DefaultKeyrings []string
// AllowUnverified accepts a repository for which no trust anchor exists, a
// Release signed by an unknown key, or one without a signature. A signature
// that is present and does not verify is rejected regardless.
AllowUnverified bool
// Client performs the transfers. Nil builds one with the default policy.
Client *httpclient.Client
// Concurrency caps the (source, architecture) pairs updated at once. Zero
// selects min(2*GOMAXPROCS, 8).
Concurrency int
// Now is the clock the Valid-Until check of a Release uses. Nil is
// time.Now.
Now func() time.Time
// Logger receives progress and warnings. Nil is silent.
Logger *slog.Logger
}
UpdateOptions configures Update. Only ListsDir is required.