16 // BackupReader checks cancellation between reads of an archive or file.
17 type BackupReader struct {
22 func (r BackupReader) Read(data []byte) (int, error) {
23 if r.ctx.Err() != nil {
27 count, err := r.reader.Read(data)
29 return count, fmt.Errorf("read backup data: %w", err)
35 // backupArchive writes the files in root to path through a private temporary
36 // file and a rename. Only directories and regular files enter the archive.
37 func backupArchive(ctx context.Context, root, path string) (size int64, err error) {
38 file, err := os.CreateTemp(filepath.Dir(path), ".onechat-backup-*")
40 return 0, fmt.Errorf("create archive: %w", err)
44 err = errors.Join(err, file.Close())
45 removeErr := os.Remove(file.Name())
46 if !errors.Is(removeErr, os.ErrNotExist) {
47 err = errors.Join(err, removeErr)
51 compressed := gzip.NewWriter(file)
52 archive := tar.NewWriter(compressed)
53 err = filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
55 return fmt.Errorf("walk backup: %w", err)
66 name, err := filepath.Rel(root, path)
68 return fmt.Errorf("name archive entry: %w", err)
71 info, err := entry.Info()
73 return fmt.Errorf("read backup entry: %w", err)
76 if !info.IsDir() && !info.Mode().IsRegular() {
77 return fmt.Errorf("unsupported backup entry %q", name)
80 header, err := tar.FileInfoHeader(info, "")
82 return fmt.Errorf("make archive header: %w", err)
85 header.Name = filepath.ToSlash(name)
86 header.Uid, header.Gid = 0, 0
87 header.Uname, header.Gname = "", ""
88 err = archive.WriteHeader(header)
90 return fmt.Errorf("write archive header: %w", err)
97 err = backupCopyFile(ctx, archive, path, info.Size())
99 return fmt.Errorf("archive file: %w", err)
105 err = errors.Join(err, archive.Close(), compressed.Close())
107 return 0, fmt.Errorf("write archive: %w", err)
112 return 0, fmt.Errorf("sync archive: %w", err)
115 info, err := file.Stat()
117 return 0, fmt.Errorf("read archive size: %w", err)
120 err = os.Rename(file.Name(), path)
122 return 0, fmt.Errorf("install archive: %w", err)
125 return info.Size(), nil
128 // backupExtract restores regular files and directories in an empty staging
129 // directory. Links, duplicate entries, unsafe names, and special modes fail.
130 // Directory modes apply last so a read-only directory can hold files.
131 func backupExtract(ctx context.Context, path, root string) (err error) {
132 file, err := os.Open(path)
134 return fmt.Errorf("open archive: %w", err)
138 err = errors.Join(err, file.Close())
141 compressed, err := gzip.NewReader(file)
143 return fmt.Errorf("open compressed archive: %w", err)
147 err = errors.Join(err, compressed.Close())
150 archive := tar.NewReader(BackupReader{
155 seen := make(map[string]bool)
157 var directories []*tar.Header
160 var header *tar.Header
162 header, err = archive.Next()
163 if errors.Is(err, io.EOF) {
168 return fmt.Errorf("read archive entry: %w", err)
171 name := strings.TrimSuffix(header.Name, "/")
172 if !filepath.IsLocal(name) || strings.Contains(name, "\\") || filepath.Clean(name) != name || backupExcluded(name) {
173 return fmt.Errorf("unsafe archive path %q", header.Name)
177 return fmt.Errorf("duplicate archive path %q", name)
181 if header.Mode & ^int64(0o777) != 0 {
182 return fmt.Errorf("unsafe archive mode for %q", name)
185 target := filepath.Join(root, name)
186 switch header.Typeflag {
188 err = os.MkdirAll(target, 0o700)
189 directories = append(directories, header)
191 err = os.MkdirAll(filepath.Dir(target), 0o700)
193 err = backupExtractFile(archive, target, os.FileMode(header.Mode))
196 return fmt.Errorf("unsupported archive entry %q", name)
200 return fmt.Errorf("restore archive entry %q: %w", name, err)
204 // Read through the gzip trailer to check its checksum.
205 _, err = io.Copy(io.Discard, compressed)
207 return fmt.Errorf("check archive checksum: %w", err)
210 for i := len(directories) - 1; i >= 0; i-- {
211 header := directories[i]
212 err = os.Chmod(filepath.Join(root, header.Name), os.FileMode(header.Mode))
214 return fmt.Errorf("restore directory mode: %w", err)
221 // backupCopyFile copies the size fixed at the snapshot of path. Growth after
222 // that point is not part of the copy, and a shorter file is an error.
223 func backupCopyFile(ctx context.Context, out io.Writer, path string, size int64) (err error) {
224 file, err := os.Open(path)
226 return fmt.Errorf("open backup file: %w", err)
230 err = errors.Join(err, file.Close())
233 _, err = io.CopyN(out, BackupReader{
238 return fmt.Errorf("copy backup file: %w", err)
244 func backupExtractFile(in io.Reader, path string, mode os.FileMode) (err error) {
245 file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
247 return fmt.Errorf("create restored file: %w", err)
251 err = errors.Join(err, file.Close())
254 _, err = io.Copy(file, in)
256 return fmt.Errorf("write restored file: %w", err)
259 err = file.Chmod(mode)
261 return fmt.Errorf("restore file mode: %w", err)
267 // backupExcluded keeps runtime locks, sockets, probe files, and import copies
268 // out of the snapshot.
269 func backupExcluded(name string) bool {
270 first, _, _ := strings.Cut(filepath.ToSlash(name), "/")
271 if first == socketFileName || first == tokenLockFileName || first == "probe" || strings.HasPrefix(first, "agent-backup-") {
275 if filepath.Base(name) == "lock" || (first == imageDirName && strings.HasPrefix(filepath.Base(name), ".image-")) || (first == voiceDirName && (strings.HasPrefix(filepath.Base(name), ".voice-") || strings.HasPrefix(filepath.Base(name), ".transcript-"))) {