aboutsummaryrefslogtreecommitdiff
path: root/internal/fusefrontend_reverse/file.go
blob: 55f5f80312e85e2da8f510d093cecc473feca30a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package fusefrontend_reverse

import (
	"bytes"
	"context"
	"os"
	"syscall"

	"github.com/hanwen/go-fuse/v2/fs"
	"github.com/hanwen/go-fuse/v2/fuse"

	"github.com/rfjakob/gocryptfs/internal/contentenc"
)

type File struct {
	// Backing FD
	fd *os.File
	// File header (contains the IV)
	header contentenc.FileHeader
	// IV for block 0
	block0IV []byte
	// Content encryption helper
	contentEnc *contentenc.ContentEnc
}

// Read - FUSE call
func (f *File) Read(ctx context.Context, buf []byte, ioff int64) (resultData fuse.ReadResult, errno syscall.Errno) {
	length := uint64(len(buf))
	off := uint64(ioff)
	out := bytes.NewBuffer(buf[:0])
	var header []byte

	// Synthesize file header
	if off < contentenc.HeaderLen {
		header = f.header.Pack()
		// Truncate to requested part
		end := int(off) + len(buf)
		if end > len(header) {
			end = len(header)
		}
		header = header[off:end]
		// Write into output buffer and adjust offsets
		out.Write(header)
		hLen := uint64(len(header))
		off += hLen
		length -= hLen
	}

	// Read actual file data
	if length > 0 {
		fileData, err := f.readBackingFile(off, length)
		if err != nil {
			return nil, fs.ToErrno(err)
		}
		if len(fileData) == 0 {
			// If we could not read any actual data, we also don't want to
			// return the file header. An empty file stays empty in encrypted
			// form.
			return nil, 0
		}
		out.Write(fileData)
	}

	return fuse.ReadResultData(out.Bytes()), 0
}

// Release - FUSE call, close file
func (f *File) Release(context.Context) syscall.Errno {
	return fs.ToErrno(f.fd.Close())
}