pacman

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 51 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

pacman

Part of pkgformat.

Go Reference

A Go library to build, read, index and download Arch Linux packages and repositories, in pure Go. It needs no makepkg, no pacman, no repo-add and no PKGBUILD: a package is described with plain Go structs.

Install

go get github.com/M0Rf30/pkgformat/pacman

Requires Go 1.27 or later.

What it does

Area API
Write .pkg.tar.zst, .xz, .gz Spec, PkgInfo, BuildInfo, Scriptlets, File, ScanDir, ScanDirWith, Spec.Write, Spec.WriteFile, WriteOptions
Read packages ReadPackage, ParsePkgInfo, ParseBuildInfo, ReadMetadata, ParseInstall, WalkPackage
Extract and verify Extract, ExtractOptions, VerifyPackage, VerifyPackageWith, VerifyInstalled, VerifyOptions, MtreeError
.MTREE ParseMtree, ReadMtree, Mtree, MtreeEntry, MtreeKeys, (*LocalDB).Mtree, (*LocalDB).VerifyInstalled
Installed packages FindLocalDB, OpenLocalDB, NewLocalDB, (*LocalDB): Packages, List, InstalledNames, InstalledProvides
Sync databases ReadDB, ReadFileLists, WriteDB, NewDBEntry, DBEntry
Versions and dependencies Vercmp, ParseDependency, Dependency.Allows
Signatures SignDetached, NormalizeSignature, verification through gpg
pacman.conf and mirrorlists ParseConfig, ParseConfigFile, ParseConfigFS, ParseOptions, Config, Repo, SigLevel, ParseMirrorlist, ExpandServer; Config: IsHeld, IsIgnored, Arch, AllowedArchitectures, ResolveOptions, ApplyUsage, ReposFor
Repository client Client: FetchDB, SyncDB, Sync, DownloadPackage, DownloadPackageFile, VerifyPackageFile
Search and resolution Index: Lookup, Providers, Search, Group, Resolve, ResolveDeps, Install, Sysupgrade, OptionalDeps, SetUsage; ResolveOptions, Transaction, Upgrade, Replacement, ConflictError, BrokenDependencyError, OptionalDep, ParseOptionalDep

The writer produces what makepkg does: .PKGINFO, .BUILDINFO, a gzipped .MTREE with SHA-256 digests, .INSTALL with the six hooks, .CHANGELOG, and a payload sorted by path with its parent directories. With WriteOptions.ClampMTime the archive is reproducible from the build date.

A File can also be a hard link (Hardlink), a pipe, a character or block device (DevMajor, DevMinor), and carry an owner (UID, GID, Uname, Gname) and extended attributes (Xattrs, stored as the SCHILY.xattr.* and LIBARCHIVE.xattr.* PAX records bsdtar writes, security.capability included). ScanDir finds hard links and pipes; ScanDirWith also reads owners and xattrs. The .MTREE lists a hard link as the file it is, and WriteOptions.MtreeMD5 adds md5digest before sha256digest, in the order bsdtar writes them (makepkg 7.1 writes sha256digest only).

Examples

Build a package, read it back, publish it in a database and resolve against it:

spec := &pacman.Spec{
	Info: pacman.PkgInfo{
		Name: "hello", Version: "1.0-1", Description: "A greeting", Arch: "x86_64",
		BuildDate: 1700000000, Depends: []string{"glibc"},
	},
	Scriptlets: &pacman.Scriptlets{PostInstall: "echo installed"},
	Files: []pacman.File{
		{Path: "usr/bin/hello", Mode: 0o755, Data: []byte("#!/bin/sh\necho hello\n")},
	},
}

var pkg bytes.Buffer
err := spec.Write(&pkg, pacman.WriteOptions{Compression: pacman.CompressionZstd, ClampMTime: true})

entry, err := pacman.NewDBEntry(spec.FileName(pacman.CompressionZstd), bytes.NewReader(pkg.Bytes()), nil)

var db bytes.Buffer
err = pacman.WriteDB(&db, []pacman.DBEntry{*entry}, false)

var index pacman.Index
err = index.AddDatabase("local", &db)

dep, _ := pacman.ParseDependency("hello>=0.9")
best, err := index.Resolve(dep)

Package a directory tree:

files, err := pacman.ScanDir("pkgroot")
spec := &pacman.Spec{Info: info, Files: files}
err = spec.WriteFile("out/"+spec.FileName(pacman.CompressionZstd), pacman.WriteOptions{})

Sync databases from the mirrors of a pacman.conf and download a package, verifying signatures against a keyring:

keyring, err := gpg.LoadKeyringFile("archlinux.gpg")
client, err := pacman.NewClient(pacman.ClientOptions{
	Keyring:           keyring,
	DBSignatures:      pacman.VerifyRequired,
	PackageSignatures: pacman.VerifyRequired,
})

cfg, err := pacman.ParseConfigFile("/etc/pacman.conf", pacman.ParseOptions{})
n, err := client.Sync(ctx, cfg.Repos, "sync")

db, err := client.FetchDB(ctx, cfg.Repos[0])
entries, err := db.Entries()
path, err := client.DownloadPackage(ctx, cfg.Repos[0], &entries[0], "cache")

Resolution

An Index holds the sync databases (AddDatabase, Add) and plans what pacman -S and pacman -Su would do, with libalpm's choices:

local, err := localDB.List(ctx) // []*pacman.InstalledPackage
tx, err := index.Install([]string{"app", "base"}, pacman.ResolveOptions{Local: local})
tx, err = index.Sysupgrade(local, pacman.ResolveOptions{IgnorePkg: []string{"linux*"}})
// tx.Packages in dependency order; tx.Installs, tx.Upgrades, tx.Replacements, tx.Removals
  • A dependency is looked up among the installed packages (ResolveOptions.Local, ResolveOptions.Installed) first, then in the repositories in the order they were added. A package of the exact name wins (the newest version of the first repository that has it), then a provider: an installed one, then the one of the earliest repository, then the lowest name. Pass Index.SetUsage (Config.ApplyUsage does it for every repository) to keep a repository out of resolution: libalpm uses one whose Usage has Install or Upgrade.
  • Versions compare with Vercmp; =, <, <=, > and >= constrain a dependency, a conflict or a replacement. A provision without a version satisfies only a dependency without one.
  • A root can be a dependency expression, a provider or a group name (Index.Group); a group stands for its members.
  • Conflicts: two packages of the transaction that conflict, by name, version or provision, fail with ErrConflict (ConflictError names both), unless one provides the name of the other, which then takes its place. A conflict with an installed package that stays fails the same way. A package that stops satisfying a dependency of an installed package fails with ErrBrokenDependency. An unsatisfiable dependency fails with ErrUnresolved.
  • Sysupgrade upgrades every installed package whose first repository holds a newer version, and applies replaces (the replacement is installed, the replaced package removed). IgnorePkg and IgnoreGroup (globs, as in pacman.conf; Config.ResolveOptions fills them) keep a package from being upgraded, replaced or picked as a dependency; a package asked for by name is installed anyway. Repositories without the Upgrade usage are skipped.
  • Optional dependencies are listed (IndexedPackage.OptionalDeps, Index.OptionalDeps, parsed by ParseOptionalDep) and never installed unless ResolveOptions.WithOptional is set.

testdata/resolver holds the scenarios the tests replay against the output of a real pacman (see its README).

Reading pacman.conf

ParseConfig, ParseConfigFile and ParseConfigFS read every option of [options] and the keys of the repository sections, with the semantics of pacman 7: Include (recursive, with globs, in [options] and in repositories, the current section carrying on after an include), list options split on spaces, single-valued options, the root-relative defaults of DBPath and LogFile, ParallelDownloads, CleanMethod, DisableSandbox and the boolean flags. ParseOptions.Include decides how an Include is resolved: ParseConfigFile reads the host, ParseConfigFS any fs.FS, and with neither (ParseConfig and no resolver) the line is skipped. Directives the parser does not know are kept in Config.Unknown, or fail with ErrUnknownDirective under ParseOptions.Strict.

SigLevel is typed: Config.SigLevel, LocalFileSigLevel, RemoteFileSigLevel and Repo.SigLevel hold a package and a database SigPolicy (SigNever, SigOptional, SigRequired, plus TrustedOnly or TrustAll), computed like pacman does: tokens apply left to right over the global level, which each repository starts from. The Client enforces a repository's SigLevel over ClientOptions.DBSignatures and PackageSignatures, which remain the fallback when the repository has none. The keyring has no trust levels, so TrustedOnly and TrustAll verify alike.

Repo.Usage limits what a repository is used for: Client.Sync skips those without UsageSync, and Config.ApplyUsage passes the rest to an Index, whose resolution then keeps to repositories with UsageInstall. Config.ResolveOptions carries IgnorePkg and IgnoreGroup, IsHeld and IsIgnored answer HoldPkg and IgnorePkg with pacman's glob matching, and Repo.CacheServers (CacheServer) are tried before Server for packages, never for databases. DownloadPackageFile and VerifyPackageFile apply a SigPolicy to a package that is not in a database.

Extracting and verifying packages

ReadMetadata returns .PKGINFO, .BUILDINFO (formats 1 and 2), .INSTALL (with the hook functions it defines, InstallScript.Has), .CHANGELOG and the parsed .MTREE. ParseMtree reads every keyword (type, mode, uid, gid, uname, gname, size, time with fractions, link, nlink, the md5, sha1, sha256, sha384, sha512 and rmd160 digests, cksum, flags, device, inode, contents, optional), /set and /unset, the nested form with .., continuation lines and \ooo escapes; the keywords of an entry are MtreeEntry.Keys.

Extract unpacks below a directory: modes and mtimes, owners (Chown, which needs privilege), hard links, symbolic links, pipes, device nodes (SpecialFiles) and xattrs (Xattrs). Nothing is written outside the directory: entry names are validated, and a symbolic link is resolved as a chroot would, so lib -> /usr/lib works and evil -> / stays inside. Special mode bits follow ExtractOptions.Umask, and MaxBytes and MaxEntries bound the work. Verify checks the result against the .MTREE; so do VerifyPackage, which checks the archive itself, and VerifyInstalled, which checks a tree and reports a *MtreeError listing each MtreeDiff.

The files database

WriteDB(w, entries, true) writes what repo-add writes into <repo>.files: the desc and files members of each package, with the %FILES% list that NewDBEntry reads out of the package, and %PGPSIG% when given a signature. ReadDB reads it back, ReadFileLists reads the file lists of the wanted packages only. The tests compare the members with those repo-add writes and have pacman -Fy, -Fl and -F answer from a database written here.

The local database

OpenLocalDB reads /var/lib/pacman/local, read-only and without locking: FindLocalDB("/") gives the path under a root, and NewLocalDB reads any fs.FS. Each <name>-<version> directory yields an InstalledPackage from its desc (name, version, base, description, URL, architecture, packager, build and install dates, installed size, install reason, licenses, groups, validation, xdata, and the dependency, provides, conflicts and replaces lists) and its files (%FILES% and %BACKUP%). desc is read with the parser of the sync database. LocalDB.Mtree parses the mtree member, and LocalDB.VerifyInstalled checks the installed files against it like pacman -Qkk: directory times are left alone and the package's backup files are not checked for content.

The name of a package is its %NAME%, never part of the directory name. Symbolic links inside the database that point out of it are not followed. A directory without a valid desc, with a malformed value, a path that climbs out of the root, or over a limit is skipped and logged at debug level. An ALPM_DB_VERSION other than 9 is ErrUnsupportedLocalDB. InstalledNames and InstalledProvides do not read the files members: they list the names, and the provides without version constraints and with each package's own name. LocalDBOptions bounds the packages and the file records of one package, and SkipFiles leaves the file lists out. pacman writes (null) as the checksum of a %BACKUP% file it has none for; BackupFile.MD5 keeps it.

Security notes

  • Packages and databases are untrusted input. Decompressed size, entry count, path length, file-list size, and the zstd and xz windows all have explicit limits (MaxUncompressedBytes, MaxFileEntries, MaxDBBytes, ...); hitting one returns an error wrapping a sentinel such as ErrPackageTooLarge.
  • Paths inside packages are validated; an unsafe one fails with ErrUnsafeEntry. ScanDir opens files below its root and does not follow links out of it.
  • The writer rejects line breaks, NUL bytes and invalid UTF-8 in metadata fields, and paths that could clash with the metadata files, so a field value cannot inject another .PKGINFO line.
  • The client checks a package against the size and SHA-256 (or MD5) of its database entry, and against its signature when PackageSignatures is set. A signature that cannot be fetched is an error, not "unsigned". A failed database or package is discarded and the next mirror is tried.
  • The library never reads a host path on its own: configuration, keyrings and directories are passed in.
  • Configuration files are bounded: one file (MaxConfigBytes), all the files of a parse together (MaxConfigTotalBytes), repositories, servers and values (MaxConfigRepos, MaxConfigServers, MaxConfigValues), include depth (DefaultMaxIncludeDepth, ten as in pacman) and the number of included files (DefaultMaxIncludeFiles); hitting one wraps ErrConfigLimit. ParseConfigFS cannot leave its fs.FS. A repository that requires signatures with no keyring fails with ErrNoKeyring rather than skipping the check.
  • Extract never follows a link out of its directory, refuses names with .., absolute names and control characters, and creates device nodes only on request; xattr counts and values are bounded (MaxEntryXattrs, MaxXattrValueBytes), and so are the .MTREE (MaxMtreeBytes, MaxMtreeEntries, MaxMtreeLineBytes) and the metadata files (MaxMetadataBytes, MaxChangelogBytes).
  • .MTREE carries SHA-256 digests, and MD5 too under WriteOptions.MtreeMD5.

License

Apache License 2.0, see LICENSE.

Documentation

Overview

Package pacman builds, reads and indexes Arch Linux packages and repositories in pure Go, without makepkg, pacman or repo-add.

Writing packages

A Spec describes a package with plain Go values: the PkgInfo that becomes .PKGINFO, an optional BuildInfo for .BUILDINFO, Scriptlets for .INSTALL, a changelog and the File list. Spec.Write produces a .pkg.tar.zst, .xz or .gz, with .PKGINFO, .BUILDINFO, .MTREE, .INSTALL and .CHANGELOG in the order pacman expects and every directory entry the payload needs. With WriteOptions.ClampMTime the output is reproducible: file times never exceed PkgInfo.BuildDate, as makepkg does with SOURCE_DATE_EPOCH. ScanDir lists a directory tree as Files. A File can be a hard link, a pipe, a device node, and carry an owner and xattrs (ScanDirWith reads them); WriteOptions.MtreeMD5 adds md5digest to the .MTREE.

Reading packages and databases

