// Package backup is the archive format and handling behind the optional // " backup create|list|verify|restore" commands of the Yetano // program standard (docs/program-conventions.md in the yetano // meta-repository). The program decides what goes in (a consistent // database copy, its config, state files -- never what can be fetched // again); this package writes, lists, rotates, checks and unpacks. // // w, err := backup.Create(dir, "yanks-registry", version.Version) // w.AddFile("registry.db", snapshotPath) // w.AddFile("config/yanks-registry.yaml", cfgPath) // a, err := w.Close() // atomic: complete or nothing // removed, err := backup.Prune(dir, "yanks-registry", backup.DefaultKeep, time.Now()) // // An archive is a gzip-compressed tar named // "-.tar.gz": the files, then MANIFEST.json (program, // version, time, and every file's name, size, mode and SHA-256). // Archives and their directory are only readable by the owner -- they // hold password hashes and keys as often as not. Extract verifies an // archive completely before it writes anything, and only ever writes // below its destination. package backup import ( "archive/tar" "compress/gzip" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "io/fs" "os" "path" "path/filepath" "regexp" "sort" "strings" "time" ) // Schema is the manifest version this package writes and reads. const Schema = 1 // ManifestName is the archive's last entry. const ManifestName = "MANIFEST.json" // timeLayout is the UTC time in archive names; it sorts as text. const timeLayout = "20060102T150405Z" // Manifest describes an archive. type Manifest struct { Schema int `json:"schema"` Program string `json:"program"` Version string `json:"version,omitempty"` CreatedAt time.Time `json:"created_at"` Files []File `json:"files"` } // File is one archived file. Name is slash-separated and relative. type File struct { Name string `json:"name"` Size int64 `json:"size"` Mode uint32 `json:"mode"` SHA256 string `json:"sha256"` } // Archive is a backup file in a directory. type Archive struct { Path string `json:"path"` Program string `json:"program"` CreatedAt time.Time `json:"created_at"` Size int64 `json:"size"` } // ErrInvalid: the archive is damaged, incomplete or not a backup. var ErrInvalid = errors.New("backup: invalid archive") func invalid(format string, args ...any) error { return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, args...)) } var ( programRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`) suffixRE = regexp.MustCompile(`^-[0-9]+$`) ) // Writer builds an archive in a temporary file next to its final name. type Writer struct { dir, program string m Manifest f *os.File gz *gzip.Writer tw *tar.Writer names map[string]bool err error } // Create starts an archive of program in dir (created owner-only when // missing). func Create(dir, program, version string) (*Writer, error) { if !programRE.MatchString(program) { return nil, fmt.Errorf("backup: invalid program name %q", program) } if err := os.MkdirAll(dir, 0o700); err != nil { return nil, fmt.Errorf("backup: %w", err) } f, err := os.CreateTemp(dir, "."+program+"-*.partial") if err != nil { return nil, fmt.Errorf("backup: %w", err) } if err := f.Chmod(0o600); err != nil { f.Close() os.Remove(f.Name()) return nil, fmt.Errorf("backup: %w", err) } gz := gzip.NewWriter(f) return &Writer{dir: dir, program: program, f: f, gz: gz, tw: tar.NewWriter(gz), names: map[string]bool{}, m: Manifest{Schema: Schema, Program: program, Version: version, CreatedAt: time.Now().UTC().Truncate(time.Second), Files: []File{}}}, nil } // validName: relative, slash-separated, clean, inside the archive. func validName(name string) bool { return name != "" && name != "." && name != ManifestName && !strings.HasPrefix(name, "/") && !strings.Contains(name, `\`) && path.Clean(name) == name && name != ".." && !strings.HasPrefix(name, "../") } func (w *Writer) add(name string, mode fs.FileMode, size int64, mtime time.Time, r io.Reader) error { if w.err != nil { return w.err } if !validName(name) { return fmt.Errorf("backup: invalid name %q", name) } if w.names[name] { return fmt.Errorf("backup: %s added twice", name) } w.names[name] = true perm := uint32(mode.Perm()) h := &tar.Header{Name: name, Mode: int64(perm), Size: size, ModTime: mtime, Typeflag: tar.TypeReg, Format: tar.FormatPAX} if err := w.tw.WriteHeader(h); err != nil { w.err = fmt.Errorf("backup: %s: %w", name, err) return w.err } sum := sha256.New() n, err := io.Copy(w.tw, io.TeeReader(r, sum)) if err == nil && n != size { err = fmt.Errorf("changed while it was read (%d of %d bytes)", n, size) } if err != nil { w.err = fmt.Errorf("backup: %s: %w", name, err) return w.err } w.m.Files = append(w.m.Files, File{Name: name, Size: size, Mode: perm, SHA256: hex.EncodeToString(sum.Sum(nil))}) return nil } // AddFile archives the regular file src as name. func (w *Writer) AddFile(name, src string) error { f, err := os.Open(src) if err != nil { return fmt.Errorf("backup: %w", err) } defer f.Close() fi, err := f.Stat() if err != nil { return fmt.Errorf("backup: %w", err) } if !fi.Mode().IsRegular() { return fmt.Errorf("backup: %s is not a regular file", src) } return w.add(name, fi.Mode(), fi.Size(), fi.ModTime(), f) } // AddBytes archives data as name. func (w *Writer) AddBytes(name string, data []byte, mode fs.FileMode) error { return w.add(name, mode, int64(len(data)), w.m.CreatedAt, strings.NewReader(string(data))) } // AddDir archives the regular files below src as prefix/, in a stable order. skip (may be nil) leaves out a file or, for // a directory, everything below it; rel is slash-separated. Symbolic // links and other special files are left out. func (w *Writer) AddDir(prefix, src string, skip func(rel string, d fs.DirEntry) bool) error { return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error { if err != nil { return fmt.Errorf("backup: %w", err) } rel, err := filepath.Rel(src, p) if err != nil { return err } if rel == "." { return nil } rel = filepath.ToSlash(rel) if skip != nil && skip(rel, d) { if d.IsDir() { return filepath.SkipDir } return nil } if !d.Type().IsRegular() { return nil } return w.AddFile(path.Join(prefix, rel), p) }) } // Close finishes the archive: the manifest, then an atomic rename to // "-