2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2021 Sergey Matveev <stargrave@stargrave.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
30 "golang.org/x/crypto/blake2b"
33 func TempFile(dir, prefix string) (*os.File, error) {
34 // Assume that probability of suffix collision is negligible
35 suffix := strconv.FormatInt(time.Now().UnixNano()+int64(os.Getpid()), 16)
36 name := filepath.Join(dir, "nncp"+prefix+suffix)
37 return os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, os.FileMode(0666))
40 func (ctx *Ctx) NewTmpFile() (*os.File, error) {
41 jobsPath := filepath.Join(ctx.Spool, "tmp")
43 if err = os.MkdirAll(jobsPath, os.FileMode(0777)); err != nil {
46 fd, err := TempFile(jobsPath, "")
48 ctx.LogD("tmp", LEs{{"Src", fd.Name()}}, func(les LEs) string {
49 return "Temporary file created: " + fd.Name()
55 type TmpFileWHash struct {
62 func (ctx *Ctx) NewTmpFileWHash() (*TmpFileWHash, error) {
63 tmp, err := ctx.NewTmpFile()
67 hsh, err := blake2b.New256(nil)
72 W: bufio.NewWriter(io.MultiWriter(hsh, tmp)),
79 func (tmp *TmpFileWHash) Cancel() {
80 tmp.Fd.Truncate(0) // #nosec G104
81 tmp.Fd.Close() // #nosec G104
82 os.Remove(tmp.Fd.Name()) // #nosec G104
85 func DirSync(dirPath string) error {
86 fd, err := os.Open(dirPath)
92 fd.Close() // #nosec G104
98 func (tmp *TmpFileWHash) Checksum() string {
99 return Base32Codec.EncodeToString(tmp.Hsh.Sum(nil))
102 func (tmp *TmpFileWHash) Commit(dir string) error {
104 if err = os.MkdirAll(dir, os.FileMode(0777)); err != nil {
107 if err = tmp.W.Flush(); err != nil {
108 tmp.Fd.Close() // #nosec G104
111 if err = tmp.Fd.Sync(); err != nil {
112 tmp.Fd.Close() // #nosec G104
115 if err = tmp.Fd.Close(); err != nil {
118 checksum := tmp.Checksum()
121 LEs{{"Src", tmp.Fd.Name()}, {"Dst", checksum}},
122 func(les LEs) string {
123 return fmt.Sprintf("Temporary file: %s -> %s", tmp.Fd.Name(), checksum)
126 if err = os.Rename(tmp.Fd.Name(), filepath.Join(dir, checksum)); err != nil {