2 NNCP -- Node to Node copy, utilities for store-and-forward data exchange
3 Copyright (C) 2016-2023 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/>.
34 NoSync = os.Getenv(CfgNoSync) != ""
37 func TempFile(dir, prefix string) (*os.File, error) {
38 // Assume that probability of suffix collision is negligible
39 suffix := strconv.FormatInt(time.Now().UnixNano()+int64(os.Getpid()), 16)
40 name := filepath.Join(dir, "nncp"+prefix+suffix)
41 return os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, os.FileMode(0666))
44 func (ctx *Ctx) NewTmpFile() (*os.File, error) {
45 jobsPath := filepath.Join(ctx.Spool, "tmp")
46 if err := ensureDir(jobsPath); err != nil {
49 fd, err := TempFile(jobsPath, "")
51 ctx.LogD("tmp", LEs{{"Src", fd.Name()}}, func(les LEs) string {
52 return "Temporary file created: " + fd.Name()
58 type TmpFileWHash struct {
65 func (ctx *Ctx) NewTmpFileWHash() (*TmpFileWHash, error) {
66 tmp, err := ctx.NewTmpFile()
72 W: bufio.NewWriter(io.MultiWriter(hsh, tmp)),
79 func (tmp *TmpFileWHash) Cancel() {
82 os.Remove(tmp.Fd.Name())
85 func DirSync(dirPath string) error {
89 fd, err := os.Open(dirPath)
101 func (tmp *TmpFileWHash) Checksum() string {
102 return Base32Codec.EncodeToString(tmp.Hsh.Sum(nil))
105 func (tmp *TmpFileWHash) Commit(dir string) error {
107 if err = ensureDir(dir); err != nil {
110 if err = tmp.W.Flush(); err != nil {
115 if err = tmp.Fd.Sync(); err != nil {
120 if err = tmp.Fd.Close(); err != nil {
123 checksum := tmp.Checksum()
126 LEs{{"Src", tmp.Fd.Name()}, {"Dst", checksum}},
127 func(les LEs) string {
128 return fmt.Sprintf("Temporary file: %s -> %s", tmp.Fd.Name(), checksum)
131 if err = os.Rename(tmp.Fd.Name(), filepath.Join(dir, checksum)); err != nil {