Documentation
¶
Overview ¶
Package apk builds, reads, verifies and signs Alpine Linux packages (.apk, the v2 format of apk-tools) and repository indexes, and fetches them from repositories. It is pure Go and needs neither abuild nor apk.
Packages ¶
An .apk file is two or three concatenated gzip members: an optional signature segment (a tar whose entry is named .SIGN.RSA.<key> or .SIGN.RSA256.<key>), the control segment (a tar that starts with .PKGINFO, followed by the install scripts) and the data segment (the files, each regular file with its SHA-1 in a PAX record). abuild leaves the end-of-archive blocks off the signature and control tars so a client reads the three segments as one tar stream.
WritePackage writes a package from a Spec of plain structs: the metadata (Info), the Scripts and the File entries; FilesFromDir lists a staged directory tree. A package may hold directories (parents are added automatically), files, symbolic links, hard links, FIFOs, device nodes, owners and extended attributes, and the metadata includes a license list, origin, commit, triggers, replaces_priority, provider_priority and install_if. ParsePackage reads one back under explicit limits, SignPackage adds a signature and VerifyPackage checks it.
APKv3 ¶
ParsePackage also reads the ADB packages of apk-tools 3 and sets Package.Format to FormatV3. The sub-package github.com/M0Rf30/pkgformat/apk/adb reads, verifies and extracts v3 packages and indexes, writes them the way "apk mkpkg" and "apk mkndx" do, and signs with RSA and ECDSA keys; it is tested against apk-tools 3.0.9.
Signatures ¶
Alpine signs with RSA and PKCS#1 v1.5, either over a SHA-1 digest (.SIGN.RSA.) or a SHA-256 digest (.SIGN.RSA256.). The type is always an explicit choice: a Signer is made for one SigAlgorithm, and VerifyOptions lists the types a verifier accepts, with the trusted keys in a Keyring (LoadKeyring reads an apk keys directory). Nothing defaults to SHA-1. A Signer wraps any crypto.Signer with an RSA key, so the key may live in an HSM or a KMS; the signature is checked against the advertised public key before it is used. ParsePrivateKeyPEM reads PKCS#1 and PKCS#8 keys and PublicKeyName gives a keys-directory file name.
The installed database ¶
OpenInstalled and NewInstalledDB read /lib/apk/db/installed, read-only: an InstalledPackage per record, with the index fields and the directories and files it owns, their checksums, owners and modes. A record that is not valid is skipped. InstalledDB.InstalledNames and InstalledDB.InstalledProvides list the installed names and capabilities.
Indexes ¶
BuildIndex and RenderIndex write an APKINDEX.tar.gz or its text, ParseIndex reads one and VerifyIndex checks its signature.
Repositories ¶
ParseRepositories reads a repositories file. A Client fetches the index of each repository, requires a valid signature by a trusted key (unless the caller opts out), and downloads packages, checking each against its index entry. The Index it returns resolves package names, provided capabilities, and Index.Solve chooses the packages for a world.
Reading packages ¶
OpenArchive reads a package for its contents: Archive.Files and Archive.Walk give every Entry (type, mode, owner, hard link and symbolic link targets, device numbers, the recorded SHA-1 and the extended attributes such as security.capability), and Archive.Extract unpacks the data segment into a directory with every path confined to it and every file checked against its checksum. Owners, device nodes and extended attributes are opt-in because they need privileges.
Versions and dependencies ¶
CompareVersions orders versions exactly as "apk version -t" does (it is tested against that tool on thousands of pairs); ParseDependency and Dependency.MatchVersion read and test "name>=1.2", "name~1.2", "!name", "name@tag" and "name><checksum". Alpine versions have no epoch: a version with a colon is refused.
Choosing packages ¶
Index.Solve follows apk's solver: constraints, conflicts, versioned and unversioned provides, provider_priority, install_if, @tag repositories, the preference for what is installed, and backtracking when a choice leads to a conflict. Its answers are tested against "apk add --simulate" on synthetic and real Alpine indexes. ParseWorld, WorldAdd, WorldDel and RenderWorld handle the world file, and ReplacesFile decides who owns a file that two packages ship, from replaces and replaces_priority.
Everything that reads untrusted bytes has explicit size and entry limits and returns typed errors; none of it panics on malformed input.
Example ¶
package main
import (
"bytes"
"fmt"
"io/fs"
"log"
"time"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
// Describe the package.
spec := &apk.Spec{
Info: apk.Info{
Name: "hello", Version: "1.0-r0", Arch: "x86_64",
Description: "Prints a greeting", License: "MIT",
BuildDate: time.Unix(1700000000, 0),
Depends: []string{"busybox"},
},
Scripts: apk.Scripts{PostInstall: "#!/bin/sh\necho installed\n"},
Files: []apk.File{
{Name: "usr", Mode: fs.ModeDir | 0o755, Uname: "root", Gname: "root"},
{Name: "usr/bin", Mode: fs.ModeDir | 0o755, Uname: "root", Gname: "root"},
apk.MemFile("usr/bin/hello", 0o755, []byte("#!/bin/sh\necho hello\n")),
},
}
// Sign it with a key of your own.
key, err := apk.GenerateKey(2048)
if err != nil {
log.Fatal(err)
}
signer, err := apk.NewSigner("me@example.org-5f0a1b2c.rsa.pub", key, apk.SigRSASHA256)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
pkg, err := apk.WritePackage(&out, spec, apk.WriteOptions{Signer: signer})
if err != nil {
log.Fatal(err)
}
// Verify it against the keys you trust.
keys := apk.NewKeyring()
if err := keys.Add(signer.KeyName(), signer.PublicKey()); err != nil {
log.Fatal(err)
}
verified, err := apk.VerifyPackage(bytes.NewReader(out.Bytes()), int64(out.Len()), apk.VerifyOptions{
Keys: keys, Algorithms: []apk.SigAlgorithm{apk.SigRSASHA256},
})
if err != nil {
log.Fatal(err)
}
// Put it in a signed repository index.
index, err := apk.BuildIndex([]apk.Package{*pkg}, "example repository", signer)
if err != nil {
log.Fatal(err)
}
entries, err := apk.VerifyIndex(index, apk.VerifyOptions{
Keys: keys, Algorithms: []apk.SigAlgorithm{apk.SigRSASHA256},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(verified.FileName(), verified.Signed, len(entries), entries[0].Checksum == pkg.Checksum)
}
Output: hello-1.0-r0.apk true 1 true
Index ¶
- Constants
- Variables
- func BuildIndex(pkgs []Package, description string, s *Signer) ([]byte, error)
- func CompareVersions(a, b string) int
- func DependencyName(spec string) string
- func FindInstalled(root string) (string, error)
- func GenerateKey(bits int) (*rsa.PrivateKey, error)
- func MarshalPrivateKeyPEM(k *rsa.PrivateKey) []byte
- func MarshalPrivateKeyPKCS1PEM(k *rsa.PrivateKey) []byte
- func MarshalPublicKeyPEM(pub *rsa.PublicKey) []byte
- func ParseFileName(s string) (string, string, bool)
- func ParsePrivateKeyPEM(data []byte) (*rsa.PrivateKey, error)
- func ParsePublicKeyPEM(data []byte) (*rsa.PublicKey, error)
- func ParseWorld(r io.Reader) ([]string, error)
- func PublicKeyName(owner string, pub *rsa.PublicKey) (string, error)
- func RenderIndex(pkgs []Package) []byte
- func RenderWorld(world []string) []byte
- func SignPackage(w io.Writer, ra io.ReaderAt, size int64, s *Signer) error
- func ValidSegment(s string) bool
- func ValidVersion(v string) bool
- func WorldAdd(world []string, add ...string) ([]string, error)
- func WorldDel(world []string, names ...string) []string
- type Archive
- type Change
- type ChangeKind
- type Client
- type ClientOptions
- type Dependency
- type Entry
- type EntryType
- type ExtractOptions
- type File
- type Format
- type Index
- func (idx *Index) Add(repo Repo, indexArch string, pkgs []Package)
- func (idx *Index) Find(name string) (*RepoPackage, bool)
- func (idx *Index) Lookup(name string) (*RepoPackage, bool)
- func (idx *Index) ResolveVirtual(name string) (*RepoPackage, bool)
- func (idx *Index) Solve(req SolveRequest) (*Solution, error)
- func (idx *Index) Stats() (packages, capabilities int)
- func (idx *Index) Versions(name string) []*RepoPackage
- type Info
- type InstalledDB
- func (db *InstalledDB) Close() error
- func (db *InstalledDB) InstalledNames(ctx context.Context) ([]string, error)
- func (db *InstalledDB) InstalledProvides(ctx context.Context) ([]string, error)
- func (db *InstalledDB) List(ctx context.Context) ([]*InstalledPackage, error)
- func (db *InstalledDB) Packages(ctx context.Context) iter.Seq2[*InstalledPackage, error]
- type InstalledFile
- type InstalledOptions
- type InstalledPackage
- type Keyring
- type Op
- type Package
- func ParseIndex(r io.Reader) ([]Package, error)
- func ParsePackage(r io.ReaderAt, size int64) (*Package, error)
- func VerifyIndex(data []byte, opts VerifyOptions) ([]Package, error)
- func VerifyPackage(ra io.ReaderAt, size int64, opts VerifyOptions) (*Package, error)
- func WritePackage(w io.Writer, spec *Spec, opts WriteOptions) (*Package, error)
- type Replacement
- type Repo
- type RepoError
- type RepoPackage
- type Scripts
- type SigAlgorithm
- type Signature
- type Signer
- type Solution
- type SolveError
- type SolveProblem
- type SolveRequest
- type Spec
- type UpdatedIndex
- type VerifyOptions
- type WriteOptions
Examples ¶
Constants ¶
const ( // OpAny matches every version. OpAny = apkver.Any // OpEqual accepts a version equal to the dependency's. OpEqual = apkver.Equal // OpLess accepts an older version. OpLess = apkver.Less // OpGreater accepts a newer version. OpGreater = apkver.Greater // OpFuzzy, always together with [OpEqual] ("~"), accepts a version that // starts with all the components of the dependency's: "foo~1.2" is met by // 1.2, 1.2.9 and 1.2.9-r3 but not by 1.3. OpFuzzy = apkver.Fuzzy // OpChecksum is "><": the version is not a version but the checksum of one // package, as "apk add foo><Q1..." pins it. OpChecksum = apkver.Checksum )
The comparison bits of an Op. The textual operators are what a depend, provides or world entry uses: "=" is OpEqual, "<" OpLess, "<=" the two together, ">" OpGreater, ">=", and "~" the fuzzy equality.
const ( DefaultMaxExtractBytes int64 = 16 << 30 DefaultMaxExtractEntries = 1 << 20 )
Defaults of the limits of ExtractOptions.
const ( // DefaultMaxInstalledPackages bounds the package records of a database. DefaultMaxInstalledPackages = 1 << 20 // DefaultMaxInstalledFiles bounds the file and directory records of one // package. DefaultMaxInstalledFiles = 1 << 21 // DefaultMaxInstalledBytes bounds the size of the database file. A system // with a thousand packages has a few megabytes. DefaultMaxInstalledBytes int64 = 1 << 30 )
Default limits of the installed-database reader, applied where an InstalledOptions field is zero.
Variables ¶
var ( // ErrInvalidOptions is wrapped by the errors of [NewClient] for options it // refuses. ErrInvalidOptions = errors.New("apk: invalid client options") // ErrNoIndex is returned by [Client.Update] when no repository index could // be loaded. It wraps the failure of each repository. ErrNoIndex = errors.New("apk: no repository index could be loaded") // ErrPackageMismatch means a downloaded package is not the one its index // entry describes: another size, checksum, name or version. ErrPackageMismatch = errors.New("apk: downloaded package does not match the index") )
var ( // ErrUnsafeEntry is returned for an entry whose path or link would leave // the destination directory. ErrUnsafeEntry = errors.New("apk: unsafe entry") // ErrExtractLimit is returned when the entries or bytes of a package // exceed the limits of [ExtractOptions]. ErrExtractLimit = errors.New("apk: extraction limit reached") // ErrUnsupported is returned when an option asks for something the // platform cannot do (device nodes, extended attributes or owners). ErrUnsupported = errors.New("apk: not supported on this platform") )
Errors of Archive.Extract.
var ( // ErrInstalledNotFound means [FindInstalled] met no installed database // under the root. ErrInstalledNotFound = errors.New("apk: no installed database found") // ErrInvalidInstalled means a file is not an installed database, or cannot // be read as one. ErrInvalidInstalled = errors.New("apk: invalid installed database") // ErrInstalledTooLarge means an installed database is over one of the // limits of [InstalledOptions]. ErrInstalledTooLarge = errors.New("apk: installed database exceeds a limit") )
Errors of the installed-database reader. Test with errors.Is.
var ( // ErrNoKeyring is returned when verifying without trusted keys. ErrNoKeyring = errors.New("apk: no trusted keys") // ErrUnsigned means the package or index carries no signature. ErrUnsigned = errors.New("apk: not signed") // ErrUntrusted means there are signatures, but none by a trusted key in an // accepted signature type. ErrUntrusted = errors.New("apk: no signature by a trusted key") // ErrBadSignature means a signature by a trusted key does not match. ErrBadSignature = errors.New("apk: signature does not verify") // ErrSign wraps the failure of a [Signer] to produce a signature: the // underlying [crypto.Signer] failed or returned something that is not a // valid PKCS#1 v1.5 signature by its own public key. ErrSign = errors.New("apk: signing failed") )
Errors of signature verification.
var ( // ErrUnsatisfiable is wrapped by the error of a request that no set of // packages meets; the error is a [*SolveError]. ErrUnsatisfiable = errors.New("apk: unable to select packages") // ErrSolveLimit is returned when the search for a solution exceeds its // step budget (a hostile index can make the search exponential). ErrSolveLimit = errors.New("apk: dependency search limit reached") )
Errors of Index.Solve.
var ErrAlreadySigned = errors.New("apk: package is already signed")
ErrAlreadySigned is returned by SignPackage for a package that already starts with a signature segment.
var ErrChecksum = errors.New("file checksum mismatch")
ErrChecksum is wrapped by the errors for a file whose content does not match the SHA-1 its package records for it. It is also an ErrInvalidPackage.
var ErrInvalidDependency = errors.New("apk: invalid dependency")
ErrInvalidDependency is wrapped by the errors of ParseDependency.
var ErrInvalidIndex = errors.New("invalid apk index")
ErrInvalidIndex is wrapped by every error ParseIndex and BuildIndex return for malformed or over-limit input.
var ErrInvalidPackage = errors.New("invalid apk package")
ErrInvalidPackage is wrapped by every error ParsePackage returns.
var ErrInvalidRepositories = errors.New("apk: invalid repositories file")
ErrInvalidRepositories is wrapped by every error ParseRepositories returns.
var ErrInvalidSpec = errors.New("apk: invalid package spec")
ErrInvalidSpec is wrapped by every error WritePackage returns for a Spec it refuses.
var ErrInvalidWorld = errors.New("apk: invalid world")
ErrInvalidWorld is wrapped by the errors of ParseWorld and WorldAdd.
var ErrNoAlgorithm = errors.New("apk: no signature algorithm chosen")
ErrNoAlgorithm is returned when a signer, a verifier or a client is used without choosing a SigAlgorithm.
var ErrPackageNotFound = errors.New("apk: package not found")
ErrPackageNotFound is wrapped by the errors of a lookup that finds neither a package nor a provider of the name.
Functions ¶
func BuildIndex ¶
BuildIndex builds a deterministic APKINDEX.tar.gz for pkgs: a gzip member with the tar entries DESCRIPTION and APKINDEX, ended like apk's own index tars. With a signer it is preceded by the signature member, a gzip member whose tar (no end-of-archive blocks, so that apk reads on into the next member) holds the entry .SIGN.RSA.<key name> or .SIGN.RSA256.<key name>, as the signer's SigAlgorithm says: the RSA PKCS#1 v1.5 signature of the complete bytes of the index member. Every package must be valid (see Package), carrying at least the Checksum; errors wrap ErrInvalidIndex.
func CompareVersions ¶ added in v0.4.0
CompareVersions compares two versions as apk does and returns -1, 0 or +1. Both versions are expected to be valid; for a string that is not (see ValidVersion) the result is defined but not meaningful.
The release ("-r1") counts: "1.0-r1" is older than "1.0-r2", and "1.0" is older than "1.0-r1". Pre-release suffixes (_alpha, _beta, _pre, _rc) are older than the version without them and post-release ones (_cvs, _svn, _git, _hg, _p) are newer. "1.0" is older than "1.0.1" and than "1.0a" but newer than "1.0_rc1".
Example ¶
Compare versions the way "apk version -t" does.
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
fmt.Println(apk.CompareVersions("1.2.3-r1", "1.2.3-r2"))
fmt.Println(apk.CompareVersions("1.0_rc1", "1.0"))
fmt.Println(apk.CompareVersions("1.0_p1", "1.0"))
fmt.Println(apk.CompareVersions("2.0", "10.0"))
}
Output: -1 -1 1 -1
func DependencyName ¶
DependencyName returns the package or capability name of a dependency entry, without its version constraint: "musl-dev>=1.2" gives "musl-dev".
func FindInstalled ¶ added in v0.3.1
FindInstalled looks for the installed database under root, the directory that holds the system's /lib: "/" for the running host, or the root of an image or an install directory. Symbolic links are followed only inside root. It returns ErrInstalledNotFound when there is no regular file.
func GenerateKey ¶
func GenerateKey(bits int) (*rsa.PrivateKey, error)
GenerateKey generates an RSA key of bits bits, which must be between 2048 and 16384.
func MarshalPrivateKeyPEM ¶
func MarshalPrivateKeyPEM(k *rsa.PrivateKey) []byte
MarshalPrivateKeyPEM encodes k as a PKCS#8 "PRIVATE KEY" PEM block. It returns nil for a key that cannot be encoded.
func MarshalPrivateKeyPKCS1PEM ¶ added in v0.4.0
func MarshalPrivateKeyPKCS1PEM(k *rsa.PrivateKey) []byte
MarshalPrivateKeyPKCS1PEM encodes k as a PKCS#1 "RSA PRIVATE KEY" PEM block, the format abuild-keygen writes. It returns nil for a nil key.
func MarshalPublicKeyPEM ¶ added in v0.4.0
MarshalPublicKeyPEM encodes pub as a "PUBLIC KEY" (SubjectPublicKeyInfo) PEM block, what apk keeps in its keys directory. It returns nil for a key that cannot be encoded.
func ParseFileName ¶
ParseFileName is the inverse of Package.FileName. The version starts at the last '-' that is followed by a digit and whose prefix is a valid package name; both halves must be valid. It returns the name, the version and whether s is a valid package file name. For every valid name and version, ParseFileName(name + "-" + version + ".apk") returns them again.
func ParsePrivateKeyPEM ¶
func ParsePrivateKeyPEM(data []byte) (*rsa.PrivateKey, error)
ParsePrivateKeyPEM decodes the first PEM block of data as an unencrypted RSA private key of 2048 to 16384 bits: PKCS#8 ("PRIVATE KEY") or PKCS#1 ("RSA PRIVATE KEY", what abuild-keygen writes).
func ParsePublicKeyPEM ¶
ParsePublicKeyPEM decodes the first PEM block of data as an RSA public key of 2048 to 16384 bits: "PUBLIC KEY" (SubjectPublicKeyInfo, what apk keeps in its keys directory) or "RSA PUBLIC KEY" (PKCS#1).
func ParseWorld ¶ added in v0.4.0
ParseWorld reads the world file of an apk system (/etc/apk/world): the dependencies the user asked for, separated by white space or newlines, each "name", "name@tag", "name>=1.2", "!name" and so on. Every entry is checked with ParseDependency. It reads at most 1 MiB and 100 000 entries.
func PublicKeyName ¶ added in v0.4.0
PublicKeyName returns the file name for pub in a keys directory, in the form abuild-keygen gives them: "<owner>-<8 hex digits>.rsa.pub". The digits are the first four bytes of the SHA-256 of the DER public key, so the same key always gets the same name. owner is typically an e-mail address. The result is only returned when it is a valid key name that fits an entry name of either signature type.
func RenderIndex ¶
RenderIndex renders packages as APKINDEX text: one stanza per package, in the order given, each ending with a blank line. Fields that are empty or zero are left out, except the mandatory C, P, V and A. Control characters in a value are replaced by a space so that a value can never start a new line or field; BuildIndex refuses such packages outright instead.
func RenderWorld ¶ added in v0.4.0
RenderWorld renders the world file: one entry per line, sorted by name, as apk writes it.
func SignPackage ¶
SignPackage writes the unsigned .apk of size bytes to w with a signature segment of s in front of it: the signature covers the control segment, as abuild-sign does. A package that is already signed is ErrAlreadySigned. The package is parsed first and must be valid.
func ValidSegment ¶
ValidSegment reports whether s may be used as a branch, repository or architecture path segment: ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$. Because the first byte must be alphanumeric, "." and ".." never pass.
func ValidVersion ¶ added in v0.4.0
ValidVersion reports whether v is a version in the syntax apk accepts: digits, ".digits", a letter, "_suffix[digits]" groups, "~hash" and "-rN", in that order. "1.2.3-r0", "2.0_rc1" and "20240101_git~1a2b3c-r2" are valid; "", "1.", "1.0-1" and "1.0_foo" are not.
func WorldAdd ¶ added in v0.4.0
WorldAdd returns world with the entries added the way "apk add" does: an entry replaces the one of the same package name, a conflict ("!name") included, and is added when there is none. The result is in the order of world, new entries last.
Example ¶
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
world, _ := apk.WorldAdd([]string{"busybox", "libfoo"}, "libfoo>=1.2", "curl")
fmt.Print(string(apk.RenderWorld(world)))
}
Output: busybox curl libfoo>=1.2
Types ¶
type Archive ¶ added in v0.4.0
type Archive struct {
// contains filtered or unexported fields
}
Archive is a package opened for reading: its verified metadata, install scripts and data segment. It holds no file descriptor of its own; the ReaderAt must stay valid while it is used. An Archive is safe for concurrent use when its ReaderAt is.
Example ¶
Read the files of a package without unpacking it, then unpack it into a directory. Every name is confined to the directory and every file is checked against the checksum the package records.
package main
import (
"bytes"
"fmt"
"io"
"io/fs"
"log"
"os"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
spec := &apk.Spec{
Info: apk.Info{Name: "tool", Version: "1-r0", Arch: "noarch"},
Files: []apk.File{
apk.MemFile("usr/bin/tool", fs.ModeSetuid|0o755, []byte("#!/bin/sh\n")),
{Name: "usr/bin/t", Mode: fs.ModeSymlink | 0o777, LinkTarget: "tool"},
{
Name: "usr/bin/cap", Mode: 0o755, Size: 1,
Xattrs: map[string][]byte{"security.capability": make([]byte, 20)},
},
},
}
spec.Files[2].Open = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader([]byte("c"))), nil }
var pkg bytes.Buffer
if _, err := apk.WritePackage(&pkg, spec, apk.WriteOptions{}); err != nil {
log.Fatal(err)
}
a, err := apk.OpenArchive(bytes.NewReader(pkg.Bytes()), int64(pkg.Len()))
if err != nil {
log.Fatal(err)
}
files, err := a.Files()
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Println(f.Type, f.Name, f.Mode)
}
dir, err := os.MkdirTemp("", "extract")
if err != nil {
log.Fatal(err)
}
defer func() { _ = os.RemoveAll(dir) }()
if err := a.Extract(dir, apk.ExtractOptions{}); err != nil {
log.Fatal(err)
}
}
Output: dir usr -rwxr-xr-x dir usr/bin -rwxr-xr-x file usr/bin/tool urwxr-xr-x symlink usr/bin/t -rwxrwxrwx file usr/bin/cap -rwxr-xr-x
func OpenArchive ¶ added in v0.4.0
OpenArchive opens an .apk of size bytes. It does everything ParsePackage does (so the datahash, the gzip framing and the entry names are verified before it returns) and also reads the install scripts of the control segment. Every error wraps ErrInvalidPackage.
func (*Archive) Extract ¶ added in v0.4.0
func (a *Archive) Extract(dir string, opts ExtractOptions) error
Extract unpacks the data segment into dir, which must exist. Every path is confined to dir: a name or a symbolic link that would leave it fails with ErrUnsafeEntry, and an existing symbolic link in the way is never followed out of dir. The checksum of every regular file is verified as it is written (ErrChecksum); a file that fails is removed. Directory modes and times are applied after their content, so a read-only directory can be filled.
func (*Archive) Files ¶ added in v0.4.0
Files lists the entries of the data segment, with their modes, owners and checksums. The content of every file is verified against its checksum on the way, as in Archive.Walk.
func (*Archive) Package ¶ added in v0.4.0
Package returns the package metadata, as ParsePackage reports it.
func (*Archive) Scripts ¶ added in v0.4.0
Scripts returns the install scripts of the package: the control segment entries .pre-install, .post-install, .pre-upgrade, .post-upgrade, .pre-deinstall, .post-deinstall and .trigger, each as its complete text. The directories the .trigger script watches are in Package.Triggers.
func (*Archive) Signatures ¶ added in v0.4.0
Signatures returns the signature entries of the package, in file order. They are not verified here; see VerifyPackage.
func (*Archive) Walk ¶ added in v0.4.0
Walk calls fn for each entry of the data segment, in archive order, with a reader of the entry's content (empty for anything but a regular file). The reader is only valid during the call. When fn returns, the rest of the content is read and the file is checked against the checksum the package records for it: a mismatch fails Walk with an error wrapping ErrChecksum. An error of fn stops the walk and is returned as is.
type Change ¶ added in v0.4.0
type Change struct {
// Old is the installed package that is removed or replaced; nil for an
// install.
Old *Package
// New is the package to install; nil for a removal.
New *RepoPackage
}
Change is one step to get from the installed packages to the solution.
func (Change) Kind ¶ added in v0.4.0
func (c Change) Kind() ChangeKind
Kind returns what the change does.
type ChangeKind ¶ added in v0.4.0
type ChangeKind uint8
ChangeKind is what a Change does to a package.
const ( // ChangeInstall installs a package that is not installed. ChangeInstall ChangeKind = iota + 1 // ChangeRemove removes an installed package (apk's "Purging"). ChangeRemove // ChangeUpgrade replaces an installed package by a higher version. ChangeUpgrade // ChangeDowngrade replaces an installed package by a lower version. ChangeDowngrade // ChangeReinstall replaces an installed package by the same version (a // different build of it). ChangeReinstall )
The kinds of change.
func (ChangeKind) String ¶ added in v0.4.0
func (k ChangeKind) String() string
String returns "install", "remove", "upgrade", "downgrade" or "reinstall".
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client fetches and verifies repository indexes and downloads packages. It is safe for concurrent use.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
client, err := apk.NewClient(apk.ClientOptions{
Repos: []apk.Repo{{URL: "https://dl-cdn.alpinelinux.org/alpine/v3.21/main"}},
Arch: "x86_64",
KeysDir: "/etc/apk/keys",
Algorithms: []apk.SigAlgorithm{apk.SigRSASHA1}, // what Alpine's own repositories use
})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
index, err := client.Update(ctx)
if err != nil {
log.Fatal(err)
}
res, err := index.Solve(apk.SolveRequest{World: []string{"curl"}})
if err != nil {
log.Fatal(err)
}
paths, err := client.Download(ctx, "/var/cache/apk", res.Packages...)
if err != nil {
log.Fatal(err)
}
fmt.Println(paths)
}
Output:
func NewClient ¶
func NewClient(opts ClientOptions) (*Client, error)
NewClient validates opts and loads the trusted keys.
func (*Client) Download ¶
func (c *Client) Download(ctx context.Context, destDir string, pkgs ...*RepoPackage) ([]string, error)
Download fetches the package files of pkgs into destDir, which must exist, and returns their paths in the order given. Transfers resume after a partial download and are retried by the client's policy. Each file is checked against its index entry before it is kept: it must be a valid package of the size, checksum, name and version the index lists, otherwise it is deleted and the error wraps ErrPackageMismatch or ErrInvalidPackage. The index checksum is the trust anchor, as in apk itself: when the index was verified, so is every package it lists.
func (*Client) FetchIndex ¶
FetchIndex downloads, verifies (when the client has keys) and parses the index of one repository.
func (*Client) Update ¶
func (c *Client) Update(ctx context.Context) (*UpdatedIndex, error)
Update fetches the index of every repository (a few in parallel) and returns them as one Index in the order of the repositories. A repository that cannot be fetched, verified or parsed is left out and reported by [Client.Failures] of the result; Update fails with ErrNoIndex only when no repository loads.
type ClientOptions ¶
type ClientOptions struct {
// Repos are the repositories, in order of preference.
Repos []Repo
// Arch is the architecture directory of every repository, for example
// x86_64.
Arch string
// KeysDir is the directory of trusted public keys (the keys directory of
// /etc/apk) the index signatures are checked against. An index without a
// valid signature by one of them is refused.
KeysDir string
// Algorithms are the signature types accepted when KeysDir is set. There
// is no default: a caller that accepts SHA-1 signatures says so.
Algorithms []SigAlgorithm
// InsecureSkipVerify accepts indexes without checking their signature. It
// excludes KeysDir. The downloaded packages are still checked against the
// index entries.
InsecureSkipVerify bool
// HTTP fetches the indexes and the packages. Nil builds a client with the
// default retry policy.
HTTP *httpclient.Client
// CacheDir, when set, receives a copy of each verified index tarball, named
// APKINDEX.<sha1 of the URL>.tar.gz. The directory is created.
CacheDir string
// Concurrency bounds the parallel package downloads; zero selects the
// download package's default.
Concurrency int
// Logger receives one line per repository and package. Nil is silent.
Logger *slog.Logger
}
ClientOptions configures a Client. Repos, Arch, and a trust decision (KeysDir with Algorithms, or InsecureSkipVerify) are required; nothing is read from a host path unless the caller names it.
type Dependency ¶ added in v0.4.0
type Dependency struct {
// Name is a package name or a capability such as "so:libc.musl-x86_64.so.1"
// or "cmd:sh".
Name string
// Conflict is the "!" prefix: no package providing Name (at a version
// matching Op and Version) may be installed.
Conflict bool
// Tag is the repository tag of "name@tag": the dependency may be met from
// the repositories of that tag. Empty means untagged repositories only.
Tag string
// Op and Version are the version constraint. Version is empty for
// [OpAny]; for [OpChecksum] it is the Q1 checksum of the package.
Op Op
Version string
}
Dependency is one entry of a depend, provides, replaces, install_if or world list: [!]name[@tag][op version].
func ParseDependency ¶ added in v0.4.0
func ParseDependency(spec string) (Dependency, error)
ParseDependency parses one dependency of the forms apk accepts:
name !name name@tag name=1.2 name>=1.2-r1 name<2 name~1.2 name><Q1...
The name runs up to the first of '<', '>', '=' and '~'. A version must be valid (see ValidVersion), except for a checksum. The text must be a single entry, without white space.
Example ¶
package main
import (
"fmt"
"log"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
d, err := apk.ParseDependency("libfoo@edge>=1.2")
if err != nil {
log.Fatal(err)
}
fmt.Println(d.Name, d.Tag, d.Op, d.MatchVersion("1.5-r0"), d.MatchVersion("1.1"))
}
Output: libfoo edge >= true false
func (Dependency) MatchVersion ¶ added in v0.4.0
func (d Dependency) MatchVersion(have string) bool
MatchVersion reports whether a provider of the version have meets the version constraint of d. The Conflict flag is not applied: "!foo<2" and "foo<2" give the same answer here. An empty have stands for a provider that declares no version ("provides: foo"), which meets any constraint, as it does in apk.
func (Dependency) MatchesPackage ¶ added in v0.4.0
func (d Dependency) MatchesPackage(p *Package) bool
MatchesPackage reports whether p, a package of an index or the installed database, meets d the way apk says a dependency on its own name does: its name is d.Name and its version meets the constraint, or one of its provides entries names d.Name with a matching version. A conflict is met by the packages that do not match.
func (Dependency) String ¶ added in v0.4.0
func (d Dependency) String() string
String returns the dependency as it is written: "!name@tag>=1.2".
type Entry ¶ added in v0.4.0
type Entry struct {
// Name is the install path: relative, slash separated, without a trailing
// slash, free of ".." elements.
Name string
Type EntryType
// Mode holds the permission bits and fs.ModeSetuid, fs.ModeSetgid and
// fs.ModeSticky; the kind is in Type.
Mode fs.FileMode
// Size is the content length of a regular file.
Size int64
ModTime time.Time
// UID, GID, Uname and Gname are the owner the package records.
UID, GID int
Uname, Gname string
// LinkTarget is the target of a symbolic link, or the earlier entry a
// hard link is another name of.
LinkTarget string
// DevMajor and DevMinor are the numbers of a device node.
DevMajor, DevMinor int64
// Checksum is the lowercase hex SHA-1 the package records for a regular
// file's content or a symbolic link's target (the PAX record
// APK-TOOLS.checksum.SHA1); empty when the package records none.
Checksum string
// Xattrs are the extended attributes (SCHILY.xattr PAX records), such as
// "security.capability".
Xattrs map[string][]byte
}
Entry is one entry of the data segment of a package.
type EntryType ¶ added in v0.4.0
type EntryType uint8
EntryType is the kind of a data segment entry.
type ExtractOptions ¶ added in v0.4.0
type ExtractOptions struct {
// MaxBytes bounds the content bytes written. Zero is
// [DefaultMaxExtractBytes].
MaxBytes int64
// MaxEntries bounds the entries processed. Zero is
// [DefaultMaxExtractEntries].
MaxEntries int
// Owners applies the numeric owner of each entry (it needs the
// privilege to chown) and keeps the setuid, setgid and sticky bits.
Owners bool
// Devices creates character and block device nodes (it needs the
// privilege to mknod). Without it a device entry is skipped.
Devices bool
// Xattrs sets the extended attributes of each entry, such as the file
// capabilities in security.capability. Setting that attribute needs
// CAP_SETFCAP.
Xattrs bool
}
ExtractOptions tunes Archive.Extract. The zero value extracts regular files, directories, symbolic links, hard links and FIFOs as the current user, with the permission bits and modification times of the package, and without the setuid, setgid and sticky bits, owners, device nodes and extended attributes.
type File ¶
type File struct {
// Name is the install path: slash separated, relative, without "." or
// ".." elements. A directory's trailing slash is added when missing.
Name string
// Mode holds the type and the permission bits, setuid, setgid and sticky
// included.
Mode fs.FileMode
// Size is the length of a regular file's content.
Size int64
// ModTime is the modification time, truncated to the second; the zero time
// is the epoch.
ModTime time.Time
// UID, GID, Uname and Gname are the owner.
UID, GID int
Uname, Gname string
// LinkTarget is the target of a symbolic link, or, with Hardlink, the
// name of the file this entry is another name of.
LinkTarget string
// Hardlink makes a regular-file entry a hard link to the earlier entry
// named LinkTarget. The target must be a regular file of the package; a
// hard link has no content of its own.
Hardlink bool
// DevMajor and DevMinor are the device numbers of a character or block
// device (Mode has fs.ModeDevice, plus fs.ModeCharDevice for a character
// device).
DevMajor, DevMinor int64
// Xattrs are the extended attributes, by name, stored as SCHILY.xattr
// PAX records: "security.capability" holds the file capabilities of a
// binary, in the binary form the kernel keeps them.
Xattrs map[string][]byte
// Open returns the content of a regular file. It is called twice (one pass
// to record the checksum, one to write) and must return Size bytes both
// times. Nil is an empty file.
Open func() (io.ReadCloser, error)
}
File is one entry of the data segment. The kind comes from Mode: a directory, a symbolic link, a named pipe, a character or block device, or a regular file, which is a hard link when Hardlink is set; sockets are refused.
func FilesFromDir ¶
FilesFromDir lists the tree under dir for Spec.Files: every entry below dir in lexical order, with names relative to dir, links not followed, the owner root:root and the modification time the epoch, so the package does not depend on who built it or when. The permission bits are kept.
type Index ¶
type Index struct {
// contains filtered or unexported fields
}
Index is the set of packages of one or more repositories, for lookups and dependency resolution. It is filled with Index.Add and then only read; it is not safe for concurrent Add.
func (*Index) Add ¶
Add lists the packages of repo's index for indexArch. Every version of a package is kept; one that an earlier repository lists with the same name, version and checksum is ignored, so the repository added first wins like the order of a repositories file. A package registers the capabilities of its Provides with their versions. A repository with a Tag is only used by a request that names the tag ("pkg@tag").
func (*Index) Find ¶
func (idx *Index) Find(name string) (*RepoPackage, bool)
Find returns the package called name or, failing that, the provider of the capability name.
func (*Index) Lookup ¶
func (idx *Index) Lookup(name string) (*RepoPackage, bool)
Lookup returns the package of that name: the highest version of an untagged repository, the earlier repository among equals; a package that only a tagged repository lists is returned when no untagged one has the name. The name has no version constraint.
func (*Index) ResolveVirtual ¶
func (idx *Index) ResolveVirtual(name string) (*RepoPackage, bool)
ResolveVirtual returns the package that provides the capability name: the one with the highest provider priority, the first added among equals.
func (*Index) Solve ¶ added in v0.4.0
func (idx *Index) Solve(req SolveRequest) (*Solution, error)
Solve finds the set of packages that meets the request and returns the changes that lead to it from the installed packages. It follows the semantics of apk's solver: versioned constraints with every operator, conflicts ("!name"), versioned and unversioned provides, provider_priority to choose among providers (an unversioned virtual without priority is not chosen on its own), install_if triggers, repository tags ("name@tag") and the preference for the installed version, the highest version and the earlier repository. Unlike a greedy walk it backtracks when a choice leads to a conflict, within a step budget (ErrSolveLimit).
The error of a request that cannot be met is a *SolveError.
Example ¶
Choose the packages for a world with apk's rules and see what changes.
package main
import (
"fmt"
"log"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
idx := apk.NewIndex()
idx.Add(apk.Repo{URL: "https://example.org/main"}, "x86_64", []apk.Package{
{Name: "app", Version: "2-r0", Depends: []string{"libfoo>=1.2"}},
{Name: "libfoo", Version: "1.1-r0"},
{Name: "libfoo", Version: "1.5-r0"},
{Name: "docs", Version: "1-r0", InstallIf: []string{"app"}},
})
sol, err := idx.Solve(apk.SolveRequest{
World: []string{"app"},
Installed: []apk.Package{{Name: "libfoo", Version: "1.1-r0"}},
})
if err != nil {
log.Fatal(err)
}
for _, c := range sol.Changes {
fmt.Println(c.Kind(), c.New.Name, c.New.Version)
}
}
Output: upgrade libfoo 1.5-r0 install app 2-r0 install docs 1-r0
func (*Index) Versions ¶ added in v0.4.0
func (idx *Index) Versions(name string) []*RepoPackage
Versions returns every package called name, in the order they were added.
type Info ¶
type Info struct {
// Name is the package name (pkgname), Version the complete version
// including the release (pkgver), for example "1.2.3-r0". apk has no
// epoch: the ordering of versions is the one of [CompareVersions], so a
// version that must outrank an older scheme is made greater by its own
// digits, and a "1:2.0" style epoch is refused as an invalid version.
// Arch is the apk architecture such as x86_64 or noarch.
Name, Version, Arch string
// Description (pkgdesc), URL, License (one SPDX expression such as
// "MPL-2.0 AND MIT"), Origin (the package the build produced it from; the
// Name when empty), Maintainer, Packager and Commit are the free text
// lines.
Description, URL, License, Origin, Maintainer, Packager, Commit string
// Licenses is the license as a list: its entries are joined by single
// spaces into the license line, the way abuild writes a license
// variable that holds several identifiers. Set it or License, not both.
Licenses []string
// BuildDate is the builddate; the line is left out when it is zero.
BuildDate time.Time
// InstalledSize is the size line, the bytes the package takes installed.
// Zero selects the sum of the sizes of the regular files.
InstalledSize int64
// Depends, Provides and Replaces get one depend, provides or replaces
// line per entry. InstallIf is one install_if line. Triggers is one
// triggers line, the directory globs that run the .trigger script.
Depends, Provides, Replaces, InstallIf, Triggers []string
// ProviderPriority is the provider_priority line; zero leaves it out.
ProviderPriority int
// ReplacesPriority is the replaces_priority line: when two packages
// own a file and both replace the other, the higher priority wins. Zero
// leaves it out.
ReplacesPriority int
// Generator, when set, is written as the first line, a comment:
// "# Generated by <Generator>".
Generator string
}
Info is the metadata of a package: what goes into its .PKGINFO. Name, Version and Arch are required; the zero value of every other field leaves the line out.
type InstalledDB ¶ added in v0.3.1
type InstalledDB struct {
// contains filtered or unexported fields
}
InstalledDB is an apk installed database: the file /lib/apk/db/installed. It is read-only and safe for concurrent use: every call reads the file again.
Example ¶
Read the packages an apk system has installed, with the files they own. On a host, FindInstalled("/") and OpenInstalled give the real database.
package main
import (
"context"
"fmt"
"log"
"strings"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
const text = `C:Q1qvTGHdzF6KLavt4PO0gs2a6pQ00=
P:busybox
V:1.37.0-r31
A:x86_64
p:cmd:busybox=1.37.0-r31 /bin/sh
F:bin
R:busybox
a:0:0:755
Z:Q1y5VcgN7Y1x2d9E1Gp7BkG5mZYGM=
`
db := apk.NewInstalledDB(strings.NewReader(text), int64(len(text)), apk.InstalledOptions{})
for pkg, err := range db.Packages(context.Background()) {
if err != nil {
log.Fatal(err)
}
fmt.Println(pkg.Name, pkg.Version, pkg.FilePaths())
}
provides, _ := db.InstalledProvides(context.Background())
fmt.Println(provides)
}
Output: busybox 1.37.0-r31 [bin/busybox] [/bin/sh busybox cmd:busybox]
func NewInstalledDB ¶ added in v0.3.1
func NewInstalledDB(r io.ReaderAt, size int64, opts InstalledOptions) *InstalledDB
NewInstalledDB reads the database text that r holds, size bytes. Close does not close r. A size over InstalledOptions.MaxBytes makes every read fail with ErrInstalledTooLarge.
func OpenInstalled ¶ added in v0.3.1
func OpenInstalled(path string, opts InstalledOptions) (*InstalledDB, error)
OpenInstalled opens the installed database at path. The file is only read and not locked, so apk can run at the same time; each call reads it as of that moment.
func (*InstalledDB) Close ¶ added in v0.3.1
func (db *InstalledDB) Close() error
Close releases the file of a database opened with OpenInstalled.
func (*InstalledDB) InstalledNames ¶ added in v0.3.1
func (db *InstalledDB) InstalledNames(ctx context.Context) ([]string, error)
InstalledNames returns the names of the installed packages, sorted and without duplicates. It does not keep the file lists.
func (*InstalledDB) InstalledProvides ¶ added in v0.3.1
func (db *InstalledDB) InstalledProvides(ctx context.Context) ([]string, error)
InstalledProvides returns the capabilities the installed packages provide ("so:libc.musl-x86_64.so.1", "cmd:sh", "/bin/sh"), as names without version constraints, sorted and without duplicates. The name of each package is included, as it provides itself. It does not keep the file lists.
func (*InstalledDB) List ¶ added in v0.3.1
func (db *InstalledDB) List(ctx context.Context) ([]*InstalledPackage, error)
List returns every installed package: InstalledDB.Packages collected into a slice.
func (*InstalledDB) Packages ¶ added in v0.3.1
func (db *InstalledDB) Packages(ctx context.Context) iter.Seq2[*InstalledPackage, error]
Packages iterates over the installed packages in the order of the database. A record that is not valid is skipped and reported at debug level to InstalledOptions.Logger: a missing P, V or A line, a repeated field, a value that is not valid, a path that climbs out of the root, a package with more than InstalledOptions.MaxFiles file records. 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.
type InstalledFile ¶ added in v0.3.1
type InstalledFile struct {
// Path is relative to the root of the system, without a leading slash:
// "usr/lib/libz.so.1".
Path string
// Dir is true for a directory the package owns, and false for a file.
Dir bool
// Checksum is the "Z:" value of a file, "Q1" and the base64 of its SHA-1
// (or, for an install made by a newer apk, the algorithm's own prefix).
// It is empty for a directory.
Checksum string
// HasACL reports that the record carries an "a:" (file) or "M:"
// (directory) line, which gives the owner and the mode.
HasACL bool
// UID and GID are the owner and group of the file, and Mode its
// permission bits, from the ACL line. They are zero without one.
UID, GID uint32
Mode uint32
}
InstalledFile is a file or directory record of an installed package.
type InstalledOptions ¶ added in v0.3.1
type InstalledOptions struct {
// Logger receives debug messages about skipped records. Optional: nil
// discards them.
Logger *slog.Logger
// MaxPackages bounds the package records read; reading more fails with
// [ErrInstalledTooLarge]. Zero selects [DefaultMaxInstalledPackages].
MaxPackages int
// MaxFiles bounds the file and directory records of one package; a
// package with more is skipped. Zero selects [DefaultMaxInstalledFiles].
MaxFiles int
// MaxBytes bounds the size of the database; a larger one fails with
// [ErrInstalledTooLarge]. Zero selects [DefaultMaxInstalledBytes].
MaxBytes int64
// SkipFiles leaves the file records out of the packages. The names and
// the metadata of a large database are then read without keeping the
// lists.
SkipFiles bool
}
InstalledOptions configures OpenInstalled, NewInstalledDB. The zero value is usable.
type InstalledPackage ¶ added in v0.3.1
type InstalledPackage struct {
// Package holds the index fields, P, V, A, S, I, T, U, L, o, m, t, c, D,
// p, i and k, "r" (Replaces) and "q" (ReplacesPriority). Checksum is the "C:" value; it is empty
// for a package without one.
Package
// Files are the directories and files of the package, in the order of the
// database: a directory, then the files in it.
Files []InstalledFile
}
InstalledPackage is a package record of the installed database: the fields of an index entry, the files the package owns and what apk adds for an installed package.
func (*InstalledPackage) FilePaths ¶ added in v0.3.1
func (p *InstalledPackage) FilePaths() []string
FilePaths returns the paths of the regular files of the package, as "apk info -L" lists them.
type Keyring ¶
type Keyring struct {
// contains filtered or unexported fields
}
Keyring is the set of public keys a signature is checked against, by key name: the file names of apk's keys directory.
func LoadKeyring ¶
LoadKeyring reads the public keys of dir: every regular file whose name ends in .rsa.pub, as PEM. Other files and subdirectories are ignored; a .rsa.pub file that is not a valid key fails the load, so a damaged key is never silently dropped from the trust set. At most 1000 files of 64 KiB.
type Op ¶ added in v0.4.0
Op is the comparison of a versioned dependency, a set of the results a version comparison may have. The zero value, OpAny, is a dependency without a version.
type Package ¶
type Package struct {
Name, Version, Arch string
Description, URL, License, Origin, Maintainer, Commit string
// Packager is the PKGINFO packager. It is not an index field.
Packager string
// BuildTime is the PKGINFO builddate (index field t), InstalledSize the
// PKGINFO size (index field I).
BuildTime, InstalledSize int64
Depends, Provides []string
// Replaces is the PKGINFO replaces list. It is not an index field.
Replaces []string
// Triggers is the PKGINFO triggers list: the directory globs whose
// changes run the package's .trigger script. It is not an index field.
Triggers []string
InstallIf []string
// ProviderPriority is the provider_priority index field (p), the
// preference among the providers of a virtual name. ReplacesPriority is
// the PKGINFO replaces_priority, which picks the owner of a file two
// packages both carry. Neither is negative.
ProviderPriority, ReplacesPriority int
// DataHash is the lowercase hex SHA-256 of the data segment (PKGINFO
// datahash); empty for index entries.
DataHash string
// Checksum is the index "C:" value: "Q1" + base64(SHA-1 of the control
// segment).
Checksum string
// Size is the size of the .apk file (index field S).
Size int64
// Signed reports that the file starts with an abuild signature segment.
// [ParsePackage] does not verify the signature, [VerifyPackage] does.
Signed bool
// Format is the container format: [FormatV2] (gzip streams of tar) or
// [FormatV3] (ADB). Checksum, DataHash and Packager are v2 fields; a v3
// package carries Hashes instead.
Format Format
// Hashes is the v3 package identity (the 20-byte digest of its ADB
// block); nil for v2.
Hashes []byte
// Recommends is the v3 recommends list; v2 has no counterpart.
Recommends []string
}
Package is a verified .apk and also one APKINDEX entry.
func ParseIndex ¶
ParseIndex reads an APKINDEX: either the plain text or an APKINDEX.tar.gz, told apart by the gzip magic. The archive is read as abuild writes it: any number of gzip members, those whose tar starts with a .SIGN. entry (the signature) skipped, and exactly one holding an APKINDEX entry. Signatures are not verified here. Input is bounded: 512 MiB decompressed, 2 000 000 entries and 1 MiB per line. Every entry must carry the C, P, V and A fields and valid values, otherwise the whole index is refused; unknown field letters are ignored. Control characters in the free text fields (T, U, L, o, m, c) are replaced by a space: a few Alpine descriptions contain tabs. Errors wrap ErrInvalidIndex.
func ParsePackage ¶
ParsePackage parses and verifies an .apk of size bytes: it locates the gzip members exactly, reads the control segment, checks that the PKGINFO datahash is the SHA-256 of the data segment, fully decompresses the data segment (verifying its gzip checksum) and refuses entries that are absolute or climb out of their directory. Every error wraps ErrInvalidPackage.
An APKv3 package (an ADB container, as apk-tools 3 writes) is read with adb.ParsePackage and returned in the same form, with Format set to FormatV3; its structure is checked, not its file digests (use adb.VerifyPackage or adb.Extract for those).
func VerifyIndex ¶
func VerifyIndex(data []byte, opts VerifyOptions) ([]Package, error)
VerifyIndex parses an APKINDEX.tar.gz like ParseIndex and checks that the signature member in front of the index member holds a valid signature of the index member by a key of opts.Keys, in a type of opts.Algorithms. The errors are those of VerifyPackage; plain APKINDEX text is ErrUnsigned.
func VerifyPackage ¶
VerifyPackage parses the .apk of size bytes like ParsePackage and checks that its signature segment holds a valid signature of the control segment by a key of opts.Keys, in a type of opts.Algorithms. The error is ErrUnsigned for a package without signature, ErrUntrusted when no signature is by a trusted key in an accepted type, ErrBadSignature when a trusted key's signature does not match; a malformed package wraps ErrInvalidPackage.
func WritePackage ¶
WritePackage writes the .apk described by spec to w: the optional signature segment, the control segment (.PKGINFO and the install scripts) and the data segment, three gzip members as abuild writes them. Each regular file of the data segment carries its SHA-1 in a PAX record (APK-TOOLS.checksum.SHA1) and the .PKGINFO records the SHA-256 of the data segment (datahash).
The result is deterministic for a given spec. It returns the package as an index entry: its checksum, size and datahash, ready for BuildIndex. Errors for a spec it refuses wrap ErrInvalidSpec.
type Replacement ¶ added in v0.4.0
type Replacement uint8
Replacement is the decision on a file that two packages both ship: whether the incoming package may take it over from the package that owns it.
const ( // ReplaceYes: the incoming package takes the file; apk overwrites it // without a warning. ReplaceYes Replacement = iota + 1 // ReplaceNo: the owner keeps the file and the incoming package's copy is // skipped. ReplaceNo // ReplaceConflict: the metadata does not say who wins; apk refuses the // installation unless it is forced ("trying to overwrite ... owned by"). ReplaceConflict )
The decisions of ReplacesFile.
func ReplacesFile ¶ added in v0.4.0
func ReplacesFile(owner, incoming *Package) Replacement
ReplacesFile decides who gets a file that both owner (installed) and incoming (about to be installed) ship, with apk's rules: an overlay file (a nil owner) goes to the incoming package; two versions of the same package are no conflict; otherwise each side's "replaces" list and "replaces_priority" are compared, a package that lists the other in "replaces" wins over one that does not, the higher priority wins, and two packages of the same origin share files; anything else is a conflict.
Example ¶
Decide which of two packages that ship the same file keeps it.
package main
import (
"fmt"
"github.com/M0Rf30/pkgformat/apk"
)
func main() {
owner := &apk.Package{Name: "old", Version: "1"}
incoming := &apk.Package{Name: "new", Version: "1", Replaces: []string{"old"}, ReplacesPriority: 1}
fmt.Println(apk.ReplacesFile(owner, incoming))
fmt.Println(apk.ReplacesFile(owner, &apk.Package{Name: "other", Version: "1"}))
}
Output: yes conflict
func (Replacement) String ¶ added in v0.4.0
func (r Replacement) String() string
String returns "yes", "no" or "conflict".
type Repo ¶
type Repo struct {
// URL is the base URL of the repository, without a trailing slash: the
// index is at <URL>/<arch>/APKINDEX.tar.gz.
URL string
// Tag is the tag of a tagged repository ("edge" for "@edge https://…"),
// empty for an untagged one. [Index.Solve] uses it: a package of a tagged
// repository is only chosen when a "name@tag" dependency allows it.
Tag string
}
Repo is one repository of a repositories file.
func ParseRepositories ¶
ParseRepositories parses the text of an apk repositories file (the repositories file of /etc/apk): one repository per line, either a URL or "@tag URL", with blank lines and '#' comments ignored. Trailing slashes are dropped. It reads at most 1 MiB and 10 000 repositories. The caller opens the file; the package never reads a host path.
type RepoPackage ¶
type RepoPackage struct {
Package
// Repo is the repository whose index lists the package.
Repo Repo
// IndexArch is the architecture directory of that index. The package file
// is in it whatever the package's own Arch is: noarch packages sit next to
// the architecture-specific ones.
IndexArch string
// contains filtered or unexported fields
}
RepoPackage is an index entry together with where it was found.
func (*RepoPackage) URL ¶
func (p *RepoPackage) URL() string
URL returns the download URL of the package file: <repository>/<index arch>/<name>-<version>.apk.
type Scripts ¶
type Scripts struct {
PreInstall, PostInstall string
PreUpgrade, PostUpgrade string
PreDeinstall, PostDeinstall string
// Trigger is the .trigger script.
Trigger string
}
Scripts are the install scripts of a package. Each is the complete file, shebang included, and is stored executable in the control segment under the name apk runs it by; an empty script is left out. A script of an install hook that also runs on upgrade is set in both fields (PreInstall and PreUpgrade), as abuild's single pre-install script would not run on upgrade.
type SigAlgorithm ¶
type SigAlgorithm int
SigAlgorithm selects the signature type of an abuild signature entry. The zero value is invalid: every caller states which type it signs with or accepts.
const ( // SigRSASHA1 is RSA PKCS#1 v1.5 over SHA-1, the entry // .SIGN.RSA.<key name>: what abuild-sign writes and every apk-tools // version verifies. SigRSASHA1 SigAlgorithm = iota + 1 // SigRSASHA256 is RSA PKCS#1 v1.5 over SHA-256, the entry // .SIGN.RSA256.<key name>. SigRSASHA256 )
func (SigAlgorithm) String ¶
func (a SigAlgorithm) String() string
String returns "RSA-SHA1", "RSA-SHA256" or "invalid".
type Signature ¶
type Signature struct {
// KeyName is the key name in the entry name, e.g. "alpine-devel@lists.alpinelinux.org-5261cecb.rsa.pub".
KeyName string
// Algorithm is the signature type; zero for an entry of a type this
// package does not know (.SIGN.DSA.…).
Algorithm SigAlgorithm
// Value is the signature bytes.
Value []byte
}
Signature is one signature entry of a package or index.
type Signer ¶
type Signer struct {
// contains filtered or unexported fields
}
Signer signs packages and indexes with an RSA key under the name apk looks the public key up by: the file name in its keys directory. The private key can live outside the process: any crypto.Signer whose public key is RSA works, such as a key held by an HSM or a cloud KMS.
func NewSigner ¶
NewSigner returns a Signer for key that writes signatures of type alg. keyName must match ^[A-Za-z0-9._@+-]+\.rsa\.pub$ and keep the entry name (the type's prefix and keyName) within 100 bytes. key is an *rsa.PrivateKey or any other crypto.Signer with an RSA public key of 2048 to 16384 bits; it is asked for PKCS#1 v1.5 signatures over the SHA-1 or SHA-256 digest (crypto.SHA1 or crypto.SHA256 as the signer options), so a hardware or KMS signer must support that scheme. A zero alg is ErrNoAlgorithm.
Example ¶
Sign a package with a key that lives in an HSM or KMS: any crypto.Signer with an RSA public key works.
package main
import (
"crypto"
"crypto/rsa"
"fmt"
"io"
"log"
"github.com/M0Rf30/pkgformat/apk"
)
// hsm stands for a signing service: the private key never leaves it.
type hsm struct{ key *rsa.PrivateKey }
func (h hsm) Public() crypto.PublicKey { return h.key.Public() }
func (h hsm) Sign(r io.Reader, digest []byte, o crypto.SignerOpts) ([]byte, error) {
return h.key.Sign(r, digest, o)
}
func main() {
key, err := apk.GenerateKey(2048)
if err != nil {
log.Fatal(err)
}
name, err := apk.PublicKeyName("builder@example.org", &key.PublicKey)
if err != nil {
log.Fatal(err)
}
signer, err := apk.NewSigner(name, hsm{key}, apk.SigRSASHA256)
if err != nil {
log.Fatal(err)
}
spec := &apk.Spec{Info: apk.Info{Name: "signed", Version: "1-r0", Arch: "noarch"}}
if _, err := apk.WritePackage(io.Discard, spec, apk.WriteOptions{Signer: signer}); err != nil {
log.Fatal(err)
}
fmt.Println(signer.EntryName() == ".SIGN.RSA256."+name)
}
Output: true
func (*Signer) Algorithm ¶
func (s *Signer) Algorithm() SigAlgorithm
Algorithm returns the signature type the Signer writes.
func (*Signer) EntryName ¶
EntryName returns the name of the signature tar entry: .SIGN.RSA.<KeyName> or .SIGN.RSA256.<KeyName>.
func (*Signer) Fingerprint ¶
Fingerprint returns the hex SHA-256 of the DER SubjectPublicKeyInfo.
func (*Signer) PublicKeyPEM ¶
PublicKeyPEM returns the public key as a "PUBLIC KEY" (SubjectPublicKeyInfo) PEM block: what apk keeps in its keys directory.
func (*Signer) Sign ¶
Sign returns the RSA PKCS#1 v1.5 signature of the digest of data: the content of the Signer.EntryName entry. For a package data is the control segment, for an index the index segment; WritePackage, SignPackage and BuildIndex do that.
type Solution ¶ added in v0.4.0
type Solution struct {
// Packages are all the packages of the resulting system that the index
// lists or that are installed, dependencies before the packages that need
// them. A package that is installed and stays is in it too.
Packages []*RepoPackage
// Changes are the removals, then the installs and replacements in the
// order of Packages.
Changes []Change
}
Solution is the result of Index.Solve.
type SolveError ¶ added in v0.4.0
type SolveError struct {
Problems []SolveProblem
}
SolveError is the error of an unsatisfiable request. It wraps ErrUnsatisfiable.
func (*SolveError) Error ¶ added in v0.4.0
func (e *SolveError) Error() string
Error renders the problems the way apk prints them.
func (*SolveError) Unwrap ¶ added in v0.4.0
func (e *SolveError) Unwrap() error
Unwrap returns ErrUnsatisfiable.
type SolveProblem ¶ added in v0.4.0
type SolveProblem struct {
// Name is the package or capability that could not be selected.
Name string
// Reason says why: no package provides it, no candidate meets the
// constraints, or the candidates conflict with the rest of the selection.
Reason string
// RequiredBy are the requesters: "world[name]" or "package-version[dep]".
RequiredBy []string
}
SolveProblem is one dependency that could not be met.
type SolveRequest ¶ added in v0.4.0
type SolveRequest struct {
// World is the set of dependencies the system must meet, the entries of
// /etc/apk/world: "name", "name=1.2", "name>=1.2", "name@tag",
// "name@tag>=1.2" and "!name". Dependencies of the packages are
// followed; everything installed that the world does not lead to is
// removed.
World []string
// Installed are the packages installed now. A package that stays is
// preferred to a different version of it, unless Upgrade is set.
Installed []Package
// Upgrade selects the latest version of everything (apk upgrade) instead
// of keeping what is installed.
Upgrade bool
}
SolveRequest is what Index.Solve resolves.
type UpdatedIndex ¶
type UpdatedIndex struct {
*Index
// Failures are the repositories that were left out.
Failures []*RepoError
}
UpdatedIndex is the result of Client.Update.
type VerifyOptions ¶
type VerifyOptions struct {
// Keys are the trusted public keys.
Keys *Keyring
// Algorithms are the accepted signature types. A SHA-1 signature is only
// accepted when SigRSASHA1 is listed.
Algorithms []SigAlgorithm
}
VerifyOptions says which signatures to trust. Both fields are required: the caller chooses the trust anchors and the signature types it accepts, there is no default.
type WriteOptions ¶
type WriteOptions struct {
// Signer, when set, puts a signature segment of the control segment in
// front of the package.
Signer *Signer
// NoParentDirs turns off the parent directories. By default a directory
// that holds an entry but is not itself an entry of Spec.Files is added
// before the first entry below it, as a 0755 root:root directory with the
// epoch as its time, so a [Spec] may list only files. With NoParentDirs
// every parent must be listed, or WritePackage refuses the spec.
NoParentDirs bool
// TempDir is where the compressed data segment is spooled until its hash
// is known (the control segment, which comes first in the file, records
// it). Empty selects os.TempDir.
TempDir string
}
WriteOptions configures WritePackage.