diff --git a/internal/export/writer.go b/internal/export/writer.go index 4832cf6..de99f61 100644 --- a/internal/export/writer.go +++ b/internal/export/writer.go @@ -1,17 +1,16 @@ package export import ( - "archive/zip" "bufio" "errors" "fmt" - "io" "os" "path/filepath" "sort" "github.com/moond4rk/hackbrowserdata/internal/category" "github.com/moond4rk/hackbrowserdata/internal/record" + "github.com/moond4rk/hackbrowserdata/internal/zipfile" ) type Writer struct { @@ -126,7 +125,7 @@ func (w *Writer) pack() error { } sort.Strings(names) zipName := filepath.Base(w.dir) + ".zip" - if err := writeZip(filepath.Join(w.dir, zipName), w.dir, names); err != nil { + if err := zipfile.Write(filepath.Join(w.dir, zipName), w.dir, names); err != nil { return fmt.Errorf("compress: %w", err) } for _, name := range names { @@ -138,49 +137,6 @@ func (w *Writer) pack() error { return nil } -// writeZip renames a finished temp file into place, so archivePath is never a partial zip. -func writeZip(archivePath, dir string, names []string) (err error) { - temporary, err := os.OpenFile(archivePath+".tmp", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) - if err != nil { - return fmt.Errorf("create %s: %w", archivePath, err) - } - defer func() { - if err != nil { - err = errors.Join(err, os.Remove(temporary.Name())) - } - }() - zipWriter := zip.NewWriter(temporary) - for _, name := range names { - if err := addZipFile(zipWriter, filepath.Join(dir, name), name); err != nil { - return errors.Join(fmt.Errorf("add %s: %w", name, err), zipWriter.Close(), temporary.Close()) - } - } - if err := zipWriter.Close(); err != nil { - return errors.Join(fmt.Errorf("finish %s: %w", archivePath, err), temporary.Close()) - } - if err := temporary.Close(); err != nil { - return fmt.Errorf("finish %s: %w", archivePath, err) - } - if err := os.Rename(temporary.Name(), archivePath); err != nil { - return fmt.Errorf("move zip into place: %w", err) - } - return nil -} - -func addZipFile(zipWriter *zip.Writer, path, name string) error { - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - entryWriter, err := zipWriter.Create(name) - if err != nil { - return err - } - _, err = io.Copy(entryWriter, file) - return err -} - func (w *Writer) open(dataCategory category.Category) (*categoryFile, error) { if existing, ok := w.files[dataCategory]; ok { return existing, nil diff --git a/internal/snapshot/zip.go b/internal/snapshot/zip.go index 1b22450..c0e2c8f 100644 --- a/internal/snapshot/zip.go +++ b/internal/snapshot/zip.go @@ -9,113 +9,30 @@ import ( "os" "path/filepath" "strings" + + "github.com/moond4rk/hackbrowserdata/internal/zipfile" ) -// Zip writes to archivePath through a temp file beside it, so a failed archive leaves no partial file. -func (d *Dir) Zip(archivePath string) (err error) { - target, existing, err := zipTarget(archivePath) - if err != nil { - return err - } - temporary, err := createBeside(target) - if err != nil { - return err - } - defer func() { - if err != nil { - os.Remove(temporary.Name()) - } - }() - - if err := writeZip(temporary, d.path); err != nil { - return errors.Join(err, temporary.Close()) - } - if existing != nil { - if err := temporary.Chmod(existing.Mode().Perm()); err != nil { - return errors.Join(fmt.Errorf("keep the mode of %s: %w", archivePath, err), temporary.Close()) - } - } - if err := temporary.Close(); err != nil { - return fmt.Errorf("close zip %s: %w", temporary.Name(), err) - } - if err := os.Rename(temporary.Name(), target); err != nil { - return fmt.Errorf("move zip into place: %w", err) - } - return nil -} - -// zipTarget follows a symlinked archivePath, so the replaced archive keeps the link and the mode os.Create would keep. -func zipTarget(archivePath string) (string, fs.FileInfo, error) { - target := archivePath - if resolved, err := filepath.EvalSymlinks(archivePath); err == nil { - target = resolved - } - info, err := os.Stat(target) - if errors.Is(err, fs.ErrNotExist) { - return target, nil, nil - } - if err != nil { - return "", nil, fmt.Errorf("create %s: %w", archivePath, err) - } - if info.IsDir() { - return "", nil, fmt.Errorf("create %s: is a directory", archivePath) - } - return target, info, nil -} - -// createBeside keeps os.Create's umask-governed mode for a new archive, which os.CreateTemp would force to 0600. -func createBeside(target string) (*os.File, error) { - dir, base := filepath.Split(target) - for i := 0; i < 100; i++ { - name := filepath.Join(dir, fmt.Sprintf("%s.%d-%d.tmp", base, os.Getpid(), i)) - file, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o666) - if errors.Is(err, fs.ErrExist) { - continue - } - if err != nil { - return nil, fmt.Errorf("create %s: %w", target, err) - } - return file, nil - } - return nil, fmt.Errorf("create %s: no free temp name beside it", target) -} - -func writeZip(writer io.Writer, root string) error { - zipWriter := zip.NewWriter(writer) - walkErr := filepath.WalkDir(root, func(walkedPath string, entry fs.DirEntry, err error) error { +func (d *Dir) Zip(archivePath string) error { + var names []string + walkErr := filepath.WalkDir(d.path, func(walkedPath string, entry fs.DirEntry, err error) error { if err != nil { return err } if entry.IsDir() { return nil } - relativePath, err := filepath.Rel(root, walkedPath) + relativePath, err := filepath.Rel(d.path, walkedPath) if err != nil { return err } - return addZipEntry(zipWriter, walkedPath, filepath.ToSlash(relativePath)) + names = append(names, filepath.ToSlash(relativePath)) + return nil }) if walkErr != nil { - return errors.Join(fmt.Errorf("zip %s: %w", root, walkErr), zipWriter.Close()) + return fmt.Errorf("zip %s: %w", d.path, walkErr) } - if err := zipWriter.Close(); err != nil { - return fmt.Errorf("close zip: %w", err) - } - return nil -} - -func addZipEntry(zipWriter *zip.Writer, path, name string) error { - writer, err := zipWriter.Create(name) - if err != nil { - return err - } - file, err := os.Open(path) - if err != nil { - return err - } - defer file.Close() - _, err = io.Copy(writer, file) - return err + return zipfile.Write(archivePath, d.path, names) } func unzip(archivePath, destDir string) error { diff --git a/internal/snapshot/zip_test.go b/internal/snapshot/zip_test.go index 597050d..48a2836 100644 --- a/internal/snapshot/zip_test.go +++ b/internal/snapshot/zip_test.go @@ -3,10 +3,8 @@ package snapshot import ( "archive/zip" "bytes" - "io/fs" "os" "path/filepath" - "runtime" "testing" "github.com/stretchr/testify/assert" @@ -74,73 +72,13 @@ func TestZip_FailureLeavesNoFile(t *testing.T) { assert.Empty(t, entries, "neither the archive nor its temp file may survive a failed zip") } -func TestZip_FailureKeepsAnExistingArchive(t *testing.T) { - out := t.TempDir() - archive := filepath.Join(out, "browser-data.zip") - writeFile(t, archive, []byte("precious")) - - require.Error(t, Open(filepath.Join(t.TempDir(), "missing")).Zip(archive)) - got, err := os.ReadFile(archive) - require.NoError(t, err) - assert.Equal(t, "precious", string(got)) - entries, err := os.ReadDir(out) - require.NoError(t, err) - assert.Len(t, entries, 1, "no temp file may survive a failed zip") -} - -func TestZip_IntoADirectoryFailsBeforeWriting(t *testing.T) { +func TestZip_IntoADirectoryFails(t *testing.T) { out := t.TempDir() require.Error(t, Open(snapshotFixture(t)).Zip(out)) entries, err := os.ReadDir(out) require.NoError(t, err) assert.Empty(t, entries) -} - -func TestZip_ModeMatchesOSCreateAndSurvivesReplacement(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("POSIX permission bits") - } - snapshotRoot := snapshotFixture(t) - out := t.TempDir() - probe, err := os.Create(filepath.Join(out, "probe")) - require.NoError(t, err) - require.NoError(t, probe.Close()) - want, err := os.Stat(probe.Name()) - require.NoError(t, err) - - fresh := filepath.Join(out, "fresh.zip") - require.NoError(t, Open(snapshotRoot).Zip(fresh)) - got, err := os.Stat(fresh) - require.NoError(t, err) - assert.Equal(t, want.Mode().Perm(), got.Mode().Perm(), "a new archive gets the mode os.Create gives a file") - - private := filepath.Join(out, "private.zip") - writeFile(t, private, []byte("old")) - require.NoError(t, os.Chmod(private, 0o600)) - require.NoError(t, Open(snapshotRoot).Zip(private)) - got, err = os.Stat(private) - require.NoError(t, err) - assert.Equal(t, fs.FileMode(0o600), got.Mode().Perm(), "a replaced archive keeps its mode") -} - -func TestZip_WritesThroughASymlinkedArchive(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("creating symlinks needs extra privileges on Windows") - } - out := t.TempDir() - target := filepath.Join(out, "real.zip") - writeFile(t, target, []byte("old")) - link := filepath.Join(out, "link.zip") - require.NoError(t, os.Symlink("real.zip", link)) - - require.NoError(t, Open(snapshotFixture(t)).Zip(link)) - info, err := os.Lstat(link) - require.NoError(t, err) - assert.NotZero(t, info.Mode()&fs.ModeSymlink, "the link stays a link") - zipReader, err := zip.OpenReader(target) - require.NoError(t, err) - defer zipReader.Close() - assert.Len(t, zipReader.File, 1, "the archive lands in the link's target") + assert.NoFileExists(t, out+".tmp") } func snapshotFixture(t *testing.T) string { diff --git a/internal/zipfile/zipfile.go b/internal/zipfile/zipfile.go new file mode 100644 index 0000000..a8810b0 --- /dev/null +++ b/internal/zipfile/zipfile.go @@ -0,0 +1,55 @@ +// Package zipfile writes the zip archives HBD produces: export's --zip and the archive command's. +package zipfile + +import ( + "archive/zip" + "errors" + "fmt" + "io" + "os" + "path/filepath" +) + +// Write renames a finished temp file into place, so archivePath is never a partial zip and a failure keeps the old one. +// Names are slash-separated paths relative to root, and each becomes the entry of that name. +func Write(archivePath, root string, names []string) (err error) { + temporary, err := os.OpenFile(archivePath+".tmp", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) + if err != nil { + return fmt.Errorf("create %s: %w", archivePath, err) + } + defer func() { + if err != nil { + err = errors.Join(err, os.Remove(temporary.Name())) + } + }() + zipWriter := zip.NewWriter(temporary) + for _, name := range names { + if err := addFile(zipWriter, filepath.Join(root, filepath.FromSlash(name)), name); err != nil { + return errors.Join(fmt.Errorf("add %s: %w", name, err), zipWriter.Close(), temporary.Close()) + } + } + if err := zipWriter.Close(); err != nil { + return errors.Join(fmt.Errorf("finish %s: %w", archivePath, err), temporary.Close()) + } + if err := temporary.Close(); err != nil { + return fmt.Errorf("finish %s: %w", archivePath, err) + } + if err := os.Rename(temporary.Name(), archivePath); err != nil { + return fmt.Errorf("move zip into place: %w", err) + } + return nil +} + +func addFile(zipWriter *zip.Writer, path, name string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + entryWriter, err := zipWriter.Create(name) + if err != nil { + return err + } + _, err = io.Copy(entryWriter, file) + return err +} diff --git a/internal/zipfile/zipfile_test.go b/internal/zipfile/zipfile_test.go new file mode 100644 index 0000000..a116e44 --- /dev/null +++ b/internal/zipfile/zipfile_test.go @@ -0,0 +1,71 @@ +package zipfile + +import ( + "archive/zip" + "io" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestWrite_ZipsOnlyTheNamedFiles(t *testing.T) { + root := t.TempDir() + writeFile(t, filepath.Join(root, "chrome", "Default", "History"), "history") + writeFile(t, filepath.Join(root, "notes.txt"), "not named") + archive := filepath.Join(t.TempDir(), "out.zip") + + require.NoError(t, Write(archive, root, []string{"chrome/Default/History"})) + assert.Equal(t, map[string]string{"chrome/Default/History": "history"}, entries(t, archive)) + assert.NoFileExists(t, archive+".tmp") +} + +func TestWrite_FailureKeepsAnExistingArchive(t *testing.T) { + out := t.TempDir() + archive := filepath.Join(out, "out.zip") + writeFile(t, archive, "precious") + + require.Error(t, Write(archive, t.TempDir(), []string{"missing"})) + got, err := os.ReadFile(archive) + require.NoError(t, err) + assert.Equal(t, "precious", string(got)) + assert.NoFileExists(t, archive+".tmp", "no temp file may survive a failed zip") +} + +// TestWrite_IsOwnerOnly keeps an archive as private as the browser files and records it holds. +func TestWrite_IsOwnerOnly(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows has no mode bits to check") + } + archive := filepath.Join(t.TempDir(), "out.zip") + require.NoError(t, Write(archive, t.TempDir(), nil)) + info, err := os.Stat(archive) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) +} + +func entries(t *testing.T, archive string) map[string]string { + t.Helper() + zipReader, err := zip.OpenReader(archive) + require.NoError(t, err) + defer zipReader.Close() + contents := make(map[string]string, len(zipReader.File)) + for _, zipFile := range zipReader.File { + entryReader, err := zipFile.Open() + require.NoError(t, err) + data, err := io.ReadAll(entryReader) + require.NoError(t, err) + require.NoError(t, entryReader.Close()) + contents[zipFile.Name] = string(data) + } + return contents +} + +func writeFile(t *testing.T, path, data string) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(data), 0o600)) +} diff --git a/rfcs/002-package-layout.md b/rfcs/002-package-layout.md index e1b231b..42a950d 100644 --- a/rfcs/002-package-layout.md +++ b/rfcs/002-package-layout.md @@ -19,6 +19,7 @@ internal/ crypto/ pure decrypt primitives over bytes (AES-CBC/GCM, 3DES, PBKDF2, ASN.1 PBE) snapshot/ snapshot Dir and Snapshot, Capture, zip transport, the copier export/ Writer; csv / json / cookie-editor encoders; --zip packaging + zipfile/ the one zip writer, for --zip and archive: a temp file renamed into place sqlitex/ thin modernc.org/sqlite helpers (open read-only by path, query) timeconv/ browser epoch conversions (Chromium/WebKit, Unix, Firefox, Core Data) winapi/ Windows only: syscall wrappers, DPAPI, locked-file copy, executable lookup