maddy

Fork https://github.com/foxcpp/maddy

git clone git://git.lin.moe/go/maddy.git

 1/*
 2Maddy Mail Server - Composable all-in-one email server.
 3Copyright © 2019-2020 Max Mazurov <fox.cpp@disroot.org>, Maddy Mail Server contributors
 4
 5This program is free software: you can redistribute it and/or modify
 6it under the terms of the GNU General Public License as published by
 7the Free Software Foundation, either version 3 of the License, or
 8(at your option) any later version.
 9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program.  If not, see <https://www.gnu.org/licenses/>.
17*/
18
19package buffer
20
21import (
22	"crypto/rand"
23	"encoding/hex"
24	"fmt"
25	"io"
26	"os"
27	"path/filepath"
28)
29
30// FileBuffer implements Buffer interface using file system.
31type FileBuffer struct {
32	Path string
33
34	// LenHint is the size of the stored blob. It can
35	// be set to avoid the need to call os.Stat in the
36	// Len() method.
37	LenHint int
38}
39
40func (fb FileBuffer) Open() (io.ReadCloser, error) {
41	return os.Open(fb.Path)
42}
43
44func (fb FileBuffer) Len() int {
45	if fb.LenHint != 0 {
46		return fb.LenHint
47	}
48
49	info, err := os.Stat(fb.Path)
50	if err != nil {
51		// Any access to the file will probably fail too.  So we can't return a
52		// sensible value.
53		return 0
54	}
55
56	return int(info.Size())
57}
58
59func (fb FileBuffer) Remove() error {
60	return os.Remove(fb.Path)
61}
62
63// BufferInFile is a convenience function which creates FileBuffer with underlying
64// file created in the specified directory with the random name.
65func BufferInFile(r io.Reader, dir string) (Buffer, error) {
66	// It is assumed that PRNG is initialized somewhere during program startup.
67	nameBytes := make([]byte, 32)
68	_, err := rand.Read(nameBytes)
69	if err != nil {
70		return nil, fmt.Errorf("buffer: failed to generate randomness for file name: %v", err)
71	}
72	path := filepath.Join(dir, hex.EncodeToString(nameBytes))
73	f, err := os.Create(path)
74	if err != nil {
75		return nil, fmt.Errorf("buffer: failed to create file: %v", err)
76	}
77	if _, err = io.Copy(f, r); err != nil {
78		return nil, fmt.Errorf("buffer: failed to write file: %v", err)
79	}
80	if err := f.Close(); err != nil {
81		return nil, fmt.Errorf("buffer: failed to close file: %v", err)
82	}
83
84	return FileBuffer{Path: path}, nil
85}