X-Git-Url: https://ruderich.org/simon/gitweb/?p=nsscash%2Fnsscash.git;a=blobdiff_plain;f=file.go;h=3884bba8b6ae3c4f0e6d86f26d796fd5fcac0952;hp=07ac987cbec6d9fb128cd746e467461750f44882;hb=HEAD;hpb=526f6f1db39bde8ca1f7684225a3983634bddafe diff --git a/file.go b/file.go index 07ac987..3884bba 100644 --- a/file.go +++ b/file.go @@ -1,6 +1,6 @@ // Download and write files atomically to the file system -// Copyright (C) 2019 Simon Ruderich +// Copyright (C) 2019-2021 Simon Ruderich // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by @@ -30,6 +30,7 @@ import ( "syscall" "time" + "github.com/google/renameio" "github.com/pkg/errors" ) @@ -89,11 +90,17 @@ func fetchFile(file *File, state *State) error { t = zero // force download } - status, body, err := fetchIfModified(file.Url, file.CA, &t) + oldT := t + status, body, err := fetchIfModified(file.Url, + file.Username, file.Password, file.CA, &t) if err != nil { return err } if status == http.StatusNotModified { + if oldT.IsZero() { + return fmt.Errorf("status code 304 " + + "but did not send If-Modified-Since") + } log.Printf("%q -> %q: not modified", file.Url, file.Path) return nil } @@ -158,18 +165,11 @@ func deployFile(file *File) error { return fmt.Errorf("refusing to write empty file") } - // Write the file in an atomic fashion by creating a temporary file - // and renaming it over the target file - - dir := filepath.Dir(file.Path) - name := filepath.Base(file.Path) - - f, err := ioutil.TempFile(dir, "tmp-"+name+"-") + f, err := renameio.TempFile(filepath.Dir(file.Path), file.Path) if err != nil { return err } - defer os.Remove(f.Name()) - defer f.Close() + defer f.Cleanup() // Apply permissions/user/group from the target file but remove the // write permissions to discourage manual modifications, use Stat @@ -198,9 +198,9 @@ func deployFile(file *File) error { if err != nil { return err } - err = f.Sync() + err = f.CloseAtomicallyReplace() if err != nil { return err } - return os.Rename(f.Name(), file.Path) + return syncPath(filepath.Dir(file.Path)) }