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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
|
package main
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/signal"
"path/filepath"
"sort"
"sync"
"syscall"
"github.com/hanwen/go-fuse/v2/fs"
"github.com/hanwen/go-fuse/v2/fuse"
"github.com/rfjakob/gocryptfs/v2/internal/exitcodes"
"github.com/rfjakob/gocryptfs/v2/internal/fusefrontend"
"github.com/rfjakob/gocryptfs/v2/internal/tlog"
)
// fsckObj walks the filesystem by calling the fusefrontend node operations
// directly, without mounting it via FUSE.
type fsckObj struct {
// List of corrupt files
corruptList []string
// List of skipped files
skippedList []string
// Protects corruptList
listLock sync.Mutex
// Inode numbers of hard-linked files (Nlink > 1) that we have already checked
seenInodes map[uint64]struct{}
// abort the running fsck operation? Checked in a few long-running loops.
abort bool
}
func runsAsRoot() bool {
return syscall.Geteuid() == 0
}
func (ck *fsckObj) markCorrupt(path string) {
ck.listLock.Lock()
ck.corruptList = append(ck.corruptList, path)
ck.listLock.Unlock()
}
func (ck *fsckObj) markSkipped(path string) {
ck.listLock.Lock()
ck.skippedList = append(ck.skippedList, path)
ck.listLock.Unlock()
}
// markError marks relPath as skipped if err is a permission error and we
// are not root, and as corrupt otherwise.
func (ck *fsckObj) markError(relPath string, err error) {
if errors.Is(err, os.ErrPermission) && !runsAsRoot() {
ck.markSkipped(relPath)
} else {
ck.markCorrupt(relPath)
}
}
// Recursively check dir for corruption
func (ck *fsckObj) dir(inode *fs.Inode, relPath string) {
tlog.Debug.Printf("ck.dir %q\n", relPath)
ck.xattrs(inode, relPath)
// Catch corrupt entries that Readdirent transparently skips
ctx := fusefrontend.WithCorruptionReporter(context.Background(), func(item string) {
fmt.Printf("fsck: corrupt entry in dir %q: %q\n", relPath, item)
ck.markCorrupt(filepath.Join(relPath, item))
})
entries, errno := ck.readdir(ctx, inode, relPath)
if errno != 0 {
ck.markError(relPath, errno)
return
}
// Sort alphabetically to make fsck runs deterministic
sort.Strings(entries)
for _, entry := range entries {
if ck.abort {
return
}
nextPath := filepath.Join(relPath, entry)
var out fuse.EntryOut
child, errno := inode.Operations().(fs.NodeLookuper).Lookup(context.Background(), entry, &out)
if errno != 0 {
fmt.Printf("fsck: error looking up %q: %v\n", nextPath, errno)
ck.markError(nextPath, errno)
continue
}
// Node operations find the backing file via the path from the root,
// so the child must be part of the tree.
inode.AddChild(entry, child, true)
filetype := out.Attr.Mode & syscall.S_IFMT
switch filetype {
case syscall.S_IFDIR:
ck.dir(child, nextPath)
case syscall.S_IFREG:
ck.file(child, nextPath, &out.Attr)
case syscall.S_IFLNK:
ck.symlink(child, nextPath)
case syscall.S_IFIFO, syscall.S_IFSOCK, syscall.S_IFBLK, syscall.S_IFCHR:
// nothing to check
default:
fmt.Printf("fsck: unhandled file type %x\n", filetype)
}
// Drop the child (and its subtree) again so memory usage does not grow
// with the size of the filesystem.
inode.RmChild(entry)
}
}
// readdir returns the names of all entries in the directory, without "." and "..".
func (ck *fsckObj) readdir(ctx context.Context, inode *fs.Inode, relPath string) (entries []string, errno syscall.Errno) {
fh, _, errno := inode.Operations().(fs.NodeOpendirHandler).OpendirHandle(ctx, syscall.O_RDONLY)
if errno != 0 {
fmt.Printf("fsck: error opening dir %q: %v\n", relPath, errno)
return nil, errno
}
defer fh.(fs.FileReleasedirer).Releasedir(ctx, 0)
for {
entry, errno := fh.(fs.FileReaddirenter).Readdirent(ctx)
if errno != 0 {
fmt.Printf("fsck: error reading dir %q: %v\n", relPath, errno)
return nil, errno
}
if entry == nil {
return entries, 0
}
if entry.Name == "." || entry.Name == ".." {
continue
}
entries = append(entries, entry.Name)
}
}
func (ck *fsckObj) symlink(inode *fs.Inode, relPath string) {
_, errno := inode.Operations().(fs.NodeReadlinker).Readlink(context.Background())
if errno != 0 {
ck.markCorrupt(relPath)
fmt.Printf("fsck: error reading symlink %q: %v\n", relPath, errno)
}
}
// Check file for corruption
func (ck *fsckObj) file(inode *fs.Inode, relPath string, attr *fuse.Attr) {
tlog.Debug.Printf("ck.file %q\n", relPath)
if attr.Nlink > 1 {
// Due to hard links, we may have already checked this file.
if _, ok := ck.seenInodes[attr.Ino]; ok {
tlog.Debug.Printf("ck.file : skipping %q (inode number %d already seen)\n", relPath, attr.Ino)
return
}
ck.seenInodes[attr.Ino] = struct{}{}
}
ck.xattrs(inode, relPath)
fh, _, errno := inode.Operations().(fs.NodeOpener).Open(context.Background(), syscall.O_RDONLY)
if errno != 0 {
fmt.Printf("fsck: error opening file %q: %v\n", relPath, errno)
ck.markError(relPath, errno)
return
}
defer fh.(fs.FileReleaser).Release(context.Background())
reader := fh.(fs.FileReader)
// 128 kiB of zeros
allZero := make([]byte, fuse.MAX_KERNEL_WRITE)
buf := make([]byte, fuse.MAX_KERNEL_WRITE)
var off int64
// Read() through the whole file and catch transparently mitigated corruptions
ctx := fusefrontend.WithCorruptionReporter(context.Background(), func(item string) {
fmt.Printf("fsck: corrupt file %q (inode %s)\n", relPath, item)
ck.markCorrupt(relPath)
})
for {
if ck.abort {
return
}
tlog.Debug.Printf("ck.file: read %d bytes from offset %d\n", len(buf), off)
res, errno := reader.Read(ctx, buf, off)
if errno != 0 {
ck.markCorrupt(relPath)
fmt.Printf("fsck: error reading file %q (inum %d): %v\n", relPath, attr.Ino, errno)
return
}
data, status := res.Bytes(buf)
if !status.Ok() {
ck.markCorrupt(relPath)
fmt.Printf("fsck: error reading file %q (inum %d): %v\n", relPath, attr.Ino, status)
return
}
// Short read means EOF
if len(data) < len(buf) {
return
}
off += int64(len(data))
// If we seem to be in the middle of a file hole, try to skip to the next
// data section.
if bytes.Equal(data, allZero) {
tlog.Debug.Printf("ck.file: trying to skip file hole\n")
const SEEK_DATA = 3
nextOff, errno := fh.(fs.FileLseeker).Lseek(context.Background(), uint64(off), SEEK_DATA)
if errno == syscall.ENXIO {
// No more data after `off`
return
}
if errno == 0 {
off = int64(nextOff)
}
}
}
}
// Check xattrs on file/dir
func (ck *fsckObj) xattrs(inode *fs.Inode, relPath string) {
ops := inode.Operations()
// Run Listxattr() and catch transparently mitigated corruptions
ctx := fusefrontend.WithCorruptionReporter(context.Background(), func(item string) {
fmt.Printf("fsck: corrupt xattr name on file %q: %q\n", relPath, item)
ck.markCorrupt(relPath + " xattr:" + item)
})
list, errno := getBuf(func(dest []byte) (uint32, syscall.Errno) {
return ops.(fs.NodeListxattrer).Listxattr(ctx, dest)
})
if errno != 0 {
fmt.Printf("fsck: error listing xattrs on %q: %v\n", relPath, errno)
ck.markCorrupt(relPath)
return
}
// Try to read all xattr values
for _, a := range bytes.Split(list, []byte{0}) {
if len(a) == 0 {
continue
}
_, errno := getBuf(func(dest []byte) (uint32, syscall.Errno) {
return ops.(fs.NodeGetxattrer).Getxattr(context.Background(), string(a), dest)
})
if errno != 0 {
fmt.Printf("fsck: error reading xattr %q from %q: %v\n", a, relPath, errno)
ck.markError(relPath, errno)
}
}
}
// getBuf calls `f` with a growing buffer until it does not return ERANGE.
// Used for Listxattr and Getxattr.
func getBuf(f func(dest []byte) (uint32, syscall.Errno)) ([]byte, syscall.Errno) {
buf := make([]byte, 1024)
for {
sz, errno := f(buf)
if errno == syscall.ERANGE && int(sz) > len(buf) {
buf = make([]byte, sz)
continue
}
if errno != 0 {
return nil, errno
}
return buf[:sz], 0
}
}
// entrypoint from main()
func fsck(args *argContainer) (exitcode int) {
if args.reverse {
tlog.Fatal.Printf("Running -fsck with -reverse is not supported")
os.Exit(exitcodes.Usage)
}
args.allow_other = false
args.ro = true
pfs, wipeKeys := initFuseFrontend(args)
rn := pfs.(*fusefrontend.RootNode)
// We never mount the filesystem, but NewNodeFS initializes the root
// inode, which is required for the node operations to work.
_ = fs.NewNodeFS(rn, nil)
ck := fsckObj{
seenInodes: make(map[uint64]struct{}),
}
// Handle SIGINT & SIGTERM
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
signal.Notify(ch, syscall.SIGTERM)
go func() {
<-ch
ck.abort = true
}()
// Recursively check the root dir
tlog.Info.Println(tlog.ColorGreen + "Checking filesystem..." + tlog.ColorReset)
ck.dir(rn.EmbeddedInode(), "")
// Report results
wipeKeys()
if ck.abort {
tlog.Info.Printf("fsck: aborted")
return exitcodes.Other
}
if len(ck.corruptList) == 0 && len(ck.skippedList) == 0 {
tlog.Info.Printf("fsck summary: no problems found\n")
return 0
}
if len(ck.skippedList) > 0 {
tlog.Warn.Printf("fsck: re-run this program as root to check all files!\n")
}
fmt.Printf("fsck summary: %d corrupt files, %d files skipped\n", len(ck.corruptList), len(ck.skippedList))
return exitcodes.FsckErrors
}
|