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, walkErr error) error {
36 return fmt.Errorf("walk backup: %w", walkErr)
47 name, nameErr := filepath.Rel(root, path)
49 return fmt.Errorf("name archive entry: %w", nameErr)
52 info, infoErr := entry.Info()
54 return fmt.Errorf("read backup entry: %w", infoErr)
57 if !info.IsDir() && !info.Mode().IsRegular() {
58 return fmt.Errorf("unsupported backup entry %q", name)
61 header, headerErr := tar.FileInfoHeader(info, "")
63 return fmt.Errorf("make archive header: %w", headerErr)
66 header.Name = filepath.ToSlash(name)
67 header.Uid, header.Gid = 0, 0
68 header.Uname, header.Gname = "", ""
69 headerErr = archive.WriteHeader(header)
71 return fmt.Errorf("write archive header: %w", headerErr)
78 return backupCopyFile(ctx, archive, path, info.Size())
80 err = errors.Join(err, archive.Close(), compressed.Close())
82 return 0, fmt.Errorf("write archive: %w", err)
87 return 0, fmt.Errorf("sync archive: %w", err)
90 info, err := file.Stat()
92 return 0, fmt.Errorf("read archive size: %w", err)
95 err = os.Rename(file.Name(), path)
97 return 0, fmt.Errorf("install archive: %w", err)
100 return info.Size(), nil
103 // backupExtract restores regular files and directories in an empty staging
104 // directory. Links, duplicate entries, unsafe names, and special modes fail.
105 // Directory modes apply last so a read-only directory can hold files.
106 func backupExtract(ctx context.Context, path, root string) (err error) {
107 file, err := os.Open(path)
109 return fmt.Errorf("open archive: %w", err)
113 err = errors.Join(err, file.Close())
116 compressed, err := gzip.NewReader(file)
118 return fmt.Errorf("open compressed archive: %w", err)
122 err = errors.Join(err, compressed.Close())
125 archive := tar.NewReader(BackupReader{ctx: ctx, reader: compressed})
126 seen := make(map[string]bool)
128 var directories []*tar.Header
131 header, readErr := archive.Next()
132 if errors.Is(readErr, io.EOF) {
137 return fmt.Errorf("read archive entry: %w", readErr)
140 name := strings.TrimSuffix(header.Name, "/")
141 if !filepath.IsLocal(name) || strings.Contains(name, "\\") || filepath.Clean(name) != name || backupExcluded(name) {
142 return fmt.Errorf("unsafe archive path %q", header.Name)
146 return fmt.Errorf("duplicate archive path %q", name)
150 if header.Mode & ^int64(0o777) != 0 {
151 return fmt.Errorf("unsafe archive mode for %q", name)
154 target := filepath.Join(root, name)
155 switch header.Typeflag {
157 err = os.MkdirAll(target, 0o700)
158 directories = append(directories, header)
160 err = os.MkdirAll(filepath.Dir(target), 0o700)
162 err = backupExtractFile(archive, target, os.FileMode(header.Mode))
165 return fmt.Errorf("unsupported archive entry %q", name)
169 return fmt.Errorf("restore archive entry %q: %w", name, err)
173 // Read through the gzip trailer to check its checksum.
174 _, err = io.Copy(io.Discard, compressed)
176 return fmt.Errorf("check archive checksum: %w", err)
179 for i := len(directories) - 1; i >= 0; i-- {
180 header := directories[i]
181 err = os.Chmod(filepath.Join(root, header.Name), os.FileMode(header.Mode))
183 return fmt.Errorf("restore directory mode: %w", err)
190 // BackupReader checks cancellation between reads of an archive or file.
191 type BackupReader struct {
196 func (r BackupReader) Read(data []byte) (int, error) {
197 if r.ctx.Err() != nil {
198 return 0, r.ctx.Err()
201 count, err := r.reader.Read(data)
203 return count, fmt.Errorf("read backup data: %w", err)
209 // backupCopyFile copies the size fixed at the snapshot of path. Growth after
210 // that point is not part of the copy, and a shorter file is an error.
211 func backupCopyFile(ctx context.Context, out io.Writer, path string, size int64) (err error) {
212 file, err := os.Open(path)
214 return fmt.Errorf("open backup file: %w", err)
218 err = errors.Join(err, file.Close())
221 _, err = io.CopyN(out, BackupReader{ctx: ctx, reader: file}, size)
223 return fmt.Errorf("copy backup file: %w", err)
229 func backupExtractFile(in io.Reader, path string, mode os.FileMode) (err error) {
230 file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
232 return fmt.Errorf("create restored file: %w", err)
236 err = errors.Join(err, file.Close())
239 _, err = io.Copy(file, in)
241 return fmt.Errorf("write restored file: %w", err)
244 err = file.Chmod(mode)
246 return fmt.Errorf("restore file mode: %w", err)
252 // backupExcluded keeps runtime locks, sockets, probe files, and import copies
253 // out of the snapshot.
254 func backupExcluded(name string) bool {
255 first, _, _ := strings.Cut(filepath.ToSlash(name), "/")
256 if first == socketFileName || first == tokenLockFileName || first == "probe" || strings.HasPrefix(first, "agent-backup-") {
260 if filepath.Base(name) == "lock" {