16 // backupArchive writes the files in root to path through a private temporary
17 // file and a rename. Only directories and regular files enter the archive.
18 func backupArchive(ctx context.Context, root, path string) (size int64, err error) {
19 file, err := os.CreateTemp(filepath.Dir(path), ".onechat-backup-*")
21 return 0, fmt.Errorf("create archive: %w", err)
25 err = errors.Join(err, file.Close())
26 removeErr := os.Remove(file.Name())
27 if !errors.Is(removeErr, os.ErrNotExist) {
28 err = errors.Join(err, removeErr)
32 compressed := gzip.NewWriter(file)
33 archive := tar.NewWriter(compressed)
34 err = filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
36 return fmt.Errorf("walk backup: %w", err)
47 name, err := filepath.Rel(root, path)
49 return fmt.Errorf("name archive entry: %w", err)
52 info, err := entry.Info()
54 return fmt.Errorf("read backup entry: %w", err)
57 if !info.IsDir() && !info.Mode().IsRegular() {
58 return fmt.Errorf("unsupported backup entry %q", name)
61 header, err := tar.FileInfoHeader(info, "")
63 return fmt.Errorf("make archive header: %w", err)
66 header.Name = filepath.ToSlash(name)
67 header.Uid, header.Gid = 0, 0
68 header.Uname, header.Gname = "", ""
69 err = archive.WriteHeader(header)
71 return fmt.Errorf("write archive header: %w", err)
78 err = backupCopyFile(ctx, archive, path, info.Size())
80 return fmt.Errorf("archive file: %w", err)
85 err = errors.Join(err, archive.Close(), compressed.Close())
87 return 0, fmt.Errorf("write archive: %w", err)
92 return 0, fmt.Errorf("sync archive: %w", err)
95 info, err := file.Stat()
97 return 0, fmt.Errorf("read archive size: %w", err)
100 err = os.Rename(file.Name(), path)
102 return 0, fmt.Errorf("install archive: %w", err)
105 return info.Size(), nil
108 // backupExtract restores regular files and directories in an empty staging
109 // directory. Links, duplicate entries, unsafe names, and special modes fail.
110 // Directory modes apply last so a read-only directory can hold files.
111 func backupExtract(ctx context.Context, path, root string) (err error) {
112 file, err := os.Open(path)
114 return fmt.Errorf("open archive: %w", err)
118 err = errors.Join(err, file.Close())
121 compressed, err := gzip.NewReader(file)
123 return fmt.Errorf("open compressed archive: %w", err)
127 err = errors.Join(err, compressed.Close())
130 archive := tar.NewReader(BackupReader{
134 seen := make(map[string]bool)
136 var directories []*tar.Header
139 var header *tar.Header
141 header, err = archive.Next()
142 if errors.Is(err, io.EOF) {
147 return fmt.Errorf("read archive entry: %w", err)
150 name := strings.TrimSuffix(header.Name, "/")
151 if !filepath.IsLocal(name) || strings.Contains(name, "\\") || filepath.Clean(name) != name || backupExcluded(name) {
152 return fmt.Errorf("unsafe archive path %q", header.Name)
156 return fmt.Errorf("duplicate archive path %q", name)
160 if header.Mode & ^int64(0o777) != 0 {
161 return fmt.Errorf("unsafe archive mode for %q", name)
164 target := filepath.Join(root, name)
165 switch header.Typeflag {
167 err = os.MkdirAll(target, 0o700)
168 directories = append(directories, header)
170 err = os.MkdirAll(filepath.Dir(target), 0o700)
172 err = backupExtractFile(archive, target, os.FileMode(header.Mode))
175 return fmt.Errorf("unsupported archive entry %q", name)
179 return fmt.Errorf("restore archive entry %q: %w", name, err)
183 // Read through the gzip trailer to check its checksum.
184 _, err = io.Copy(io.Discard, compressed)
186 return fmt.Errorf("check archive checksum: %w", err)
189 for i := len(directories) - 1; i >= 0; i-- {
190 header := directories[i]
191 err = os.Chmod(filepath.Join(root, header.Name), os.FileMode(header.Mode))
193 return fmt.Errorf("restore directory mode: %w", err)
200 // BackupReader checks cancellation between reads of an archive or file.
201 type BackupReader struct {
206 func (r BackupReader) Read(data []byte) (int, error) {
207 if r.ctx.Err() != nil {
208 return 0, r.ctx.Err()
211 count, err := r.reader.Read(data)
213 return count, fmt.Errorf("read backup data: %w", err)
219 // backupCopyFile copies the size fixed at the snapshot of path. Growth after
220 // that point is not part of the copy, and a shorter file is an error.
221 func backupCopyFile(ctx context.Context, out io.Writer, path string, size int64) (err error) {
222 file, err := os.Open(path)
224 return fmt.Errorf("open backup file: %w", err)
228 err = errors.Join(err, file.Close())
231 _, err = io.CopyN(out, BackupReader{
236 return fmt.Errorf("copy backup file: %w", err)
242 func backupExtractFile(in io.Reader, path string, mode os.FileMode) (err error) {
243 file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
245 return fmt.Errorf("create restored file: %w", err)
249 err = errors.Join(err, file.Close())
252 _, err = io.Copy(file, in)
254 return fmt.Errorf("write restored file: %w", err)
257 err = file.Chmod(mode)
259 return fmt.Errorf("restore file mode: %w", err)
265 // backupExcluded keeps runtime locks, sockets, probe files, and import copies
266 // out of the snapshot.
267 func backupExcluded(name string) bool {
268 first, _, _ := strings.Cut(filepath.ToSlash(name), "/")
269 if first == socketFileName || first == tokenLockFileName || first == "probe" || strings.HasPrefix(first, "agent-backup-") {
273 if filepath.Base(name) == "lock" {