ReadPackage returns the PkgInfo and the file list of a package, ParsePkgInfo and ParseBuildInfo parse the metadata files on their own, and ReadDB reads a sync database ("core.db") into DBEntry values. WriteDB writes one, the way repo-add does, from entries NewDBEntry builds out of package files. Vercmp compares versions like libalpm. The files database ("core.files") is the same format: WriteDB with withFiles, ReadDB and ReadFileLists.

Extracting and verifying

ReadMetadata reads the metadata files of a package, ParseMtree the .MTREE. Extract unpacks a package into a directory without writing outside it, restoring modes, times, hard links, pipes, optionally owners, device nodes and xattrs. VerifyPackage, VerifyPackageWith and Extract with Verify check a package against its .MTREE; VerifyInstalled and LocalDB.VerifyInstalled do what pacman -Qkk does for installed files.

The local database

OpenLocalDB, NewLocalDB and FindLocalDB read the installed packages of /var/lib/pacman/local, read-only: LocalDB.Packages yields an InstalledPackage for each package directory, from its desc and files members, named by its %NAME%. LocalDB.InstalledNames and LocalDB.InstalledProvides list the installed names and capabilities.

Repositories

ParseConfig, ParseConfigFS and ParseConfigFile read pacman.conf, with its includes, into a Config of typed options and Repo values (SigLevel, Usage, Server, CacheServer); ParseMirrorlist reads a mirrorlist. They touch no file unless asked to (ParseConfigFile, ParseConfigFS), and no path is built in. A Client fetches databases from the servers of a Repo, with mirror failover, OpenPGP verification as the repository's SigLevel or ClientOptions say (VerifyMode) and atomic writes (SyncDB, Sync, which skips repositories whose Usage excludes it), and downloads packages checked against their database entry, from CacheServer addresses first (DownloadPackage), or from a URL (DownloadPackage).

Resolution

An Index holds the entries of several databases. Index.Resolve and Index.ResolveDeps resolve dependencies and provisions; Index.Install plans what "pacman -S" does for targets that are packages, providers or groups (Index.Group), and Index.Sysupgrade what "pacman -Su" does, as a Transaction of installs, upgrades, replacements ("replaces") and removals. The plan follows libalpm: versioned dependencies, provisions and conflicts compare with Vercmp, a provision without a version satisfies only a dependency without one, a package of the exact name is preferred to a provider, ignored packages (ResolveOptions.IgnorePkg, IgnoreGroup) are not upgraded, and the Usage of a repository (Index.SetUsage) decides whether it is used. Conflicts and broken dependencies fail with ErrConflict and ErrBrokenDependency. Optional dependencies are exposed (OptionalDep) and not installed unless asked for.

Signatures

SignDetached signs a package or database with a gpg.Signer and returns the binary signature pacman expects in a ".sig" file; NormalizeSignature accepts an armored one too.

Untrusted input

Everything read is bounded: sizes, entry counts, path lengths and the zstd and xz windows have explicit limits, paths are validated, and failures are returned as errors wrapping the exported sentinels, never as panics. The writer rejects values that would corrupt a metadata file, such as a line break in a field.

Example
package main

