-
Notifications
You must be signed in to change notification settings - Fork 6
/
handle.go
120 lines (104 loc) · 2.26 KB
/
handle.go
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"fmt"
"os"
"syscall"
"bazil.org/fuse"
)
var (
handleIDGeneratorChan <-chan uint64
)
func handleIDGenerator() <-chan uint64 {
outChan := make(chan uint64)
go func() {
for nextId := uint64(1); ; nextId++ {
outChan <- nextId
}
}()
return outChan
}
func newHandleID() uint64 {
return <-handleIDGeneratorChan
}
func init() {
handleIDGeneratorChan = handleIDGenerator()
}
type Handle struct {
file *os.File
handleID uint64
flags fuse.OpenFlags
blksize uint32
}
func NewHandle() *Handle {
return &Handle{}
}
func (h Handle) String() string {
return fmt.Sprintf("%d", h.handleID)
}
func (h *Handle) isOpen() bool {
return h.file != nil
}
func (h *Handle) doOpen(path string, flags fuse.OpenFlags) (uint64, error) {
if h.isOpen() {
return 0, nil
}
mode := int(flags & fuse.OpenAccessModeMask)
perm := os.FileMode(flags).Perm()
file, err := os.OpenFile(path, mode, perm)
if err != nil {
return 0, osErrorToFuseError(err)
}
blksize, err := getBlkSize(file)
if err != nil {
return 0, err
}
h.file, h.flags, h.handleID, h.blksize = file, flags, newHandleID(), blksize
return h.getFileSize()
}
func (h *Handle) doCreate(path string, flags fuse.OpenFlags, mode os.FileMode) error {
if h.isOpen() {
return nil
}
file, err := os.OpenFile(path, int(flags), mode)
if err != nil {
return osErrorToFuseError(err)
}
blksize, err := getBlkSize(file)
if err != nil {
return err
}
h.file, h.flags, h.handleID, h.blksize = file, flags, newHandleID(), blksize
return nil
}
func (h *Handle) getFileSize() (uint64, error) {
var stat syscall.Stat_t
if err := syscall.Fstat(int(h.file.Fd()), &stat); err != nil {
return 0, osErrorToFuseError(err)
}
return uint64(stat.Size), nil
}
func (h *Handle) doClose() error {
if h.isOpen() {
file := h.file
h.file = nil
h.handleID = 0
return osErrorToFuseError(file.Close())
}
return nil
}
func (h *Handle) doSync() (uint64, error) {
if !h.isOpen() {
return 0, nil
}
if err := h.file.Sync(); err != nil {
return 0, osErrorToFuseError(err)
}
return h.getFileSize()
}
func getBlkSize(f *os.File) (uint32, error) {
var stat syscall.Stat_t
if err := syscall.Fstat(int(f.Fd()), &stat); err != nil {
return 0, osErrorToFuseError(err)
}
return uint32(stat.Blksize), nil
}