import (
	"bytes"
	"fmt"
	"strings"
	"time"

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

func main() {
	spec := &pacman.Spec{
		Info: pacman.PkgInfo{
			Name: "hello", Version: "1.0-1", Description: "A greeting", Arch: "x86_64",
			BuildDate: 1700000000, Depends: []string{"glibc"},
		},
		Scriptlets: &pacman.Scriptlets{PostInstall: "echo installed"},
		Files: []pacman.File{
			{Path: "usr/bin/hello", Mode: 0o755, Data: []byte("#!/bin/sh\necho hello\n"), ModTime: time.Unix(1700000000, 0)},
		},
	}

	// Write the package, reproducibly.
	var pkg bytes.Buffer
	if err := spec.Write(&pkg, pacman.WriteOptions{Compression: pacman.CompressionZstd, ClampMTime: true}); err != nil {
		fmt.Println(err)

		return
	}

	// Read it back.
	read, err := pacman.ReadPackage(bytes.NewReader(pkg.Bytes()))
	if err != nil {
		fmt.Println(err)

		return
	}

	fmt.Println(spec.FileName(pacman.CompressionZstd), read.Info.Depends, read.Files)

	// Put it in a database and resolve a dependency against it.
	entry, err := pacman.NewDBEntry(spec.FileName(pacman.CompressionZstd), bytes.NewReader(pkg.Bytes()), nil)
	if err != nil {
		fmt.Println(err)

		return
	}

	var db bytes.Buffer
	if err := pacman.WriteDB(&db, []pacman.DBEntry{*entry}, false); err != nil {
		fmt.Println(err)

		return
	}

	var index pacman.Index
	if err := index.AddDatabase("local", &db); err != nil {
		fmt.Println(err)

		return
	}

	dep, _ := pacman.ParseDependency("hello>=0.9")
	best, err := index.Resolve(dep)
	fmt.Println(best.Repo, best.Version, err, pacman.Vercmp("1.0-1", "1.0.1-1"))

	// A pacman.conf yields repositories whose server URLs expand per arch.
	cfg, _ := pacman.ParseConfig(strings.NewReader("[core]\nServer = https://mirror.example/$repo/os/$arch\n"), pacman.ParseOptions{})
	fmt.Println(pacman.ExpandServer(cfg.Repos[0].Servers[0], "core", "x86_64"))

}
Output:
hello-1.0-1-x86_64.pkg.tar.zst [glibc] [usr/ usr/bin/ usr/bin/hello]
local 1.0-1 <nil> -1
https://mirror.example/core/os/x86_64

Index

Examples

Constants

View Source
const (
	// DefaultMaxDBBytes bounds a downloaded database; the largest Arch ones are
	// well under 50 MiB.
	DefaultMaxDBBytes int64 = 256 << 20
	// DefaultMaxPackageBytes bounds a package whose database entry declares no
	// compressed size.
	DefaultMaxPackageBytes int64 = 16 << 30
	// DefaultSyncConcurrency is the number of repositories Sync refreshes at a
	// time.
	DefaultSyncConcurrency = 4
)

Sizes the client enforces on what it downloads.

View Source
const (
	// MaxConfigBytes bounds one pacman.conf, included file or mirrorlist.
	MaxConfigBytes = 4 << 20
	// MaxConfigTotalBytes bounds the bytes read from a configuration and all
	// the files it includes.
	MaxConfigTotalBytes = 32 << 20
	// MaxConfigRepos bounds the repositories of one configuration.
	MaxConfigRepos = 1000
	// MaxConfigServers bounds the servers (or cache servers) of one repository.
	MaxConfigServers = 10000
	// MaxConfigValues bounds the entries of one list option, such as
	// IgnorePkg, and the retained unknown directives.
	MaxConfigValues = 100000
	// DefaultMaxIncludeDepth is the include nesting ParseOptions allows when
	// MaxIncludeDepth is zero; it is pacman's own limit.
	DefaultMaxIncludeDepth = 10
	// DefaultMaxIncludeFiles is the number of included files ParseOptions
	// allows in total when MaxIncludeFiles is zero.
	DefaultMaxIncludeFiles = 1000
)

Limits on the configuration files the parsers read.

View Source
const (
	// MaxDBBytes bounds the decompressed tar stream of a database.
	MaxDBBytes int64 = 2 << 30
	// MaxDBEntries bounds the entries of a database.
	MaxDBEntries = 500_000
	// MaxDescBytes bounds the "desc" (or "depends") member of one package.
	MaxDescBytes = 4 << 20
	// MaxDBFileListBytes bounds the file lists kept from one files database.
	MaxDBFileListBytes = 256 << 20
)

Limits on what reading one repository database may cost. A database is fetched from a mirror and is untrusted input.

View Source
const (
	// MaxEntryXattrs bounds the extended attributes of one entry.
	MaxEntryXattrs = 256
	// MaxXattrValueBytes bounds the value of one extended attribute.
	MaxXattrValueBytes = 64 << 10
)

Limits on the extended attributes of an entry read from an archive.

View Source
const (
	// DefaultMaxExtractBytes is the default limit on the bytes Extract writes.
	DefaultMaxExtractBytes int64 = 16 << 30
	// DefaultMaxExtractEntries is the default limit on the archive entries
	// Extract processes.
	DefaultMaxExtractEntries = 1 << 20
)
View Source
const (
	// DefaultMaxLocalPackages bounds the package directories of a database.
	DefaultMaxLocalPackages = MaxDBEntries
	// DefaultMaxLocalFiles bounds the file records of one package.
	DefaultMaxLocalFiles = 1 << 21
)

Default limits of the local-database reader, applied where a LocalDBOptions field is zero.

View Source
const (
	HookPreInstall  = "pre_install"
	HookPostInstall = "post_install"
	HookPreUpgrade  = "pre_upgrade"
	HookPostUpgrade = "post_upgrade"
	HookPreRemove   = "pre_remove"
	HookPostRemove  = "post_remove"
)

Hook names pacman runs from a package's .INSTALL file.

View Source
const (
	// MaxMtreeBytes bounds the decompressed text of an .MTREE.
	MaxMtreeBytes int64 = 1 << 30
	// MaxMtreeEntries bounds its entries.
	MaxMtreeEntries = MaxFileEntries
	// MaxMtreeLineBytes bounds one logical line, continuations included.
	MaxMtreeLineBytes = 64 << 10
)

Limits on reading a .MTREE.

View Source
const (
	CompressionZstd = "zst"
	CompressionXZ   = "xz"
	CompressionGzip = "gz"
)

Package compressions, the extension of the package file after ".pkg.tar.".

View Source
const (
	// MaxUncompressedBytes bounds the decompressed tar stream.
	MaxUncompressedBytes int64 = 32 << 30
	// MaxFileEntries bounds the entries of the archive.
	MaxFileEntries = 2_000_000
	// MaxFileListBytes bounds the bytes of the file list kept for the files database.
	MaxFileListBytes = 64 << 20
	// MaxEntryNameLen bounds one archive path.
	MaxEntryNameLen = 4096
)

Limits on what reading one package may cost. The package is untrusted input and a few KiB of zstd can decompress to gigabytes.

View Source
const (
	// MaxPkgInfoBytes bounds the .PKGINFO of a package.
	MaxPkgInfoBytes = 1 << 20
	// MaxNameLen bounds package names, versions, architectures and each
	// dependency-like value.
	MaxNameLen = 255
	// MaxValueLen bounds a free-text value (description, URL, packager).
	MaxValueLen = 4096
	// MaxListEntries bounds each multi-valued field.
	MaxListEntries = 5000
)

Field and size limits. They keep what a package can put into one database row and one desc entry bounded.

View Source
const (
	FilePkgInfo   = ".PKGINFO"
	FileBuildInfo = ".BUILDINFO"
	FileMtree     = ".MTREE"
	FileInstall   = ".INSTALL"
	FileChangelog = ".CHANGELOG"
)

Names of the metadata files a package carries at the top of its archive.

View Source
const ArchAny = "any"

ArchAny is the architecture of a package that runs on every architecture.

KeyDigests are the digest keywords.

View Source
const MaxBuildInfoBytes = 1 << 20

MaxBuildInfoBytes bounds a .BUILDINFO.

View Source
const MaxChangelogBytes = 16 << 20

MaxChangelogBytes bounds the .CHANGELOG of a package.

View Source
const MaxIndexPackages = 2_000_000

MaxIndexPackages bounds the packages an Index holds.

View Source
const MaxInstallBytes = 4 << 20

MaxInstallBytes bounds the .INSTALL scriptlet of a package.

View Source
const MaxMetadataBytes = 1 << 30

MaxMetadataBytes bounds one metadata member that Extract keeps in memory.

View Source
const MaxMtreeDiffs = 10000

MaxMtreeDiffs bounds the differences an MtreeError lists.

View Source
const MaxSignatureBytes = 16 << 10

MaxSignatureBytes bounds a detached signature (a few hundred bytes for an RSA 4096 or Ed25519 signature; the rest is room for hashed subpackets).

Variables

View Source
var (
	// ErrAllServersFailed wraps the failures of every server of a repository.
	ErrAllServersFailed = errors.New("pacman: all servers failed")
	// ErrNoServers reports a repository with no server.
	ErrNoServers = errors.New("pacman: repository has no servers")
	// ErrSignatureRequired reports a missing signature when the client is set
	// to require one.
	ErrSignatureRequired = errors.New("pacman: required signature is missing")
	// ErrNoKeyring reports a verification mode that needs a keyring, without one.
	ErrNoKeyring = errors.New("pacman: signature verification needs a keyring")
	// ErrChecksumMismatch reports a package that does not match the size or
	// digest its database entry declares.
	ErrChecksumMismatch = errors.New("pacman: package does not match its database entry")
	// ErrNoChecksum reports a database entry with neither a SHA-256 nor an MD5
	// sum, which makes the download unverifiable.
	ErrNoChecksum = errors.New("pacman: database entry has no checksum")
	// ErrInvalidRepoName reports a repository name that is not usable in a file
	// name.
	ErrInvalidRepoName = errors.New("pacman: invalid repository name")
)

Errors of the client. Test with errors.Is.

View Source
var (
	// ErrInvalidConfig reports a pacman.conf or mirrorlist that cannot be
	// parsed or exceeds a limit. The errors below wrap it.
	ErrInvalidConfig = errors.New("pacman: invalid configuration")
	// ErrConfigLimit reports an include nested too deeply, too many included
	// files or a configuration over a size limit.
	ErrConfigLimit = fmt.Errorf("%w: limit exceeded", ErrInvalidConfig)
	// ErrUnknownDirective reports, in strict mode, a directive pacman does not
	// know.
	ErrUnknownDirective = fmt.Errorf("%w: unknown directive", ErrInvalidConfig)
)

Errors of the configuration parsers. Test with errors.Is.

View Source
var (
	ErrNotDatabase = errors.New("pacman: not a pacman database")
	ErrDBTooLarge  = errors.New("pacman: database exceeds the limit")
)

Errors reading a database.

View Source
var (
	// ErrInvalidDependency reports a dependency expression that cannot be parsed.
	ErrInvalidDependency = errors.New("pacman: invalid dependency")
	// ErrUnresolved reports a dependency no package of the index satisfies.
	ErrUnresolved = errors.New("pacman: unresolvable dependency")
	// ErrIndexTooLarge reports an index that would exceed MaxIndexPackages.
	ErrIndexTooLarge = errors.New("pacman: index exceeds the package limit")
)

Errors of dependency parsing and resolution. Test with errors.Is.

View Source
var (
	// ErrLocalDBNotFound means [FindLocalDB] met no local database under the
	// root.
	ErrLocalDBNotFound = errors.New("pacman: no local database found")
	// ErrInvalidLocalDB means a directory is not a local database, or cannot
	// be read as one.
	ErrInvalidLocalDB = errors.New("pacman: invalid local database")
	// ErrLocalDBTooLarge means a local database is over one of the limits of
	// [LocalDBOptions].
	ErrLocalDBTooLarge = errors.New("pacman: local database exceeds a limit")
	// ErrUnsupportedLocalDB means the ALPM_DB_VERSION file names a layout this
	// package does not read.
	ErrUnsupportedLocalDB = errors.New("pacman: unsupported local database version")
)

Errors of the local-database reader. Test with errors.Is.

View Source
var (
	// ErrMtreeMismatch is matched (errors.Is) by the *MtreeError that reports
	// files that differ from their .MTREE.
	ErrMtreeMismatch = errors.New("pacman: contents differ from the .MTREE")
	// ErrNoMtree reports a package without an .MTREE to verify against.
	ErrNoMtree = errors.New("pacman: package has no .MTREE")
)

Errors of the verification against an .MTREE.

View Source
var (
	ErrNotPackage      = errors.New("pacman: not a pacman package")
	ErrNoPkgInfo       = errors.New("pacman: package has no .PKGINFO")
	ErrPackageTooLarge = errors.New("pacman: package expands beyond the limit")
	ErrUnsafeEntry     = errors.New("pacman: unsafe path in package")
)

Errors reading a package.

View Source
var (
	ErrPkgInfoTooLarge = errors.New("pacman: .PKGINFO too large")
	ErrMissingField    = errors.New("pacman: .PKGINFO misses a required field")
	ErrInvalidField    = errors.New("pacman: invalid .PKGINFO field")
)

Validation errors.

View Source
var (
	// ErrConflict reports packages that cannot be installed together, or a
	// package that conflicts with an installed one that is not removed.
	ErrConflict = errors.New("pacman: conflicting packages")
	// ErrBrokenDependency reports a transaction that leaves an installed
	// package without a dependency it had.
	ErrBrokenDependency = errors.New("pacman: transaction breaks a dependency")
)

Errors of transaction planning. Test with errors.Is; errors.As reaches the details in ConflictError and BrokenDependencyError.

View Source
var (
	// ErrInvalidFile reports a File that cannot be stored: a bad path, a
	// duplicate, a path below a regular file, or a body that does not match.
	ErrInvalidFile = errors.New("pacman: invalid package file")
	// ErrUnsupportedFile reports a file type a package cannot hold (a socket).
	ErrUnsupportedFile = errors.New("pacman: unsupported file type")
	// ErrReservedName reports a payload path whose first element starts with a
	// dot: pacman treats those as package metadata.
	ErrReservedName = errors.New("pacman: reserved package path")
	// ErrUnsupportedCompression reports a compression other than zst, xz, gz.
	ErrUnsupportedCompression = errors.New("pacman: unsupported compression")
)

Errors writing a package.

View Source
var ErrExtractTooLarge = errors.New("pacman: extraction exceeds the limit")

ErrExtractTooLarge reports that an extraction reached the limit of ExtractOptions.

View Source
var ErrInvalidMtree = errors.New("pacman: invalid .MTREE")

ErrInvalidMtree reports an .MTREE that cannot be parsed or exceeds a limit.

View Source
var ErrInvalidSigLevel = fmt.Errorf("%w: invalid SigLevel", ErrInvalidConfig)

ErrInvalidSigLevel reports a SigLevel value that names an unknown option. It wraps ErrInvalidConfig.

View Source
var ErrInvalidSignature = errors.New("pacman: not a detached OpenPGP signature")

ErrInvalidSignature reports a detached signature that is not exactly one OpenPGP binary-document signature.

View Source
var ErrMetadataTooLarge = errors.New("pacman: metadata file too large")

ErrMetadataTooLarge reports a metadata file over its limit.

View Source
var ErrNoLocalMtree = errors.New("pacman: installed package has no mtree")

ErrNoLocalMtree reports a package directory without an mtree member. Old packages and some tools leave it out; pacman -Qk falls back to the file list then.

Functions

func ArchFromGOARCH

func ArchFromGOARCH(goarch string) string

ArchFromGOARCH maps a GOARCH value to the architecture name Arch Linux (and its ports) use. Unknown values are returned unchanged.

func ExpandServer

func ExpandServer(server, repo, arch string) string

ExpandServer returns the URL of a server entry for a repository and an architecture: $repo and $arch are replaced and trailing slashes dropped.

func FileNameMatches

func FileNameMatches(filename string, info *PkgInfo, ext string) bool

FileNameMatches reports whether filename is the name the package described by info and ext must be published under: the one makepkg writes, or the same with the colon of an epoch written as a hyphen (the spelling of tools that avoid colons in file names).

func FileSums

func FileSums(data io.Reader) (md5sum, sha256sum string, err error)

FileSums returns the MD5 and SHA-256 of data as hex, the sums a database entry carries.

func FindLocalDB added in v0.3.1

func FindLocalDB(root string) (string, error)

FindLocalDB looks for the local database under root, the directory that holds the system's /var: "/" for the running host, or the root of an image or an install directory. Symbolic links are followed only inside root. It returns ErrLocalDBNotFound when there is no directory.

func NormalizeSignature

func NormalizeSignature(data []byte) ([]byte, error)

NormalizeSignature returns the binary form of a detached package signature given either as binary packets or ASCII-armored (gpg --armor), after checking it is a single OpenPGP signature over a binary document. The signature is not verified here: that needs a keyring (see gpg.VerifyDetached).

func PackageFileName

func PackageFileName(name, version, arch, ext string) string

PackageFileName returns the file name makepkg gives a package: name-version-arch.pkg.tar.ext, the colon of an epoch included.

func ParseMirrorlist

func ParseMirrorlist(r io.Reader) ([]string, error)

ParseMirrorlist returns the Server entries of a mirrorlist, in order. A server holding a control character is an ErrInvalidConfig.

func ReadFileLists

func ReadFileLists(r io.Reader, want func(dir string) bool) (map[string][]string, error)

ReadFileLists reads the "files" members of a files database: the file list of every package whose database directory (name-version, see DBEntry.DirName) want accepts, keyed by that directory. Other packages' lists are never retained, so reading the files database of a large repository costs memory in proportion to what is wanted.

func ReadMtree added in v0.4.0

func ReadMtree(r io.Reader, fn func(*MtreeEntry) error) error

ReadMtree parses an .MTREE like ParseMtree but hands each entry to fn as it is read, so that a huge file never sits in memory. The entry is reused between calls; fn must copy what it keeps. An error of fn stops the reading and is returned as it is.

func SignDetached

func SignDetached(signer gpg.Signer, data io.Reader) ([]byte, error)

SignDetached signs data with signer and returns the binary detached signature, the form pacman reads from a .sig file and from %PGPSIG%.

func SplitPackageFileName

func SplitPackageFileName(filename string) (string, string, bool)

SplitPackageFileName returns the extension ("zst", "xz", "gz") of a package file name and the part before ".pkg.tar.". ok is false for any other name.

func ValidArch

func ValidArch(s string) bool

ValidArch reports whether s is a legal architecture ("any", "x86_64", ...).

func ValidFileName

func ValidFileName(s string) bool

ValidFileName reports whether s is acceptable as the name of a package file in a repository: a name ending in ".pkg.tar.{zst,xz,gz}" made of the characters makepkg produces, never a path separator, a control byte or a leading dot.

func ValidFileNameChars

func ValidFileNameChars(s string) bool

ValidFileNameChars accepts the characters of package and database file names.

func ValidName

func ValidName(s string) bool

ValidName reports whether s is a legal package name: lowercase letters, digits and "@._+-", not starting with a hyphen or a dot (the makepkg rule).

func ValidRepoName

func ValidRepoName(s string) bool

ValidRepoName reports whether s can name a repository: it is used as a file name, so it must hold no path separator and not start with a dot.

func ValidVersion

func ValidVersion(s string) bool

ValidVersion reports whether s is a legal "[epoch:]pkgver-pkgrel": no whitespace, slashes or control characters, a numeric epoch when present and a release.

func Vercmp

func Vercmp(a, b string) int

Vercmp compares two package versions the way libalpm's alpm_pkg_vercmp does: "[epoch:]pkgver[-pkgrel]". It returns -1, 0 or 1. The release is compared only when both versions carry one.

func VerifyInstalled added in v0.4.0

func VerifyInstalled(fsys fs.FS, mt *Mtree, opts VerifyOptions) error

VerifyInstalled checks installed files against an .MTREE, the way pacman -Qkk does. fsys is the root of the system; give it an fs.FS that implements fs.ReadLinkFS and does not follow links out of the root, such as the one of an os.Root (os.OpenRoot(dir).FS()). A path the .MTREE lists that is not there is DiffMissing, whatever is not listed is not looked at.

Owners are compared when the file system reports them; the owner names of the .MTREE are not. Like pacman, it leaves the modification time of directories alone: installing or removing a file changes it.

func VerifyPackage added in v0.4.0

func VerifyPackage(r io.Reader, opts VerifyOptions) error

VerifyPackage checks the files of a package against its own .MTREE: type, mode, owner, size, modification time, link target and every digest the .MTREE lists (md5digest, sha1digest, sha256digest, sha384digest, sha512digest, rmd160digest and cksum). Keywords it does not know how to check (flags, device, inode, nlink, contents) are ignored.

It returns nil when everything matches, ErrNoMtree when the package has no .MTREE, and otherwise a *MtreeError that lists the differences.

Example

VerifyPackage checks the files of a package against its .MTREE.

package main

import (
	"bytes"
	"fmt"
	"io/fs"
	"time"

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

func examplePackage() []byte {
	built := time.Unix(1700000000, 0)

	spec := &pacman.Spec{
		Info: pacman.PkgInfo{Name: "shapes", Version: "1.0-1", Description: "Some shapes", Arch: "any", BuildDate: 1700000000},
		Scriptlets: &pacman.Scriptlets{
			PostInstall: "echo installed",
		},
		Files: []pacman.File{
			{Path: "usr/bin/shape", Mode: 0o755, ModTime: built, Data: []byte("#!/bin/sh\n")},
			{Path: "usr/bin/shape-hard", Hardlink: "usr/bin/shape", ModTime: built},
			{Path: "usr/bin/shape-link", Mode: fs.ModeSymlink | 0o777, Linkname: "shape", ModTime: built},
			{Path: "usr/share/shapes/data", Mode: 0o644, UID: 1234, GID: 5678, ModTime: built, Data: []byte("data\n")},
		},
	}

	var buf bytes.Buffer
	if err := spec.Write(&buf, pacman.WriteOptions{MtreeMD5: true}); err != nil {
		panic(err)
	}

	return buf.Bytes()
}

func main() {
	pkg := examplePackage()

	fmt.Println(pacman.VerifyPackage(bytes.NewReader(pkg), pacman.VerifyOptions{}))
}
Output:
<nil>

func VerifyPackageWith added in v0.4.0

func VerifyPackageWith(r io.Reader, mt *Mtree, opts VerifyOptions) error

VerifyPackageWith is VerifyPackage against an .MTREE that is given, such as the one of the local database, instead of the one inside the package.

func WalkPackage added in v0.4.0

func WalkPackage(r io.Reader, fn func(e *Entry, body io.Reader) error) error

WalkPackage reads a .pkg.tar.{zst,xz,gz} from r and calls fn for each member in archive order, the metadata files included. body yields the content of a regular file and is empty for any other kind; it is valid until fn returns. A non-nil error of fn stops the walk and is returned as it is.

The archive is untrusted: its decompressed size, the number of its entries, the length of paths and the number of extended attributes are bounded, and a path that is absolute, climbs above the root or holds a control character is refused with ErrUnsafeEntry. Socket-like and unknown member types fail with ErrUnsupportedFile.

func WriteDB

func WriteDB(w io.Writer, entries []DBEntry, withFiles bool) error

WriteDB writes a repository database as a gzip-compressed tar: one directory per package holding its "desc" and, when withFiles is set, its "files" entry. Entries are written in the order of name and version so the output does not depend on the input order.

Types

type BackupFile added in v0.3.1

type BackupFile struct {
	// Path is relative to the root of the system: "etc/pacman.conf".
	Path string
	// MD5 is the hex digest of the file as installed. pacman writes the text
	// "(null)" where it has none; it is kept as it is.
	MD5 string
}

BackupFile is a "%BACKUP%" line: a file pacman keeps a checksum of so that it can tell a user's edit from the packaged file on upgrade.

type BrokenDependencyError added in v0.4.0

type BrokenDependencyError struct {
	// Package is the installed package that would lose the dependency.
	Package string
	// Dependency is the dependency expression, such as "libold=1-1".
	Dependency string
	// By is the package that satisfied it and is upgraded or removed.
	By string
}

BrokenDependencyError reports an installed package whose dependency the transaction stops satisfying. It matches ErrBrokenDependency.

func (*BrokenDependencyError) Error added in v0.4.0

func (e *BrokenDependencyError) Error() string

Error implements error.

func (*BrokenDependencyError) Unwrap added in v0.4.0

func (e *BrokenDependencyError) Unwrap() error

Unwrap returns ErrBrokenDependency.

type BuildInfo

type BuildInfo struct {
	// Format is the .BUILDINFO format; zero means 2, the one makepkg writes.
	Format         int
	PkgName        string
	PkgBase        string
	PkgVer         string // [epoch:]pkgver-pkgrel
	PkgArch        string
	PkgbuildSHA256 string // hex SHA-256 of the build recipe
	Packager       string
	BuildDate      int64
	BuildDir       string
	StartDir       string
	BuildTool      string
	BuildToolVer   string
	BuildEnv       []string
	Options        []string
	// Installed lists the packages present in the build environment, each
	// "name-version-arch".
	Installed []string
}

BuildInfo is the .BUILDINFO of a package: how and where it was built.

func ParseBuildInfo

func ParseBuildInfo(r io.Reader) (*BuildInfo, error)

ParseBuildInfo parses the text of a .BUILDINFO. Unknown keys are ignored. A malformed number or a value over the limits is an error.

func (*BuildInfo) Render

func (b *BuildInfo) Render() ([]byte, error)

Render returns the text of the .BUILDINFO in the order makepkg writes it. Empty optional values are left out.

type CleanMethod added in v0.4.0

type CleanMethod uint8

CleanMethod is the CleanMethod option: what clearing the package cache keeps. The values combine with |.

const (
	// CleanKeepInstalled keeps the packages that are installed.
	CleanKeepInstalled CleanMethod = 1 << iota
	// CleanKeepCurrent keeps the packages in a sync database.
	CleanKeepCurrent
)

func (CleanMethod) String added in v0.4.0

func (m CleanMethod) String() string

String returns the option value, such as "KeepInstalled KeepCurrent".

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client fetches sync databases and packages from pacman mirrors. It is safe for concurrent use.

func NewClient

func NewClient(opts ClientOptions) (*Client, error)

NewClient returns a Client. It fails with ErrNoKeyring when a verification mode is set without a keyring.

func (*Client) DownloadPackage

func (c *Client) DownloadPackage(ctx context.Context, repo Repo, entry *DBEntry, dir string) (string, error)

DownloadPackage downloads the package described by entry from the servers of repo into dir and returns its path. The file is checked against the size and SHA-256 (or, failing that, MD5) of the entry and, per the verification mode, against its signature: the one the entry carries, else "<file>.sig" from the server. The verification follows the package part of the repository's SigLevel (ClientOptions.PackageSignatures when it has none). A package already in dir that passes the checks is reused. The CacheServers of the repository are tried first, then its Servers, in order; a package that fails a check is discarded and the next server is tried. A cache server that does not have the package is skipped like any other server.

func (*Client) DownloadPackageFile added in v0.4.0

func (c *Client) DownloadPackageFile(ctx context.Context, rawURL, dir string, policy SigPolicy) (string, error)

DownloadPackageFile downloads the package at rawURL into dir, as pacman -U does for a URL, and returns its path. The file takes the last element of the URL's path as its name. Its signature "<url>.sig" is checked under policy: pass Config.RemoteFileSigLevel.Package; an unset policy falls back to ClientOptions.PackageSignatures. A package that fails verification is removed. The package has no database entry to check its size or digest against, so the download is bounded by DefaultMaxPackageBytes only.

func (*Client) FetchDB

func (c *Client) FetchDB(ctx context.Context, repo Repo) (*DBFile, error)

FetchDB downloads the database of repo from the first server that serves it (and, per the database part of the repository's SigLevel, a valid signature for it). CacheServers are not used for databases, and the repository's Usage is not consulted: naming a repository is asking for it explicitly.

func (*Client) Sync

func (c *Client) Sync(ctx context.Context, repos []Repo, dir string) (int, error)

Sync refreshes the databases of repos into dir, up to DefaultSyncConcurrency at a time, as pacman -Sy does: a repository whose Usage does not allow UsageSync is skipped (neither counted nor an error). To refresh one regardless of its Usage, as pacman does for a repository named explicitly, call SyncDB. A repository that fails does not stop the others: it returns how many succeeded and the joined failures (each wrapping its repository name's ErrAllServersFailed or the cause).

func (*Client) SyncDB

func (c *Client) SyncDB(ctx context.Context, repo Repo, dir string) (*DBFile, error)

SyncDB downloads the database of repo into dir as "<repo>.db", with its signature as "<repo>.db.sig"; a stale signature from an earlier sync is removed when the server has none, since it would not match the new database. Both files are replaced atomically.

func (*Client) VerifyPackageFile added in v0.4.0

func (c *Client) VerifyPackageFile(name string, policy SigPolicy) (*gpg.Verified, error)

VerifyPackageFile verifies the package file at name, one the caller names explicitly (pacman -U on a path), against its detached signature in "<name>.sig", under policy: pass Config.LocalFileSigLevel.Package. An unset policy falls back to ClientOptions.PackageSignatures. It returns nil, nil when the policy is Never or the signature is absent and not required.

type ClientOptions

type ClientOptions struct {
	// HTTP fetches databases and signatures, with its retry policy and size
	// caps; packages are downloaded through it too. Nil builds a default client.
	HTTP *httpclient.Client
	// Arch replaces $arch in server URLs; empty selects ArchFromGOARCH of the
	// running system.
	Arch string
	// Keyring holds the public keys signatures are checked against.
	Keyring *gpg.Keyring
	// DBSignatures and PackageSignatures set the verification of databases
	// and of packages of the repositories that carry no SigLevel of their own
	// (Repo.SigLevel zero); a repository's SigLevel overrides them, per kind:
	// its Database part governs the database, its Package part the packages.
	// Anything but VerifyNone needs Keyring; so does a repository whose
	// SigLevel is not Never, which fails with ErrNoKeyring when used.
	DBSignatures      VerifyMode
	PackageSignatures VerifyMode
	// MaxDBBytes bounds a database; zero selects DefaultMaxDBBytes.
	MaxDBBytes int64
	// Progress, when set, receives the progress of package downloads: the
	// file name, the bytes on disk and the expected total (-1 when unknown).
	// It may be called from several goroutines.
	Progress func(name string, done, total int64)
	// Logger receives one debug line per server tried. Nil is silent.
	Logger *slog.Logger
}

ClientOptions configures a Client. The zero value is valid: no verification, the default HTTP client and the architecture of the running system.

type Config

type Config struct {
	// RootDir is the installation root, "/" by default.
	RootDir string
	// DBPath is the database directory, <RootDir>/var/lib/pacman/ by default.
	DBPath string
	// CacheDirs are the package cache directories in the order the file lists
	// them, /var/cache/pacman/pkg/ by default.
	CacheDirs []string
	// HookDirs are the extra hook directories, /etc/pacman.d/hooks/ by default.
	HookDirs []string
	// GPGDir is the GnuPG directory, /etc/pacman.d/gnupg/ by default.
	GPGDir string
	// LogFile is the log file, <RootDir>/var/log/pacman.log by default.
	LogFile string

	// HoldPkg, IgnorePkg, IgnoreGroup, NoUpgrade and NoExtract are the lists of
	// names and shell-style patterns of the options of the same names.
	HoldPkg     []string
	IgnorePkg   []string
	IgnoreGroup []string
	NoUpgrade   []string
	NoExtract   []string

	// Architectures are the Architecture values as written, "auto" included;
	// see Arch and AllowedArchitectures for the resolved ones. Empty when the
	// option is absent.
	Architectures []string

	// XferCommand is the external downloader command line, empty when unset.
	XferCommand string
	// CleanMethod says what a cache clean keeps; KeepInstalled by default.
	CleanMethod CleanMethod

	// SigLevel is the default signature level of repositories, "Required
	// TrustedOnly" unless set.
	SigLevel SigLevel
	// LocalFileSigLevel and RemoteFileSigLevel are the levels for package
	// files named explicitly (pacman -U on a path or on a URL). Each starts
	// from SigLevel, as pacman does; only the Package part applies to files.
	LocalFileSigLevel  SigLevel
	RemoteFileSigLevel SigLevel

	// ParallelDownloads is the number of concurrent download streams, 1 by
	// default.
	ParallelDownloads int
	// DownloadUser is the user downloads switch to, empty when unset.
	DownloadUser string

	// The flag options.
	UseSyslog              bool
	Color                  bool
	CheckSpace             bool
	VerbosePkgLists        bool
	ILoveCandy             bool
	NoProgressBar          bool
	DisableDownloadTimeout bool
	// DisableSandboxFilesystem and DisableSandboxSyscalls are set by their own
	// options and both by DisableSandbox.
	DisableSandboxFilesystem bool
	DisableSandboxSyscalls   bool

	// Repos are the repositories in the order the file lists them, which is
	// the order pacman searches them.
	Repos []Repo
	// Unknown holds the directives the parser does not know, in file order. In
	// strict mode they are an error instead.
	Unknown []Directive
}

Config is a parsed pacman.conf: the [options] values, with libalpm's defaults applied where the file leaves an option out, and the repositories.

Paths are cleaned lexically where pacman resolves them (RootDir, DBPath, GPGDir); symbolic links are not followed, as no file system is consulted.

func ParseConfig

func ParseConfig(r io.Reader, opts ParseOptions) (*Config, error)

ParseConfig parses the text of a pacman.conf. [options] yields the global options and every other section is a repository; "Include" lines are expanded through opts.Include (nil leaves them out). Invalid values (a ParallelDownloads that is not a positive number, an unknown SigLevel, CleanMethod or Usage option) are errors, as in pacman; other unknown directives are kept in Config.Unknown unless opts.Strict.

Example

A pacman.conf is parsed into typed options and repositories.

package main

import (
	"fmt"
	"strings"

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

func main() {
	cfg, err := pacman.ParseConfig(strings.NewReader(`
[options]
HoldPkg = pacman glibc
IgnorePkg = linux*
ParallelDownloads = 5
Color

[core]
SigLevel = Required DatabaseOptional
Server = https://mirror.example/$repo/os/$arch
`), pacman.ParseOptions{})
	if err != nil {
		fmt.Println(err)

		return
	}

	core := cfg.Repos[0]

	fmt.Println(cfg.ParallelDownloads, cfg.Color, cfg.IsHeld("glibc"), cfg.IsIgnored("linux-lts"))
	fmt.Println(core.Name, core.SigLevel)
}
Output:
5 true true true
core PackageRequired PackageTrustedOnly DatabaseOptional DatabaseTrustedOnly

func ParseConfigFS added in v0.4.0

func ParseConfigFS(fsys fs.FS, name string, opts ParseOptions) (*Config, error)

ParseConfigFS parses the pacman.conf named name inside fsys. Includes are read from the same file system unless opts.Include says otherwise: a value such as "/etc/pacman.d/mirrorlist" names "etc/pacman.d/mirrorlist" in fsys, and globs are expanded with fs.Glob. No host path is built in.

Example

ParseConfigFS reads a configuration and everything it includes from any fs.FS, here an in-memory one; ParseConfigFile does the same on disk.

package main

import (
	"fmt"
	"testing/fstest"

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

func main() {
	fsys := fstest.MapFS{
		"etc/pacman.conf":         {Data: []byte("[core]\nInclude = /etc/pacman.d/mirrorlist\n")},
		"etc/pacman.d/mirrorlist": {Data: []byte("Server = https://a.example/$repo/os/$arch\nServer = https://b.example/$repo/os/$arch\n")},
	}

	cfg, err := pacman.ParseConfigFS(fsys, "etc/pacman.conf", pacman.ParseOptions{})
	if err != nil {
		fmt.Println(err)

		return
	}

	for _, s := range cfg.Repos[0].Servers {
		fmt.Println(pacman.ExpandServer(s, "core", pacman.ArchFromGOARCH("amd64")))
	}
}
Output:
https://a.example/core/os/x86_64
https://b.example/core/os/x86_64

func ParseConfigFile

func ParseConfigFile(name string, opts ParseOptions) (*Config, error)

ParseConfigFile reads the pacman.conf at name in the host file system. Include values are paths too (relative ones to the working directory, as in pacman), with globs expanded, unless opts.Include says otherwise. The path is the caller's: no location is built in.

func (*Config) AllowedArchitectures added in v0.4.0

func (c *Config) AllowedArchitectures(goarch string) []string

AllowedArchitectures returns the Architecture values in file order with "auto" replaced by ArchFromGOARCH(goarch), as pacman does (a value listed twice stays twice). goarch is a GOARCH value such as runtime.GOARCH, or an Arch Linux architecture name (for instance the output of "uname -m"), which is used as is. It is nil when the option is absent: pacman then makes no architecture check.

Example

Architecture = auto is replaced by the running machine's architecture.

package main

import (
	"fmt"
	"strings"

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

func main() {
	cfg, _ := pacman.ParseConfig(strings.NewReader("[options]\nArchitecture = auto x86_64_v3\n"), pacman.ParseOptions{})

	fmt.Println(cfg.AllowedArchitectures("amd64"))
	fmt.Println(cfg.Arch("arm64"))
}
Output:
[x86_64 x86_64_v3]
aarch64

func (*Config) ApplyUsage added in v0.4.0

func (c *Config) ApplyUsage(x *Index)

ApplyUsage sets the Usage of every repository of the configuration on x, so that resolution, upgrades and searches skip the repositories whose Usage does not allow them.

func (*Config) Arch added in v0.4.0

func (c *Config) Arch(goarch string) string

Arch returns the architecture $arch stands for: the first Architecture value, with "auto" resolved as AllowedArchitectures does. It is empty when the option is absent.

func (*Config) IsHeld added in v0.4.0

func (c *Config) IsHeld(name string) bool

IsHeld reports whether name matches a HoldPkg entry, a package pacman asks confirmation for before removing. Entries are shell-style patterns, matched as fnmatch(3) does.

func (*Config) IsIgnored added in v0.4.0

func (c *Config) IsIgnored(name string, groups ...string) bool

IsIgnored reports whether pacman skips upgrades of a package: its name matches an IgnorePkg entry, or one of its groups matches an IgnoreGroup entry. Entries are shell-style patterns, matched as fnmatch(3) does.

func (*Config) Repo added in v0.4.0

func (c *Config) Repo(name string) (Repo, bool)

Repo returns the repository called name.

func (*Config) ReposFor added in v0.4.0

func (c *Config) ReposFor(use Usage) []Repo

ReposFor returns the repositories whose Usage allows every use in use, in configuration order. ReposFor(UsageSync) is what a database refresh (see Client.Sync) works on.

Example

A repository's Usage tells which operations may use it.

package main

import (
	"fmt"
	"strings"

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

func main() {
	cfg, _ := pacman.ParseConfig(strings.NewReader(`
[core]
Server = https://m.example/$repo
[testing]
Usage = Sync Search
Server = https://m.example/$repo
`), pacman.ParseOptions{})

	for _, r := range cfg.ReposFor(pacman.UsageInstall) {
		fmt.Println(r.Name)
	}
}
Output:
core

func (*Config) ResolveOptions added in v0.4.0

func (c *Config) ResolveOptions() ResolveOptions

ResolveOptions returns ResolveOptions carrying the IgnorePkg and IgnoreGroup of the configuration.

type ConflictError added in v0.4.0

type ConflictError struct {
	// Package is the package to install whose (or whose counterpart's)
	// conflict is reported.
	Package string
	// With is the package it conflicts with.
	With string
	// Installed reports that With is installed, not part of the transaction.
	Installed bool
	// Expr is the conflict expression that matched, such as "vlib<2".
	Expr string
}

ConflictError names the two packages of a conflict. It matches ErrConflict.

Example

A conflict with an installed package is an error that names both.

package main

import (
	"fmt"

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

func resolveExampleIndex() *pacman.Index {
	x := &pacman.Index{}

	_ = x.Add("core", []pacman.DBEntry{
		{Name: "glibc", Version: "2.40-1", Groups: []string{"base"}},
		{Name: "bash", Version: "5.2-1", Depends: []string{"glibc"}, Provides: []string{"sh"}, Groups: []string{"base"}},
		{Name: "app", Version: "2-1", Depends: []string{"sh", "glibc>=2.40"}, OptDepends: []string{"nice: prettier output"}, Conflicts: []string{"app-git"}},
		{Name: "nice", Version: "1-1"},
		{Name: "newname", Version: "1-1", Replaces: []string{"oldname"}},
	})

	return x
}

func main() {
	x := resolveExampleIndex()

	_, err := x.Install([]string{"app"}, pacman.ResolveOptions{
		Local: []*pacman.InstalledPackage{{Name: "app-git", Version: "1-1"}, {Name: "glibc", Version: "2.40-1"}},
	})
	fmt.Println(err)

}
Output:
pacman: conflicting packages: app and app-git (installed) conflict (app-git)

func (*ConflictError) Error added in v0.4.0

func (e *ConflictError) Error() string

Error implements error.

func (*ConflictError) Unwrap added in v0.4.0

func (e *ConflictError) Unwrap() error

Unwrap returns ErrConflict.

type DBEntry

type DBEntry struct {
	Filename    string
	Name        string
	Base        string
	Version     string
	Description string
	Groups      []string
	CSize       int64
	ISize       int64
	MD5         string
	SHA256      string
	// PGPSig is the base64 of the binary detached signature of the package file,
	// empty for an unsigned package.
	PGPSig       string
	URL          string
	Licenses     []string
	Arch         string
	BuildDate    int64
	Packager     string
	Replaces     []string
	Conflicts    []string
	Provides     []string
	Depends      []string
	OptDepends   []string
	MakeDepends  []string
	CheckDepends []string
	// Files is the file list written to the "files" entry of the files database.
	Files []string
}

DBEntry is one package of a repository database: what repo-add writes into the "desc" (and, for the files database, "files") entry of a package.

func NewDBEntry

func NewDBEntry(filename string, pkgFile io.ReadSeeker, sig []byte) (*DBEntry, error)

NewDBEntry builds the database entry of a package file read from r: the file's .PKGINFO and file list, its compressed size and its sums, as repo-add records them. sig, when not empty, is the binary detached signature of the file. Entries are meant for WriteDB.

func ReadDB

func ReadDB(r io.Reader) ([]DBEntry, error)

ReadDB reads a repository database (the "db" or "files" tarball, gzip, xz or zstd compressed) into its entries: the fields of each package's "desc" (and legacy "depends") member and, when the archive has them, its "files" member.

The database is untrusted. An entry whose identity is unusable (no valid name, version or package file name, or a malformed number or list) is left out; a database that is not a compressed tar, or exceeds a limit, is an error. Fields the database does not carry stay empty.

func (*DBEntry) Desc

func (e *DBEntry) Desc() []byte

Desc renders the "desc" entry exactly as repo-add writes it: one "%FIELD%" block per non-empty field, a blank line after each.

func (*DBEntry) DirName

func (e *DBEntry) DirName() string

DirName is the directory the package has in the database tarball.

func (*DBEntry) FilesEntry

func (e *DBEntry) FilesEntry() []byte

FilesEntry renders the "files" entry of the files database.

type DBFile

type DBFile struct {
	// Repo is the repository name.
	Repo string
	// URL is the address of the database that was fetched.
	URL string
	// Data is the compressed database as served.
	Data []byte
	// Sig is the binary detached signature, nil when the server has none.
	Sig []byte
	// Verified describes the signer when the signature was verified.
	Verified *gpg.Verified
}

DBFile is a downloaded sync database.

func (*DBFile) Entries

func (d *DBFile) Entries() ([]DBEntry, error)

Entries parses the database.

type Dependency

type Dependency struct {
	Name string
	// Op is "", "=", "<", "<=", ">" or ">=".
	Op string
	// Version is the compared version; empty exactly when Op is empty.
	Version string
}

Dependency is a parsed dependency, provision or conflict expression: "name", or "name" followed by a comparison operator and a version.

func ParseDependency

func ParseDependency(s string) (Dependency, error)

ParseDependency parses "name[(<=|>=|=|<|>)version]".

func (Dependency) Allows

func (d Dependency) Allows(version string) bool

Allows reports whether version satisfies the constraint of d. A dependency without constraint allows every version.

func (Dependency) String

func (d Dependency) String() string

String returns the expression ParseDependency accepts.

type DiffKind added in v0.4.0

type DiffKind int

DiffKind says how a path differs from the .MTREE.

const (
	// DiffMismatch means the path exists and one keyword differs.
	DiffMismatch DiffKind = iota
	// DiffMissing means the .MTREE lists a path that is not there.
	DiffMissing
	// DiffExtra means the archive holds a path the .MTREE does not list.
	DiffExtra
)

The kinds of difference.

func (DiffKind) String added in v0.4.0

func (k DiffKind) String() string

type Directive added in v0.4.0

type Directive struct {
	// Section is the section the line appeared in.
	Section string
	// Key is the directive name; the whole line when it has no "=".
	Key string
	// Value is the text after "=", empty for a line without one.
	Value string
}

Directive is a configuration line the parser does not know.

type Entry added in v0.4.0

type Entry struct {
	// Path is the slash-separated path below the root of the package, without
	// a leading "./" or a trailing "/". The metadata files are listed as
	// ".PKGINFO", ".MTREE" and so on.
	Path string
	// Mode holds the permission bits, setuid, setgid and sticky, and the type
	// bit: fs.ModeDir, fs.ModeSymlink, fs.ModeNamedPipe, fs.ModeDevice or
	// fs.ModeDevice|fs.ModeCharDevice. A regular file and a hard link have no
	// type bit.
	Mode fs.FileMode
	// UID and GID are the numeric owner; Uname and Gname the names, which may
	// be empty.
	UID, GID     int
	Uname, Gname string
	// Size is the length of the content in the archive: zero for everything but
	// a regular file that carries data (a hard link member has none).
	Size    int64
	ModTime time.Time
	// Linkname is the target of a symbolic link.
	Linkname string
	// Hardlink is the path of the member a hard link member links to; empty for
	// every other kind.
	Hardlink string
	// DevMajor and DevMinor are the device number of a device node.
	DevMajor, DevMinor int64
	// Xattrs are the extended attributes stored in the PAX records, such as
	// "security.capability".
	Xattrs map[string][]byte
}

Entry is one member of a package archive: its path, kind and the metadata a file system keeps.

func (*Entry) IsDir added in v0.4.0

func (e *Entry) IsDir() bool

IsDir reports whether the entry is a directory.

func (*Entry) IsMetadata added in v0.4.0

func (e *Entry) IsMetadata() bool

IsMetadata reports whether the entry is one of the dot files that describe the package and are not part of its payload.

func (*Entry) IsRegular added in v0.4.0

func (e *Entry) IsRegular() bool

IsRegular reports whether the entry is a regular file that carries content; a hard link member is not.

type ExtractOptions added in v0.4.0

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
	// Umask clears the given bits of every file and directory mode, as a unix
	// mask over the permission bits (0777) and the special bits: 07000 drops
	// setuid, setgid and sticky. The default applies the modes of the package
	// unchanged, as pacman does.
	Umask uint32
	// Chown applies the numeric owner of each entry. It needs the privilege to
	// chown; a failure is an error.
	Chown bool
	// SpecialFiles allows creating named pipes and device nodes. They are
	// skipped, with a logged warning, unless set. Device nodes need privileges.
	SpecialFiles bool
	// Xattrs applies the extended attributes of each entry, such as
	// security.capability for file capabilities. Without it they are dropped
	// with a logged warning. Only Linux supports them; elsewhere, setting them
	// fails.
	Xattrs bool
	// Metadata also writes the dot files that describe the package (.PKGINFO,
	// .BUILDINFO, .MTREE, .INSTALL, .CHANGELOG), which pacman does not
	// extract.
	Metadata bool
	// Verify checks what was written against the .MTREE of the package, as
	// VerifyPackage does, and fails with a *MtreeError or ErrNoMtree after the
	// extraction. The files stay in place. Owners and modes are compared with
	// what the package says, not with what the extraction could apply, so
	// IgnoreOwner is usually wanted when Chown is off.
	Verify bool
	// VerifyOptions tunes Verify.
	VerifyOptions VerifyOptions
	// Logger receives a warning for everything that is skipped. Nil discards.
	Logger *slog.Logger
}

ExtractOptions tunes Extract. The zero value applies the defaults: the modes and modification times of the package, the owner of the extracting user, no special files and no extended attributes.

type File

type File struct {
	// Path is the slash-separated path below the root of the package, such as
	// "usr/bin/tool". A leading "./" and a trailing "/" are accepted. The first
	// element must not start with a dot (see ErrReservedName).
	Path string
	// Mode holds the permission bits, setuid, setgid and sticky, plus the type
	// bit: fs.ModeDir, fs.ModeSymlink, fs.ModeNamedPipe, fs.ModeDevice (block
	// device) or fs.ModeDevice|fs.ModeCharDevice (character device). A regular
	// file and a hard link have no type bit.
	Mode fs.FileMode
	// UID and GID are the numeric owner of the entry. Uname and Gname are the
	// owner names; when empty and the number is 0 they are "root".
	UID, GID     int
	Uname, Gname string
	// DevMajor and DevMinor are the device number of a device node.
	DevMajor, DevMinor int64
	// Hardlink, when not empty, makes the entry a hard link to the regular file
	// of the package with that path. The entry takes the type, content, mode,
	// owner, time and extended attributes of that file, so Mode, Data, Open,
	// Size, UID, GID, ModTime and Xattrs are ignored. The link target must be
	// a regular file entry of its own, not another hard link.
	Hardlink string
	// Xattrs are extended attributes, such as "security.capability" for file
	// capabilities, stored as PAX records the way bsdtar (and so makepkg)
	// writes them. They need the PAX tar format.
	Xattrs map[string][]byte
	// ModTime is the modification time, kept to the second. The zero time means
	// the build date of the package.
	ModTime time.Time
	// Linkname is the target of a symbolic link.
	Linkname string
	// Data is the content of a regular file. When Open is set, Data is ignored.
	Data []byte
	// Open returns the content of a regular file, for content too large to hold
	// in memory. It is called twice (once to checksum for the .MTREE, once to
	// write) and must return the same Size bytes both times.
	Open func() (io.ReadCloser, error)
	// Size is the length of the content Open returns.
	Size int64
}

File is one entry of the payload of a package: a regular file, a directory, a symbolic link, a hard link, a named pipe or a device node.

func ScanDir

func ScanDir(root string) ([]File, error)

ScanDir lists the files below root as payload Files, in directory order. The top-level entries named like the generated metadata files (.PKGINFO, .BUILDINFO, .MTREE, .INSTALL, .CHANGELOG) are skipped, so a staging directory that was used before can be scanned again. Contents are opened lazily and never followed outside root.

Files that share an inode become hard links, named pipes and device nodes are listed as such, and every file is owned by root:root; ScanDirWith keeps the owners and the extended attributes of the tree instead.

func ScanDirWith added in v0.4.0

func ScanDirWith(root string, opts ScanOptions) ([]File, error)

ScanDirWith is ScanDir with options.

type FileKind

type FileKind int

FileKind says what a file name in a repository directory names.

const (
	FileInvalid FileKind = iota
	FilePackage
	FilePackageSig
	FileDatabase
	FileDatabaseSig
)

The kinds of file a repository directory holds.

func ClassifyFile

func ClassifyFile(filename string) (FileKind, string)

ClassifyFile names the kind of file a URL file name is. For databases it also returns the generated document it maps to ("db.tar.gz" or "files.tar.gz").

type IncludeFile added in v0.4.0

type IncludeFile struct {
	// Name appears in error messages.
	Name string
	// Open returns the file's content; the parser closes it.
	Open func() (io.ReadCloser, error)
}

IncludeFile is a file an include resolves to. Open is called once, when the parser reaches the file, so a pattern matching many files opens them one at a time.

func IncludeText added in v0.4.0

func IncludeText(name, text string) IncludeFile

IncludeText returns an IncludeFile that holds text, for resolvers that do not read files.

func OSIncludeResolver added in v0.4.0

func OSIncludeResolver(include string) ([]IncludeFile, error)

OSIncludeResolver resolves an include to host files: the value is a path, or a glob pattern that expands to the matching files in sorted order. A value that matches no file fails with an error wrapping fs.ErrNotExist, as in pacman.

type IncludeResolver

type IncludeResolver func(include string) ([]IncludeFile, error)

IncludeResolver returns the files an "Include = value" line names, in the order pacman reads them (glob matches sorted). A value that names nothing is an error, as in pacman. Included files may hold repository sections, options or just servers, and are parsed as if their lines stood where the Include does.

func FSIncludeResolver added in v0.4.0

func FSIncludeResolver(fsys fs.FS) IncludeResolver

FSIncludeResolver returns an IncludeResolver reading from fsys. A leading "/" of the include value is dropped, and a value that would climb out of fsys is an ErrInvalidConfig.

type Index

type Index struct {
	// contains filtered or unexported fields
}

Index is a set of sync databases that can be searched and whose dependencies can be resolved. The zero value is an empty index. Repositories are searched in the order they were added; an Index is not safe for concurrent modification, but is for concurrent reads.

func (*Index) Add

func (x *Index) Add(repo string, entries []DBEntry) error

Add appends the entries of repo to the index.

func (*Index) AddDatabase

func (x *Index) AddDatabase(repo string, r io.Reader) error

AddDatabase reads a sync database (as ReadDB does) and adds it as repo.

func (*Index) Group added in v0.4.0

func (x *Index) Group(name string) []*IndexedPackage

Group returns the members of the group called name, as "pacman -S name" installs them: a package of the first repository that has it, its newest version, whatever the other repositories hold. Repositories whose Usage has neither Install nor Upgrade are left out. The members are ordered by repository, then by name.

Example

A group name stands for its members.

package main

import (
	"fmt"

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

func resolveExampleIndex() *pacman.Index {
	x := &pacman.Index{}

	_ = x.Add("core", []pacman.DBEntry{
		{Name: "glibc", Version: "2.40-1", Groups: []string{"base"}},
		{Name: "bash", Version: "5.2-1", Depends: []string{"glibc"}, Provides: []string{"sh"}, Groups: []string{"base"}},
		{Name: "app", Version: "2-1", Depends: []string{"sh", "glibc>=2.40"}, OptDepends: []string{"nice: prettier output"}, Conflicts: []string{"app-git"}},
		{Name: "nice", Version: "1-1"},
		{Name: "newname", Version: "1-1", Replaces: []string{"oldname"}},
	})

	return x
}

func main() {
	for _, p := range resolveExampleIndex().Group("base") {
		fmt.Println(p.Name)
	}

}
Output:
bash
glibc

func (*Index) Install added in v0.4.0

func (x *Index) Install(roots []string, opts ResolveOptions) (*Transaction, error)

Install plans installing roots, as "pacman -S" does: each root is a dependency expression ("foo", "bar>=2"; a provider of the name when no package has it) or the name of a group, and is installed with what it needs that the system, ResolveOptions.Local or ResolveOptions.Installed, does not satisfy. A package of the transaction takes the place of an installed one of the same name.

The plan is checked as libalpm checks it. Two packages of the transaction that conflict are an error, except that when one provides the name of the other the provided one is left out. A package that conflicts with an installed one is an error. A package that stops satisfying a dependency of an installed package is an error. The errors wrap ErrConflict, ErrBrokenDependency and ErrUnresolved.

Example

Install resolves what pacman -S would install, with libalpm's choices.

package main

import (
	"fmt"

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

func resolveExampleIndex() *pacman.Index {
	x := &pacman.Index{}

	_ = x.Add("core", []pacman.DBEntry{
		{Name: "glibc", Version: "2.40-1", Groups: []string{"base"}},
		{Name: "bash", Version: "5.2-1", Depends: []string{"glibc"}, Provides: []string{"sh"}, Groups: []string{"base"}},
		{Name: "app", Version: "2-1", Depends: []string{"sh", "glibc>=2.40"}, OptDepends: []string{"nice: prettier output"}, Conflicts: []string{"app-git"}},
		{Name: "nice", Version: "1-1"},
		{Name: "newname", Version: "1-1", Replaces: []string{"oldname"}},
	})

	return x
}

func main() {
	x := resolveExampleIndex()

	tx, err := x.Install([]string{"app"}, pacman.ResolveOptions{
		Local: []*pacman.InstalledPackage{{Name: "glibc", Version: "2.39-1"}},
	})
	if err != nil {
		fmt.Println(err)

		return
	}

	for _, p := range tx.Packages {
		fmt.Println(p.Name, p.Version)
	}

	for _, u := range tx.Upgrades {
		fmt.Println("upgrades", u.Installed.Name, u.Installed.Version, "->", u.Package.Version)
	}

}
Output:
glibc 2.40-1
bash 5.2-1
app 2-1
upgrades glibc 2.39-1 -> 2.40-1

func (*Index) Len

func (x *Index) Len() int

Len returns the number of packages.

func (*Index) Lookup

func (x *Index) Lookup(name string) (*IndexedPackage, bool)

Lookup returns the package called name: of the first repository that has it, its newest version.

func (*Index) OptionalDeps added in v0.4.0

func (x *Index) OptionalDeps(p *IndexedPackage) ([]OptionalDep, error)

OptionalDeps returns the optional dependencies of p with, for each, the package of the index that would satisfy it (nil when none does).

Example

Optional dependencies are listed, not installed.

package main

import (
	"fmt"

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

func resolveExampleIndex() *pacman.Index {
	x := &pacman.Index{}

	_ = x.Add("core", []pacman.DBEntry{
		{Name: "glibc", Version: "2.40-1", Groups: []string{"base"}},
		{Name: "bash", Version: "5.2-1", Depends: []string{"glibc"}, Provides: []string{"sh"}, Groups: []string{"base"}},
		{Name: "app", Version: "2-1", Depends: []string{"sh", "glibc>=2.40"}, OptDepends: []string{"nice: prettier output"}, Conflicts: []string{"app-git"}},
		{Name: "nice", Version: "1-1"},
		{Name: "newname", Version: "1-1", Replaces: []string{"oldname"}},
	})

	return x
}

func main() {
	x := resolveExampleIndex()
	app, _ := x.Lookup("app")

	opts, _ := x.OptionalDeps(app)
	for _, o := range opts {
		fmt.Printf("%s (%s) from %s\n", o.Name, o.Description, o.Package.Repo)
	}

}
Output:
nice (prettier output) from core

func (*Index) Packages

func (x *Index) Packages() []*IndexedPackage

Packages returns every package in the order it was added.

func (*Index) Providers

func (x *Index) Providers(dep Dependency) []*IndexedPackage

Providers returns the packages that satisfy dep other than by their own name: those with a matching provision.

func (*Index) Resolve

func (x *Index) Resolve(dep Dependency) (*IndexedPackage, error)

Resolve returns the package that satisfies dep, as libalpm picks one: a package of that name with an acceptable version wins (the newest one of the first repository that has one); otherwise a provider does, the first one in repository order and then name order. Repositories whose Usage does not allow UsageInstall are not searched. It fails with ErrUnresolved when nothing satisfies dep.

func (*Index) ResolveDeps

func (x *Index) ResolveDeps(roots []string, opts ResolveOptions) ([]*IndexedPackage, error)

ResolveDeps returns the packages needed to install roots (dependency expressions such as "foo" or "bar>=2", or a group name), the roots included, with every package after the ones it depends on. A dependency cycle is tolerated: the package that closes it is placed before the one that needed it. A dependency nothing satisfies fails with an error wrapping ErrUnresolved that names the package that asked for it. It is Index.Install without the classification of the result.

func (*Index) Search added in v0.4.0

func (x *Index) Search(query string) []*IndexedPackage

Search returns the packages whose name or description contains query, ignoring case, as "pacman -Ss" lists them: only repositories that allow UsageSearch are searched, in the order they were added. An empty query matches every package.

func (*Index) SetUsage added in v0.4.0

func (x *Index) SetUsage(repo string, u Usage)

SetUsage sets what the repository repo may be used for. A repository never set is usable for everything, as one without a Usage line in pacman.conf.

func (*Index) Sysupgrade added in v0.4.0

func (x *Index) Sysupgrade(installed []*InstalledPackage, opts ResolveOptions) (*Transaction, error)

Sysupgrade plans a system upgrade, as "pacman -Su" does, for the installed packages. Every installed package for which the first repository that has it (among those allowing UsageUpgrade) holds a newer version is upgraded. A sync package whose "replaces" entry matches an installed package of another name replaces it: it is installed and the installed one removed. Packages covered by ResolveOptions.IgnorePkg or ResolveOptions.IgnoreGroup are neither upgraded nor used as replacements, and are not picked to satisfy a dependency. What the upgraded and replacing packages need that the system lacks is installed too, and the plan is checked for conflicts and broken dependencies as Index.Install does. The errors wrap ErrUnresolved, ErrConflict and ErrBrokenDependency. ResolveOptions.Local is ignored: the installed argument is the system.

Example

Sysupgrade upgrades what has a newer version and applies replaces.

package main

import (
	"fmt"

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

func resolveExampleIndex() *pacman.Index {
	x := &pacman.Index{}

	_ = x.Add("core", []pacman.DBEntry{
		{Name: "glibc", Version: "2.40-1", Groups: []string{"base"}},
		{Name: "bash", Version: "5.2-1", Depends: []string{"glibc"}, Provides: []string{"sh"}, Groups: []string{"base"}},
		{Name: "app", Version: "2-1", Depends: []string{"sh", "glibc>=2.40"}, OptDepends: []string{"nice: prettier output"}, Conflicts: []string{"app-git"}},
		{Name: "nice", Version: "1-1"},
		{Name: "newname", Version: "1-1", Replaces: []string{"oldname"}},
	})

	return x
}

func main() {
	x := resolveExampleIndex()

	tx, err := x.Sysupgrade([]*pacman.InstalledPackage{
		{Name: "glibc", Version: "2.39-1"},
		{Name: "oldname", Version: "1-1"},
	}, pacman.ResolveOptions{IgnorePkg: []string{"nothing"}})
	if err != nil {
		fmt.Println(err)

		return
	}

	for _, u := range tx.Upgrades {
		fmt.Println("upgrade", u.Package.Name, u.Package.Version)
	}

	for _, r := range tx.Replacements {
		fmt.Println(r.Package.Name, "replaces", r.Installed.Name)
	}

	for _, r := range tx.Removals {
		fmt.Println("remove", r.Name)
	}

}
Output:
upgrade glibc 2.40-1
newname replaces oldname
remove oldname

type IndexedPackage

type IndexedPackage struct {
	Repo string
	DBEntry
}

IndexedPackage is a package of an Index and the repository it comes from.

func (*IndexedPackage) OptionalDeps added in v0.4.0

func (p *IndexedPackage) OptionalDeps() ([]OptionalDep, error)

OptionalDeps parses the optional dependencies of the package, in order. They are never installed unless ResolveOptions.WithOptional says so.

func (*IndexedPackage) Satisfies

func (p *IndexedPackage) Satisfies(dep Dependency) bool

Satisfies reports whether the package fulfils dep by its own name and version, or by one of its provisions. A provision without version fulfils only a dependency without constraint, as in libalpm.

type InstallScript added in v0.4.0

type InstallScript struct {
	// Raw is the whole text of the file.
	Raw []byte
	// Hooks lists the hook functions the file defines, in the order of
	// pacman's run (pre_install first), once each.
	Hooks []string
}

InstallScript is the .INSTALL file of a package, as read back.

func ParseInstall added in v0.4.0

func ParseInstall(r io.Reader) (*InstallScript, error)

ParseInstall reads the text of a .INSTALL file and finds which of the six hook functions it defines. The text is not run or otherwise interpreted: a definition is recognized by the line that opens it, so a function defined inside an "eval" or a here-document is not seen. A file over MaxInstallBytes fails with ErrMetadataTooLarge.

func (*InstallScript) Has added in v0.4.0

func (s *InstallScript) Has(hook string) bool

Has reports whether the script defines the hook (HookPostInstall, ...).

type InstalledPackage added in v0.3.1

type InstalledPackage struct {
	// Dir is the name of the package's directory, "<name>-<version>" in a
	// database pacman wrote. The package's name is Name, not a part of Dir.
	Dir         string
	Name        string
	Base        string
	Version     string
	Description string
	URL         string
	Arch        string
	Packager    string
	// BuildDate and InstallDate are Unix seconds, zero when absent.
	BuildDate   int64
	InstallDate int64
	// Size is the installed size in bytes.
	Size   int64
	Reason Reason

	Groups     []string
	Licenses   []string
	Validation []string
	Replaces   []string
	Conflicts  []string
	Provides   []string
	Depends    []string
	OptDepends []string
	// XData holds the "%XDATA%" lines, "key=value" ("pkgtype=pkg").
	XData []string

	// Files are the "%FILES%" of the package, relative to the root of the
	// system. A directory has a trailing slash: "usr/bin/".
	Files []string
	// Backup are the "%BACKUP%" entries of the files member.
	Backup []BackupFile
}

InstalledPackage is an entry of the local database: the desc and files members of one package directory.

type LocalDB added in v0.3.1

type LocalDB struct {
	// contains filtered or unexported fields
}

LocalDB is the pacman local database: the directory /var/lib/pacman/local. It is read-only and safe for concurrent use: every call reads the directory again.

Example

Read the packages a pacman system has installed. On a host, FindLocalDB("/") and OpenLocalDB give the real database.

package main

import (
	"context"
	"fmt"
	"log"
	"testing/fstest"

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

func main() {
	fsys := fstest.MapFS{
		"ALPM_DB_VERSION":   {Data: []byte("9\n")},
		"acl-2.4.0-1/desc":  {Data: []byte("%NAME%\nacl\n\n%VERSION%\n2.4.0-1\n\n%REASON%\n1\n\n%PROVIDES%\nlibacl.so=1-64\n\n")},
		"acl-2.4.0-1/files": {Data: []byte("%FILES%\nusr/\nusr/bin/\nusr/bin/chacl\n")},
	}

	db := pacman.NewLocalDB(fsys, pacman.LocalDBOptions{})

	for pkg, err := range db.Packages(context.Background()) {
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println(pkg.Name, pkg.Version, pkg.Reason == pacman.ReasonDependency, pkg.Files)
	}

	provides, _ := db.InstalledProvides(context.Background())
	fmt.Println(provides)
}
Output:
acl 2.4.0-1 true [usr/ usr/bin/ usr/bin/chacl]
[acl libacl.so]

func NewLocalDB added in v0.3.1

func NewLocalDB(fsys fs.FS, opts LocalDBOptions) *LocalDB

NewLocalDB reads the local database that fsys holds at its top level: the package directories and ALPM_DB_VERSION. Close does nothing.

func OpenLocalDB added in v0.3.1

func OpenLocalDB(dir string, opts LocalDBOptions) (*LocalDB, error)

OpenLocalDB opens the local database in dir. The directory is only read and not locked, so pacman can run at the same time; each call reads it as of that moment. Links inside the database that point out of dir are not followed.

func (*LocalDB) Close added in v0.3.1

func (db *LocalDB) Close() error

Close releases the directory of a database opened with OpenLocalDB.

func (*LocalDB) InstalledNames added in v0.3.1

func (db *LocalDB) InstalledNames(ctx context.Context) ([]string, error)

InstalledNames returns the names of the installed packages, sorted and without duplicates. It does not read the files members.

func (*LocalDB) InstalledProvides added in v0.3.1

func (db *LocalDB) InstalledProvides(ctx context.Context) ([]string, error)

InstalledProvides returns the names the installed packages answer to: their own and what they provide, without version constraints ("libacl.so=1-64" gives "libacl.so"), sorted and without duplicates. It does not read the files members.

func (*LocalDB) List added in v0.3.1

func (db *LocalDB) List(ctx context.Context) ([]*InstalledPackage, error)

List returns every installed package: LocalDB.Packages collected into a slice.

func (*LocalDB) Mtree added in v0.4.0

func (db *LocalDB) Mtree(pkg *InstalledPackage) (*Mtree, error)

Mtree reads and parses the mtree member of an installed package: the .MTREE of the package it came from, which pacman copies into the local database. It returns ErrNoLocalMtree when there is none.

func (*LocalDB) Packages added in v0.3.1

func (db *LocalDB) Packages(ctx context.Context) iter.Seq2[*InstalledPackage, error]

Packages iterates over the installed packages, in the order of their directory names. A package whose directory has no valid desc, whose name or version is not valid, whose desc or files member is over its limit or has a malformed value is skipped and reported at debug level to LocalDBOptions.Logger. The name of a package is the %NAME% of its desc, whatever its directory is called. The iteration ends with an error when the directory is over its limit, cannot be read, has a version this package does not read, or when ctx is done; the error is the last pair it yields. Stopping early releases everything.

func (*LocalDB) VerifyInstalled added in v0.4.0

func (db *LocalDB) VerifyInstalled(pkg *InstalledPackage, root fs.FS, opts VerifyOptions) error

VerifyInstalled checks the files of an installed package against its mtree, like pacman -Qkk: type, mode, owner, size, time, link target and digests. root is the root of the system the package is installed in; give it an fs.FS that implements fs.ReadLinkFS and stays inside the root, such as os.OpenRoot(dir).FS(). The backup files of the package (pkg.Backup) are exempt from the size, time and digest checks, because the user edits them. It returns nil when everything matches, ErrNoLocalMtree when the package has no mtree, and otherwise a *MtreeError.

type LocalDBOptions added in v0.3.1

type LocalDBOptions struct {
	// Logger receives debug messages about skipped packages. Optional: nil
	// discards them.
	Logger *slog.Logger
	// MaxPackages bounds the entries of the database directory; one with more
	// fails with [ErrLocalDBTooLarge]. Zero selects [DefaultMaxLocalPackages].
	MaxPackages int
	// MaxFiles bounds the file records of one package; a package with more is
	// skipped. Zero selects [DefaultMaxLocalFiles].
	MaxFiles int
	// SkipFiles leaves the files members unread: the packages come without
	// Files and Backup.
	SkipFiles bool
}

LocalDBOptions configures OpenLocalDB and NewLocalDB. The zero value is usable.

type Metadata added in v0.4.0

type Metadata struct {
	// Info is the .PKGINFO.
	Info *PkgInfo
	// BuildInfo is the .BUILDINFO, nil when the package has none (a package
	// built before makepkg 5.1).
	BuildInfo *BuildInfo
	// Install is the .INSTALL, nil when the package has none.
	Install *InstallScript
	// Changelog is the .CHANGELOG, nil when the package has none.
	Changelog []byte
	// Mtree is the .MTREE, nil when the package has none.
	Mtree *Mtree
}

Metadata is everything a package says about itself outside its payload.

func ReadMetadata added in v0.4.0

func ReadMetadata(r io.Reader) (*Metadata, error)

ReadMetadata reads the metadata files of a package: .PKGINFO, .BUILDINFO (format 1 or 2), .INSTALL, .CHANGELOG and .MTREE. It reads the whole archive, because the format does not fix the position of the metadata members, and ignores the payload. A package without .PKGINFO fails with ErrNoPkgInfo.

Example

ReadMetadata returns the metadata files of a package: .PKGINFO, .BUILDINFO, .INSTALL, .CHANGELOG and the parsed .MTREE.

package main

import (
	"bytes"
	"fmt"
	"io/fs"
	"time"

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

func examplePackage() []byte {
	built := time.Unix(1700000000, 0)

	spec := &pacman.Spec{
		Info: pacman.PkgInfo{Name: "shapes", Version: "1.0-1", Description: "Some shapes", Arch: "any", BuildDate: 1700000000},
		Scriptlets: &pacman.Scriptlets{
			PostInstall: "echo installed",
		},
		Files: []pacman.File{
			{Path: "usr/bin/shape", Mode: 0o755, ModTime: built, Data: []byte("#!/bin/sh\n")},
			{Path: "usr/bin/shape-hard", Hardlink: "usr/bin/shape", ModTime: built},
			{Path: "usr/bin/shape-link", Mode: fs.ModeSymlink | 0o777, Linkname: "shape", ModTime: built},
			{Path: "usr/share/shapes/data", Mode: 0o644, UID: 1234, GID: 5678, ModTime: built, Data: []byte("data\n")},
		},
	}

	var buf bytes.Buffer
	if err := spec.Write(&buf, pacman.WriteOptions{MtreeMD5: true}); err != nil {
		panic(err)
	}

	return buf.Bytes()
}

func main() {
	md, err := pacman.ReadMetadata(bytes.NewReader(examplePackage()))
	if err != nil {
		fmt.Println(err)

		return
	}

	data, _ := md.Mtree.Lookup("usr/share/shapes/data")

	fmt.Println(md.Info.Name, md.Info.Version)
	fmt.Println("post_install:", md.Install.Has(pacman.HookPostInstall), "pre_remove:", md.Install.Has(pacman.HookPreRemove))
	fmt.Println(len(md.Mtree.Entries), "entries; data is", data.Size, "bytes owned by", data.UID, data.GID)
}
Output:
shapes 1.0-1
post_install: true pre_remove: false
10 entries; data is 5 bytes owned by 1234 5678

type Mtree added in v0.4.0

type Mtree struct {
	Entries []MtreeEntry
	// contains filtered or unexported fields
}

Mtree is a parsed .MTREE.

func ParseMtree added in v0.4.0

func ParseMtree(r io.Reader) (*Mtree, error)

ParseMtree parses an .MTREE, gzip-compressed as in a package and in the local database, or plain text. Both the flat layout libarchive writes (a full path on every line) and the nested one of mtree(8) (directories entered by name and left with "..") are read, with "/set" and "/unset" and continuation lines.

Example

ParseMtree reads an .MTREE, applying /set and /unset.

package main

import (
	"fmt"
	"strings"

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

func main() {
	mt, err := pacman.ParseMtree(strings.NewReader(`#mtree
/set type=file uid=0 gid=0 mode=644
./usr type=dir mode=755
./usr/bin type=dir mode=755
./usr/bin/tool mode=755 size=10 time=1700000000.0
`))
	if err != nil {
		fmt.Println(err)

		return
	}

	tool, _ := mt.Lookup("usr/bin/tool")
	fmt.Println(tool.Type, tool.FileMode(), tool.Size, tool.Time.Unix())
}
Output:
file -rwxr-xr-x 10 1700000000

func (*Mtree) Lookup added in v0.4.0

func (m *Mtree) Lookup(p string) (*MtreeEntry, bool)

Lookup returns the entry of a path (relative, without "./"); a path listed twice yields its last line.

type MtreeDiff added in v0.4.0

type MtreeDiff struct {
	Path string
	Kind DiffKind
	// Keyword is the mtree keyword that differs ("size", "sha256digest",
	// "mode", ...); empty for DiffMissing and DiffExtra.
	Keyword string
	// Want is the value of the .MTREE and Got the one found.
	Want, Got string
}

MtreeDiff is one difference between a file and its .MTREE entry.

func (MtreeDiff) String added in v0.4.0

func (d MtreeDiff) String() string

type MtreeEntry added in v0.4.0

type MtreeEntry struct {
	// Path is relative to the root of the package, without "./".
	Path string
	Type MtreeType
	// Keys says which of the fields below were given.
	Keys MtreeKeys
	// Mode is the permission bits with setuid (04000), setgid (02000) and
	// sticky (01000).
	Mode  uint32
	UID   int64
	GID   int64
	Uname string
	Gname string
	Size  int64
	// Time is the modification time; the "time" keyword has fractions.
	Time  time.Time
	Link  string
	Nlink int64
	// MD5, SHA1, SHA256, SHA384, SHA512 and RMD160 are the lowercase hex
	// digests of the content (keywords md5digest or md5, sha256digest or
	// sha256, and so on).
	MD5, SHA1, SHA256, SHA384, SHA512, RMD160 string
	Cksum                                     string
	Flags                                     string
	Device                                    string
	Inode                                     int64
	Contents                                  string
	// Optional is set by the "optional" keyword: the entry need not exist.
	Optional bool
	// Extra holds the keywords this type does not know, by name.
	Extra map[string]string
}

MtreeEntry is one line of an .MTREE, with the keywords of the "/set" lines in force applied.

func (*MtreeEntry) FileMode added in v0.4.0

func (e *MtreeEntry) FileMode() fs.FileMode

FileMode returns the entry as a Go file mode: the type bit, the permissions and the setuid, setgid and sticky bits. An entry without a mode has the permission bits 0.

func (*MtreeEntry) Has added in v0.4.0

func (e *MtreeEntry) Has(k MtreeKeys) bool

Has reports whether every keyword of k is present.

type MtreeError added in v0.4.0

type MtreeError struct {
	Diffs []MtreeDiff
	// Truncated is set when more than MaxMtreeDiffs differences were found and
	// the rest is not listed.
	Truncated bool
}

MtreeError reports files that differ from the .MTREE. It matches ErrMtreeMismatch.

func (*MtreeError) Error added in v0.4.0

func (e *MtreeError) Error() string

func (*MtreeError) String added in v0.4.0

func (e *MtreeError) String() string

String joins the differences, one per line.

func (*MtreeError) Unwrap added in v0.4.0

func (e *MtreeError) Unwrap() error

Unwrap returns ErrMtreeMismatch.

type MtreeKeys added in v0.4.0

type MtreeKeys uint32

MtreeKeys is the set of keywords an entry carries, after the defaults of the "/set" lines have been applied. It tells a keyword that is absent from one that is zero.

const (
	KeyType MtreeKeys = 1 << iota
	KeyMode
	KeyUID
	KeyGID
	KeyUname
	KeyGname
	KeySize
	KeyTime
	KeyLink
	KeyNlink
	KeyMD5
	KeySHA1
	KeySHA256
	KeySHA384
	KeySHA512
	KeyRMD160
	KeyCksum
	KeyFlags
	KeyDevice
	KeyInode
	KeyContents
	KeyOptional
)

The keywords an MtreeEntry holds as fields. Any other keyword is in MtreeEntry.Extra.

type MtreeType added in v0.4.0

type MtreeType string

MtreeType is the "type" keyword of an mtree entry.

const (
	MtreeFile   MtreeType = "file"
	MtreeDir    MtreeType = "dir"
	MtreeLink   MtreeType = "link"
	MtreeFifo   MtreeType = "fifo"
	MtreeChar   MtreeType = "char"
	MtreeBlock  MtreeType = "block"
	MtreeSocket MtreeType = "socket"
)

The types of an mtree entry.

type OptionalDep added in v0.4.0

type OptionalDep struct {
	Dependency
	// Description says what the dependency adds; it can be empty.
	Description string
	// Package is the package of the index that would satisfy it, set by
	// Index.OptionalDeps; nil when none does.
	Package *IndexedPackage
}

OptionalDep is an optional dependency: "name[: description]" in the optdepends of a package. It is a dependency that pacman suggests but does not install.

func ParseOptionalDep added in v0.4.0

func ParseOptionalDep(s string) (OptionalDep, error)

ParseOptionalDep parses "name[(<=|>=|=|<|>)version][: description]".

Example
package main

import (
	"fmt"

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

func main() {
	o, _ := pacman.ParseOptionalDep("python>=3: scripting support")
	fmt.Println(o.Name, o.Op, o.Version, "-", o.Description)

}
Output:
python >= 3 - scripting support

func (OptionalDep) String added in v0.4.0

func (o OptionalDep) String() string

String returns the optdepends entry ParseOptionalDep accepts.

type Package

type Package struct {
	Info        *PkgInfo
	Compression string
	// Files is the file list as the files database writes it: paths relative to
	// the root, directories with a trailing slash, dot files (.PKGINFO,
	// .BUILDINFO, .MTREE, .INSTALL) left out.
	Files []string
}

Package is what the repository database needs to know about a package file.

func Extract added in v0.4.0

func Extract(r io.Reader, dir string, opts ExtractOptions) (*Package, error)

Extract unpacks a package into dir, which must exist, and returns what ReadPackage would: the .PKGINFO and the file list.

Entry paths are confined to dir: they are resolved the way a chroot would, so a symbolic link of the package (an absolute "lib -> /usr/lib" included) cannot redirect a later entry out of dir, and a hard link or symbolic link that names something outside fails with ErrUnsafeEntry. A regular file replaces whatever is at its path; directories already there are kept and given the mode and time of the package at the end. Reaching a limit fails with ErrPackageTooLarge or ErrExtractTooLarge.

Example

Extract unpacks a package below a directory and checks it against its .MTREE. Nothing is written outside the directory.

package main

import (
	"bytes"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"time"

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

func examplePackage() []byte {
	built := time.Unix(1700000000, 0)

	spec := &pacman.Spec{
		Info: pacman.PkgInfo{Name: "shapes", Version: "1.0-1", Description: "Some shapes", Arch: "any", BuildDate: 1700000000},
		Scriptlets: &pacman.Scriptlets{
			PostInstall: "echo installed",
		},
		Files: []pacman.File{
			{Path: "usr/bin/shape", Mode: 0o755, ModTime: built, Data: []byte("#!/bin/sh\n")},
			{Path: "usr/bin/shape-hard", Hardlink: "usr/bin/shape", ModTime: built},
			{Path: "usr/bin/shape-link", Mode: fs.ModeSymlink | 0o777, Linkname: "shape", ModTime: built},
			{Path: "usr/share/shapes/data", Mode: 0o644, UID: 1234, GID: 5678, ModTime: built, Data: []byte("data\n")},
		},
	}

	var buf bytes.Buffer
	if err := spec.Write(&buf, pacman.WriteOptions{MtreeMD5: true}); err != nil {
		panic(err)
	}

	return buf.Bytes()
}

func main() {
	dir, err := os.MkdirTemp("", "extract")
	if err != nil {
		fmt.Println(err)

		return
	}

	defer func() { _ = os.RemoveAll(dir) }()

	pkg, err := pacman.Extract(bytes.NewReader(examplePackage()), dir, pacman.ExtractOptions{
		Verify:        true,
		VerifyOptions: pacman.VerifyOptions{IgnoreOwner: true}, // the owners need root
	})
	if err != nil {
		fmt.Println(err)

		return
	}

	target, _ := os.Readlink(filepath.Join(dir, "usr/bin/shape-link"))
	a, _ := os.Stat(filepath.Join(dir, "usr/bin/shape"))
	b, _ := os.Stat(filepath.Join(dir, "usr/bin/shape-hard"))

	fmt.Println(pkg.Info.Name, len(pkg.Files), "files")
	fmt.Println("symlink to", target, "- hard link:", os.SameFile(a, b))
}
Output:
shapes 8 files
symlink to shape - hard link: true

func ReadPackage

func ReadPackage(r io.Reader) (*Package, error)

ReadPackage reads a .pkg.tar.{zst,xz,gz} from r: its .PKGINFO and its file list. Compression is detected from the content, not the name.

type ParseOptions added in v0.4.0

type ParseOptions struct {
	// Include opens the files an "Include = value" line names, expanding
	// globs. Library code never touches the file system on its own: the caller
	// decides where includes come from (see FSIncludeResolver and
	// OSIncludeResolver). With a nil Include, ParseConfig leaves Include lines
	// out; ParseConfigFS and ParseConfigFile default to their own resolver.
	Include IncludeResolver
	// MaxIncludeDepth bounds the include nesting; zero selects
	// DefaultMaxIncludeDepth.
	MaxIncludeDepth int
	// MaxIncludeFiles bounds the included files of the whole configuration;
	// zero selects DefaultMaxIncludeFiles.
	MaxIncludeFiles int
	// Strict rejects directives pacman does not know with
	// ErrUnknownDirective; by default they are kept in Config.Unknown.
	Strict bool
}

ParseOptions tunes the configuration parsers. The zero value is valid.

type PkgInfo

type PkgInfo struct {
	Name        string
	Base        string
	Version     string // [epoch:]pkgver-pkgrel
	Description string
	URL         string
	Packager    string
	Arch        string
	BuildDate   int64
	InstalledSz int64

	Licenses     []string
	Groups       []string
	Replaces     []string
	Conflicts    []string
	Provides     []string
	Backup       []string // files pacman keeps as ".pacsave"/".pacnew" on upgrade
	Depends      []string
	OptDepends   []string
	MakeDepends  []string
	CheckDepends []string
	// XData holds the "xdata" lines, each "key=value" (makepkg writes
	// "pkgtype=pkg" there).
	XData []string
}

PkgInfo is the parsed .PKGINFO of a package.

func ParsePkgInfo

func ParsePkgInfo(r io.Reader) (*PkgInfo, error)

ParsePkgInfo parses the text of a .PKGINFO. The name, version and architecture are required and validated; everything else is optional.

func (*PkgInfo) Render

func (p *PkgInfo) Render(generator string) ([]byte, error)

Render returns the text of the .PKGINFO in the order makepkg writes it, after Validate. generator, when not empty, names the tool in the leading "# Generated by" comment.

func (*PkgInfo) Validate

func (p *PkgInfo) Validate() error

Validate checks that the PkgInfo can be written and read back: a valid name, version and architecture, a valid base name (the name when empty), values without line breaks and within the field limits. It fills an empty Base with the name, as ParsePkgInfo does.

type Reason added in v0.3.1

type Reason int

Reason is why a package was installed: the "%REASON%" of its desc.

const (
	// ReasonExplicit means the user asked for the package. It is also the
	// reason of a package whose desc has no %REASON%.
	ReasonExplicit Reason = 0
	// ReasonDependency means the package came in to satisfy another one.
	ReasonDependency Reason = 1
)

The reasons pacman records.

type Replacement added in v0.4.0

type Replacement struct {
	Installed *InstalledPackage
	Package   *IndexedPackage
}

Replacement is an installed package that Package replaces, through its "replaces" entry, in a system upgrade.

type Repo

type Repo struct {
	Name    string
	Servers []string
	// CacheServers are the CacheServer URLs: package locations a Client tries
	// before Servers. They never serve databases.
	CacheServers []string
	// Usage is what the repository may be used for; the zero value is all.
	Usage Usage
	// SigLevel is the signature level of the repository, merged over the
	// global one by ParseConfig. The zero value means unspecified: a Client
	// then applies its ClientOptions.
	SigLevel SigLevel
}

Repo is a repository: a name and the servers that carry it. A server is a URL that may contain the $repo and $arch placeholders (see ExpandServer).

type ResolveOptions

type ResolveOptions struct {
	// Installed, when set, reports a dependency the system already satisfies;
	// such dependencies are not resolved further.
	Installed func(Dependency) bool
	// Local is the set of installed packages (LocalDB.List). A dependency one
	// of them satisfies is not resolved further, and Index.Install and
	// Index.Sysupgrade check the transaction against them for conflicts and
	// broken dependencies. Index.Sysupgrade uses its own installed argument
	// instead.
	Local []*InstalledPackage
	// IgnorePkg lists package names or glob patterns, as pacman's IgnorePkg
	// option does. An ignored package is not upgraded or replaced by
	// Index.Sysupgrade and is not picked to satisfy a dependency. A package
	// asked for explicitly is installed all the same, as pacman does when it is
	// not asked.
	IgnorePkg []string
	// IgnoreGroup lists group names or glob patterns, as pacman's IgnoreGroup
	// option does; a package is ignored when one of its groups matches.
	IgnoreGroup []string
	// WithOptional also installs the optional dependencies the index can
	// satisfy. Without it they are never installed, as in pacman.
	WithOptional bool
}

ResolveOptions tunes ResolveDeps, Index.Install and Index.Sysupgrade.

type ScanOptions added in v0.4.0

type ScanOptions struct {
	// Owners keeps the numeric owner of each file, and its name when the user
	// and group databases know it, where ScanDir makes everything root:root.
	// A packager that is not root usually builds under fakeroot, which reports
	// root as the owner, and leaves this off.
	Owners bool
	// Xattrs keeps the extended attributes of each file, such as
	// security.capability. Only Linux reads them.
	Xattrs bool
}

ScanOptions tunes ScanDirWith.

type Scriptlets

type Scriptlets struct {
	PreInstall  string
	PostInstall string
	PreUpgrade  string
	PostUpgrade string
	PreRemove   string
	PostRemove  string

	// UpgradeFallback makes an undefined PreUpgrade run the PreInstall body and
	// an undefined PostUpgrade run the PostInstall body, so a package that only
	// declares install hooks sees them on upgrades too.
	UpgradeFallback bool

	// Preamble is shell text placed before the hooks, typically the helper
	// functions the hooks call. It is written verbatim.
	Preamble string
}

Scriptlets are the bodies of the six hooks pacman runs from a package's .INSTALL file. Each field holds the shell commands of one hook, without the "name() { ... }" wrapper; an empty field means the hook is not defined.

func (*Scriptlets) Empty

func (s *Scriptlets) Empty() bool

Empty reports whether no hook is defined (the package has no .INSTALL).

func (*Scriptlets) Hooks

func (s *Scriptlets) Hooks() string

Hooks renders the six function definitions, without the Preamble. It is what a caller scans to decide which helper functions the Preamble must carry.

func (*Scriptlets) Render

func (s *Scriptlets) Render() []byte

Render returns the content of the .INSTALL file: the Preamble followed by the hook functions. It is nil when no hook is defined.

type SigCheck added in v0.4.0

type SigCheck uint8

SigCheck says when signatures are checked: the "Never", "Optional" and "Required" options of a SigLevel.

const (
	// SigCheckUnset means no level was given; the zero value.
	SigCheckUnset SigCheck = iota
	// SigNever suppresses signature checking, even for a signature present.
	SigNever
	// SigOptional checks a signature that is present and accepts its absence.
	SigOptional
	// SigRequired fails on a missing or invalid signature.
	SigRequired
)

The values of SigCheck.

type SigLevel added in v0.4.0

type SigLevel struct {
	Package  SigPolicy
	Database SigPolicy
}

SigLevel is a signature verification level as libalpm models it: one policy for packages and one for databases. The zero value is "not specified", for which a Client falls back to its ClientOptions.

func DefaultSigLevel added in v0.4.0

func DefaultSigLevel() SigLevel

DefaultSigLevel is libalpm's built-in level, "Required TrustedOnly" for packages and databases.

func ParseSigLevel added in v0.4.0

func ParseSigLevel(s string) (SigLevel, error)

ParseSigLevel parses the value of a SigLevel option on top of DefaultSigLevel, like pacman does for the global option.

Example

SigLevel directives apply left to right, as in pacman: a bare level sets the package and the database policy, a Package or Database prefix only one.

package main

import (
	"fmt"

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

func main() {
	level, err := pacman.ParseSigLevel("Required DatabaseOptional")
	if err != nil {
		fmt.Println(err)

		return
	}

	fmt.Println(level.Package.Check == pacman.SigRequired, level.Database.Check == pacman.SigOptional)
	fmt.Println(level.Database.VerifyMode() == pacman.VerifyIfPresent)
	fmt.Println(level)
}
Output:
true true
true
PackageRequired PackageTrustedOnly DatabaseOptional DatabaseTrustedOnly

func (SigLevel) Apply added in v0.4.0

func (l SigLevel) Apply(s string) (SigLevel, error)

Apply returns l modified by the options of a SigLevel value, processed left to right with later options overriding earlier ones, as pacman does. The options are "Never", "Optional", "Required", "TrustedOnly" and "TrustAll", each of which may carry a "Package" or "Database" prefix to affect that object only. Separate options with spaces; the names are case-sensitive.

func (SigLevel) IsZero added in v0.4.0

func (l SigLevel) IsZero() bool

IsZero reports a level nothing was specified for.

func (SigLevel) String added in v0.4.0

func (l SigLevel) String() string

String returns Tokens joined by spaces, a value ParseSigLevel reads back.

func (SigLevel) Tokens added in v0.4.0

func (l SigLevel) Tokens() []string

Tokens returns the level as pacman-conf prints it, one option per element: "PackageRequired", "PackageTrustedOnly", "DatabaseOptional" and so on. A policy that is Never has no trust option; an unset one has no option at all.

type SigPolicy added in v0.4.0

type SigPolicy struct {
	Check SigCheck
	Trust SigTrust
}

SigPolicy is the signature policy of one kind of object, a package or a database.

Trust is carried for fidelity with pacman.conf: a gpg.Keyring holds public keys without trust levels, so every key in it counts as fully trusted and SigTrustedOnly and SigTrustAll verify alike.

func (SigPolicy) String added in v0.4.0

func (p SigPolicy) String() string

String returns the pacman-conf rendering: "Never", "Optional" or "Required" followed, unless Never, by "TrustedOnly" or "TrustAll" ("" when unset).

func (SigPolicy) VerifyMode added in v0.4.0

func (p SigPolicy) VerifyMode() VerifyMode

VerifyMode maps the policy onto the client's VerifyMode. An unset policy maps to VerifyNone; the Client falls back to its own default before asking.

type SigTrust added in v0.4.0

type SigTrust uint8

SigTrust says which signing keys are acceptable: the "TrustedOnly" and "TrustAll" options of a SigLevel.

const (
	// SigTrustedOnly accepts fully trusted keys only; the default.
	SigTrustedOnly SigTrust = iota
	// SigTrustAll accepts keys of marginal or unknown trust.
	SigTrustAll
)

The values of SigTrust.

type Spec

type Spec struct {
	// Info is the .PKGINFO. Name, Version and Arch are required. A zero
	// InstalledSz is replaced by the total size of the regular files, and an
	// empty Base by the name.
	Info PkgInfo
	// BuildInfo is the .BUILDINFO; nil leaves the file out. Its empty PkgName,
	// PkgBase, PkgVer, PkgArch, Packager and BuildDate are taken from Info.
	BuildInfo *BuildInfo
	// Scriptlets are the install hooks written to .INSTALL; nil or no hook
	// leaves the file out.
	Scriptlets *Scriptlets
	// Changelog is the content of .CHANGELOG; empty leaves the file out.
	Changelog []byte
	// Files is the payload. Parent directories that are not listed are added
	// with mode 0755.
	Files []File
}

Spec describes a package to write: everything the archive holds.

func (*Spec) FileName

func (s *Spec) FileName(compression string) string

FileName returns the file name the package is published under: name-version-arch.pkg.tar.ext.

func (*Spec) Write

func (s *Spec) Write(w io.Writer, opts WriteOptions) error

Write writes the package to w.

func (*Spec) WriteFile

func (s *Spec) WriteFile(path string, opts WriteOptions) error

WriteFile writes the package to path through a temporary file in the same directory, so a failed write leaves nothing behind.

type Transaction added in v0.4.0

type Transaction struct {
	// Packages is every package to install or upgrade, each after the ones it
	// depends on.
	Packages []*IndexedPackage
	// Installs are the packages of Packages that are new to the system and
	// replace nothing.
	Installs []*IndexedPackage
	// Upgrades are the packages of Packages that take the place of an installed
	// package of the same name.
	Upgrades []Upgrade
	// Replacements are the packages of Packages that replace installed ones of
	// another name; the replaced packages are in Removals too.
	Replacements []Replacement
	// Removals are the installed packages to remove: the replaced ones.
	Removals []*InstalledPackage
}

Transaction is what installing packages or upgrading a system changes.

type Upgrade added in v0.4.0

type Upgrade struct {
	Installed *InstalledPackage
	Package   *IndexedPackage
}

Upgrade is an installed package and the sync package that takes its place. The versions can be equal (a reinstall) or the installed one newer when the package was asked for by name.

type Usage added in v0.4.0

type Usage uint8

Usage says what a repository may be used for: the Usage option of a pacman.conf repository section. The zero value means no Usage line, which pacman reads as All.

const (
	// UsageSync allows refreshing the database (pacman -Sy).
	UsageSync Usage = 1 << iota
	// UsageSearch allows searching the repository (pacman -Ss).
	UsageSearch
	// UsageInstall allows installing its packages (pacman -S pkg).
	UsageInstall
	// UsageUpgrade allows upgrading installed packages from it (pacman -Su).
	UsageUpgrade
	// UsageAll is every use.
	UsageAll = UsageSync | UsageSearch | UsageInstall | UsageUpgrade
)

The uses of a repository. They combine with |.

func (Usage) Allows added in v0.4.0

func (u Usage) Allows(want Usage) bool

Allows reports whether u permits every use in want. The zero Usage permits everything.

func (Usage) String added in v0.4.0

func (u Usage) String() string

String returns the Usage option value: "All", or the names of the uses separated by spaces.

type VerifyMode

type VerifyMode int

VerifyMode says how the client treats detached OpenPGP signatures.

const (
	// VerifyNone never verifies. Databases still fetch their ".sig" on a
	// best-effort basis so it can be stored beside the database for other
	// tools.
	VerifyNone VerifyMode = iota
	// VerifyIfPresent verifies a signature the server provides and fails on an
	// invalid one; a server that has none (HTTP 404 or 410) is accepted.
	VerifyIfPresent
	// VerifyRequired fails when a signature is missing or invalid.
	VerifyRequired
)

type VerifyOptions added in v0.4.0

type VerifyOptions struct {
	// IgnoreTime leaves the modification time unchecked.
	IgnoreTime bool
	// IgnoreOwner leaves uid, gid, uname and gname unchecked. A package
	// extracted by a user that is not root has the owner of that user.
	IgnoreOwner bool
	// IgnoreMode leaves the permission bits unchecked.
	IgnoreMode bool
	// SkipContent, when not nil, reports paths whose size, time and digests
	// are not checked, such as the backup files a user may have edited.
	SkipContent func(path string) bool
	// contains filtered or unexported fields
}

VerifyOptions tunes the verification against an .MTREE. The zero value checks every keyword the .MTREE gives.

type WriteOptions

type WriteOptions struct {
	// Compression is the extension of the package: CompressionZstd (the
	// default), CompressionXZ or CompressionGzip.
	Compression string
	// Level is the compression level: a zstd level (1-22), or a gzip level
	// (1-9). Zero selects the default; xz has a single setting.
	Level int
	// ClampMTime limits every file time to the build date (Info.BuildDate), as
	// makepkg does under SOURCE_DATE_EPOCH, so the archive does not depend on
	// when the files were touched.
	ClampMTime bool
	// TarFormat is the tar flavour; the zero value selects tar.FormatPAX.
	TarFormat tar.Format
	// Generator, when not empty, names the tool in the "# Generated by" comment
	// of .PKGINFO.
	Generator string
	// MtreeMD5 adds an md5digest next to the sha256digest of every regular file
	// of the .MTREE, as older makepkg versions wrote it (they asked bsdtar for
	// "md5,sha256"). makepkg 7.1, the version checked against, writes the
	// sha256digest only, which is the default here. libarchive prints the
	// md5digest before the sha256digest.
	MtreeMD5 bool
}

WriteOptions tunes how a package is written. The zero value writes a zstd-compressed PAX tar.

Jump to

Keyboard shortcuts

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