aboutsummaryrefslogtreecommitdiff
path: root/internal/fusefrontend/file.go
blob: ffc41c61207ad0f09bb646ca3e5b7f4414b60c71 (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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package fusefrontend

// FUSE operations on file handles

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
	"sync"
	"syscall"
	"time"

	"github.com/hanwen/go-fuse/fuse"
	"github.com/hanwen/go-fuse/fuse/nodefs"

	"github.com/rfjakob/gocryptfs/internal/contentenc"
	"github.com/rfjakob/gocryptfs/internal/openfiletable"
	"github.com/rfjakob/gocryptfs/internal/serialize_reads"
	"github.com/rfjakob/gocryptfs/internal/stupidgcm"
	"github.com/rfjakob/gocryptfs/internal/syscallcompat"
	"github.com/rfjakob/gocryptfs/internal/tlog"
)

var _ nodefs.File = &File{} // Verify that interface is implemented.

// File - based on loopbackFile in go-fuse/fuse/nodefs/files.go
type File struct {
	fd *os.File
	// Has Release() already been called on this file? This also means that the
	// wlock entry has been freed, so let's not crash trying to access it.
	// Due to concurrency, Release can overtake other operations. These will
	// return EBADF in that case.
	released bool
	// fdLock prevents the fd to be closed while we are in the middle of
	// an operation.
	// Every FUSE entrypoint should RLock(). The only user of Lock() is
	// Release(), which closes the fd and sets "released" to true.
	fdLock sync.RWMutex
	// Content encryption helper
	contentEnc *contentenc.ContentEnc
	// Device and inode number uniquely identify the backing file
	qIno openfiletable.QIno
	// Entry in the open file table
	fileTableEntry *openfiletable.Entry
	// go-fuse nodefs.loopbackFile
	loopbackFile nodefs.File
	// Store where the last byte was written
	lastWrittenOffset int64
	// The opCount is used to judge whether "lastWrittenOffset" is still
	// guaranteed to be correct.
	lastOpCount uint64
	// Parent filesystem
	fs *FS
	// We embed a nodefs.NewDefaultFile() that returns ENOSYS for every operation we
	// have not implemented. This prevents build breakage when the go-fuse library
	// adds new methods to the nodefs.File interface.
	nodefs.File
}

// NewFile returns a new go-fuse File instance.
func NewFile(fd *os.File, fs *FS) (*File, fuse.Status) {
	var st syscall.Stat_t
	err := syscall.Fstat(int(fd.Fd()), &st)
	if err != nil {
		tlog.Warn.Printf("NewFile: Fstat on fd %d failed: %v\n", fd.Fd(), err)
		return nil, fuse.ToStatus(err)
	}
	qi := openfiletable.QInoFromStat(&st)
	e := openfiletable.Register(qi)

	return &File{
		fd:             fd,
		contentEnc:     fs.contentEnc,
		qIno:           qi,
		fileTableEntry: e,
		loopbackFile:   nodefs.NewLoopbackFile(fd),
		fs:             fs,
		File:           nodefs.NewDefaultFile(),
	}, fuse.OK
}

// intFd - return the backing file descriptor as an integer. Used for debug
// messages.
func (f *File) intFd() int {
	return int(f.fd.Fd())
}

// readFileID loads the file header from disk and extracts the file ID.
// Returns io.EOF if the file is empty.
func (f *File) readFileID() ([]byte, error) {
	// We read +1 byte to determine if the file has actual content
	// and not only the header. A header-only file will be considered empty.
	// This makes File ID poisoning more difficult.
	readLen := contentenc.HeaderLen + 1
	buf := make([]byte, readLen)
	n, err := f.fd.ReadAt(buf, 0)
	if err != nil {
		if err == io.EOF && n != 0 {
			tlog.Warn.Printf("readFileID %d: incomplete file, got %d instead of %d bytes",
				f.qIno.Ino, n, readLen)
			f.fs.reportMitigatedCorruption(fmt.Sprint(f.qIno.Ino))
		}
		return nil, err
	}
	buf = buf[:contentenc.HeaderLen]
	h, err := contentenc.ParseHeader(buf)
	if err != nil {
		return nil, err
	}
	return h.ID, nil
}

// createHeader creates a new random header and writes it to disk.
// Returns the new file ID.
// The caller must hold fileIDLock.Lock().
func (f *File) createHeader() (fileID []byte, err error) {
	h := contentenc.RandomHeader()
	buf := h.Pack()
	// Prevent partially written (=corrupt) header by preallocating the space beforehand
	if !f.fs.args.NoPrealloc {
		err = syscallcompat.EnospcPrealloc(int(f.fd.Fd()), 0, contentenc.HeaderLen)
		if err != nil {
			if !syscallcompat.IsENOSPC(err) {
				tlog.Warn.Printf("ino%d: createHeader: prealloc failed: %s\n", f.qIno.Ino, err.Error())
			}
			return nil, err
		}
	}
	// Actually write header
	_, err = f.fd.WriteAt(buf, 0)
	if err != nil {
		return nil, err
	}
	return h.ID, err
}

// doRead - read "length" plaintext bytes from plaintext offset "off" and append
// to "dst".
// Arguments "length" and "off" do not have to be block-aligned.
//
// doRead reads the corresponding ciphertext blocks from disk, decrypts them and
// returns the requested part of the plaintext.
//
// Called by Read() for normal reading,
// by Write() and Truncate() via doWrite() for Read-Modify-Write.
//
// doWrite() uses nolock=true because it makes sure the ID is in the cache and
// HeaderLock is locked before calling doRead.
func (f *File) doRead(dst []byte, off uint64, length uint64, nolock bool) ([]byte, fuse.Status) {
	if !nolock {
		// Make sure we have the file ID.
		f.fileTableEntry.HeaderLock.RLock()
		if f.fileTableEntry.ID == nil {
			f.fileTableEntry.HeaderLock.RUnlock()
			// Yes, somebody else may take the lock before we can. This will get
			// the header read twice, but causes no harm otherwise.
			f.fileTableEntry.HeaderLock.Lock()
			tmpID, err := f.readFileID()
			if err == io.EOF {
				f.fileTableEntry.HeaderLock.Unlock()
				return nil, fuse.OK
			}
			if err != nil {
				f.fileTableEntry.HeaderLock.Unlock()
				tlog.Warn.Printf("doRead %d: corrupt header: %v", f.qIno.Ino, err)
				return nil, fuse.EIO
			}
			f.fileTableEntry.ID = tmpID
			// Downgrade the lock.
			f.fileTableEntry.HeaderLock.Unlock()
			// The file ID may change in here. This does no harm because we
			// re-read it after the RLock().
			f.fileTableEntry.HeaderLock.RLock()
		}
	}
	fileID := f.fileTableEntry.ID
	if fileID == nil {
		log.Panicf("filedID=%v, nolock=%v", fileID, nolock)
	}
	// Read the backing ciphertext in one go
	blocks := f.contentEnc.ExplodePlainRange(off, length)
	alignedOffset, alignedLength := blocks[0].JointCiphertextRange(blocks)
	skip := blocks[0].Skip
	tlog.Debug.Printf("doRead: off=%d len=%d -> off=%d len=%d skip=%d\n",
		off, length, alignedOffset, alignedLength, skip)

	ciphertext := f.fs.contentEnc.CReqPool.Get()
	ciphertext = ciphertext[:int(alignedLength)]
	n, err := f.fd.ReadAt(ciphertext, int64(alignedOffset))
	// We don't care if the file ID changes after we have read the data. Drop the lock.
	if !nolock {
		f.fileTableEntry.HeaderLock.RUnlock()
	}
	if err != nil && err != io.EOF {
		tlog.Warn.Printf("read: ReadAt: %s", err.Error())
		return nil, fuse.ToStatus(err)
	}
	// The ReadAt came back empty. We can skip all the decryption and return early.
	if n == 0 {
		f.fs.contentEnc.CReqPool.Put(ciphertext)
		return dst, fuse.OK
	}
	// Truncate ciphertext buffer down to actually read bytes
	ciphertext = ciphertext[0:n]

	firstBlockNo := blocks[0].BlockNo
	tlog.Debug.Printf("ReadAt offset=%d bytes (%d blocks), want=%d, got=%d", alignedOffset, firstBlockNo, alignedLength, n)

	// Decrypt it
	plaintext, err := f.contentEnc.DecryptBlocks(ciphertext, firstBlockNo, fileID)
	f.fs.contentEnc.CReqPool.Put(ciphertext)
	if err != nil {
		if f.fs.args.ForceDecode && err == stupidgcm.ErrAuth {
			// We do not have the information which block was corrupt here anymore,
			// but DecryptBlocks() has already logged it anyway.
			tlog.Warn.Printf("doRead %d: off=%d len=%d: returning corrupt data due to forcedecode",
				f.qIno.Ino, off, length)
		} else {
			curruptBlockNo := firstBlockNo + f.contentEnc.PlainOffToBlockNo(uint64(len(plaintext)))
			tlog.Warn.Printf("doRead %d: corrupt block #%d: %v", f.qIno.Ino, curruptBlockNo, err)
			return nil, fuse.EIO
		}
	}

	// Crop down to the relevant part
	var out []byte
	lenHave := len(plaintext)
	lenWant := int(skip + length)
	if lenHave > lenWant {
		out = plaintext[skip:lenWant]
	} else if lenHave > int(skip) {
		out = plaintext[skip:lenHave]
	}
	// else: out stays empty, file was smaller than the requested offset

	out = append(dst, out...)
	f.fs.contentEnc.PReqPool.Put(plaintext)

	return out, fuse.OK
}

// Read - FUSE call
func (f *File) Read(buf []byte, off int64) (resultData fuse.ReadResult, code fuse.Status) {
	if len(buf) > fuse.MAX_KERNEL_WRITE {
		// This would crash us due to our fixed-size buffer pool
		tlog.Warn.Printf("Read: rejecting oversized request with EMSGSIZE, len=%d", len(buf))
		return nil, fuse.Status(syscall.EMSGSIZE)
	}
	f.fdLock.RLock()
	defer f.fdLock.RUnlock()

	tlog.Debug.Printf("ino%d: FUSE Read: offset=%d length=%d", f.qIno.Ino, len(buf), off)
	if f.fs.args.SerializeReads {
		serialize_reads.Wait(off, len(buf))
	}
	out, status := f.doRead(buf[:0], uint64(off), uint64(len(buf)), false)
	if f.fs.args.SerializeReads {
		serialize_reads.Done()
	}
	if status != fuse.OK {
		return nil, status
	}
	tlog.Debug.Printf("ino%d: Read: status %v, returning %d bytes", f.qIno.Ino, status, len(out))
	return fuse.ReadResultData(out), status
}

// doWrite - encrypt "data" and write it to plaintext offset "off"
//
// Arguments do not have to be block-aligned, read-modify-write is
// performed internally as necessary
//
// Called by Write() for normal writing,
// and by Truncate() to rewrite the last file block.
//
// Empty writes do nothing and are allowed.
func (f *File) doWrite(data []byte, off int64) (uint32, fuse.Status) {
	fileWasEmpty := false
	// If the file ID is not cached, read it from disk
	if f.fileTableEntry.ID == nil {
		// Block other readers while we mess with the file header. Other writers
		// are blocked by ContentLock already.
		f.fileTableEntry.HeaderLock.Lock()
		tmpID, err := f.readFileID()
		// Write a new file header if the file is empty
		if err == io.EOF {
			tmpID, err = f.createHeader()
			fileWasEmpty = true
		}
		if err != nil {
			f.fileTableEntry.HeaderLock.Unlock()
			return 0, fuse.ToStatus(err)
		}
		f.fileTableEntry.ID = tmpID
		if fileWasEmpty {
			// The file was empty and we wrote a new file header. Keep the lock
			// as we might have to kill the file header again if the data write
			// fails.
			defer f.fileTableEntry.HeaderLock.Unlock()
		} else {
			// We won't touch the header again, drop the lock immediately.
			f.fileTableEntry.HeaderLock.Unlock()
		}
	}
	// Handle payload data
	dataBuf := bytes.NewBuffer(data)
	blocks := f.contentEnc.ExplodePlainRange(uint64(off), uint64(len(data)))
	toEncrypt := make([][]byte, len(blocks))
	for i, b := range blocks {
		blockData := dataBuf.Next(int(b.Length))
		// Incomplete block -> Read-Modify-Write
		if b.IsPartial() {
			// Read
			oldData, status := f.doRead(nil, b.BlockPlainOff(), f.contentEnc.PlainBS(), true)
			if status != fuse.OK {
				tlog.Warn.Printf("ino%d fh%d: RMW read failed: %s", f.qIno.Ino, f.intFd(), status.String())
				return 0, status
			}
			// Modify
			blockData = f.contentEnc.MergeBlocks(oldData, blockData, int(b.Skip))
			tlog.Debug.Printf("len(oldData)=%d len(blockData)=%d", len(oldData), len(blockData))
		}
		tlog.Debug.Printf("ino%d: Writing %d bytes to block #%d",
			f.qIno.Ino, uint64(len(blockData))-f.contentEnc.BlockOverhead(), b.BlockNo)
		// Write into the to-encrypt list
		toEncrypt[i] = blockData
	}
	// Encrypt all blocks
	ciphertext := f.contentEnc.EncryptBlocks(toEncrypt, blocks[0].BlockNo, f.fileTableEntry.ID)
	// Preallocate so we cannot run out of space in the middle of the write.
	// This prevents partially written (=corrupt) blocks.
	var err error
	cOff := int64(blocks[0].BlockCipherOff())
	if !f.fs.args.NoPrealloc {
		err = syscallcompat.EnospcPrealloc(int(f.fd.Fd()), cOff, int64(len(ciphertext)))
		if err != nil {
			if !syscallcompat.IsENOSPC(err) {
				tlog.Warn.Printf("ino%d fh%d: doWrite: prealloc failed: %v", f.qIno.Ino, f.intFd(), err)
			}
			if fileWasEmpty {
				// Kill the file header again
				f.fileTableEntry.ID = nil
				err2 := syscall.Ftruncate(int(f.fd.Fd()), 0)
				if err2 != nil {
					tlog.Warn.Printf("ino%d fh%d: doWrite: rollback failed: %v", f.qIno.Ino, f.intFd(), err2)
				}
			}
			return 0, fuse.ToStatus(err)
		}
	}
	// Write
	_, err = f.fd.WriteAt(ciphertext, cOff)
	// Return memory to CReqPool
	f.fs.contentEnc.CReqPool.Put(ciphertext)
	if err != nil {
		tlog.Warn.Printf("doWrite: Write failed: %s", err.Error())
		return 0, fuse.ToStatus(err)
	}
	return uint32(len(data)), fuse.OK
}

// isConsecutiveWrite returns true if the current write
// directly (in time and space) follows the last write.
// This is an optimisation for streaming writes on NFS where a
// Stat() call is very expensive.
// The caller must "wlock.lock(f.devIno.ino)" otherwise this check would be racy.
func (f *File) isConsecutiveWrite(off int64) bool {
	opCount := openfiletable.WriteOpCount()
	return opCount == f.lastOpCount+1 && off == f.lastWrittenOffset+1
}

// Write - FUSE call
//
// If the write creates a hole, pads the file to the next block boundary.
func (f *File) Write(data []byte, off int64) (uint32, fuse.Status) {
	if len(data) > fuse.MAX_KERNEL_WRITE {
		// This would crash us due to our fixed-size buffer pool
		tlog.Warn.Printf("Write: rejecting oversized request with EMSGSIZE, len=%d", len(data))
		return 0, fuse.Status(syscall.EMSGSIZE)
	}
	f.fdLock.RLock()
	defer f.fdLock.RUnlock()
	if f.released {
		// The file descriptor has been closed concurrently, which also means
		// the wlock has been freed. Exit here so we don't crash trying to access
		// it.
		tlog.Warn.Printf("ino%d fh%d: Write on released file", f.qIno.Ino, f.intFd())
		return 0, fuse.EBADF
	}
	f.fileTableEntry.ContentLock.Lock()
	defer f.fileTableEntry.ContentLock.Unlock()
	tlog.Debug.Printf("ino%d: FUSE Write: offset=%d length=%d", f.qIno.Ino, off, len(data))
	// If the write creates a file hole, we have to zero-pad the last block.
	// But if the write directly follows an earlier write, it cannot create a
	// hole, and we can save one Stat() call.
	if !f.isConsecutiveWrite(off) {
		status := f.writePadHole(off)
		if !status.Ok() {
			return 0, status
		}
	}
	n, status := f.doWrite(data, off)
	if status.Ok() {
		f.lastOpCount = openfiletable.WriteOpCount()
		f.lastWrittenOffset = off + int64(len(data)) - 1
	}
	return n, status
}

// Release - FUSE call, close file
func (f *File) Release() {
	f.fdLock.Lock()
	if f.released {
		log.Panicf("ino%d fh%d: double release", f.qIno.Ino, f.intFd())
	}
	f.fd.Close()
	f.released = true
	f.fdLock.Unlock()

	openfiletable.Unregister(f.qIno)
}

// Flush - FUSE call
func (f *File) Flush() fuse.Status {
	f.fdLock.RLock()
	defer f.fdLock.RUnlock()

	// Since Flush() may be called for each dup'd fd, we don't
	// want to really close the file, we just want to flush. This
	// is achieved by closing a dup'd fd.
	newFd, err := syscall.Dup(int(f.fd.Fd()))

	if err != nil {
		return fuse.ToStatus(err)
	}
	err = syscall.Close(newFd)
	return fuse.ToStatus(err)
}

// Fsync FUSE call
func (f *File) Fsync(flags int) (code fuse.Status) {
	f.fdLock.RLock()
	defer f.fdLock.RUnlock()

	return fuse.ToStatus(syscall.Fsync(int(f.fd.Fd())))
}

// Chmod FUSE call
func (f *File) Chmod(mode uint32) fuse.Status {
	f.fdLock.RLock()
	defer f.fdLock.RUnlock()

	// os.File.Chmod goes through the "syscallMode" translation function that messes
	// up the suid and sgid bits. So use syscall.Fchmod directly.
	err := syscall.Fchmod(f.intFd(), mode)
	return fuse.ToStatus(err)
}

// Chown FUSE call
func (f *File) Chown(uid uint32, gid uint32) fuse.Status {
	f.fdLock.RLock()
	defer f.fdLock.RUnlock()

	return fuse.ToStatus(f.fd.Chown(int(uid), int(gid)))
}

// GetAttr FUSE call (like stat)
func (f *File) GetAttr(a *fuse.Attr) fuse.Status {
	f.fdLock.RLock()
	defer f.fdLock.RUnlock()

	tlog.Debug.Printf("file.GetAttr()")
	st := syscall.Stat_t{}
	err := syscall.Fstat(int(f.fd.Fd()), &st)
	if err != nil {
		return fuse.ToStatus(err)
	}
	a.FromStat(&st)
	a.Size = f.contentEnc.CipherSizeToPlainSize(a.Size)
	if f.fs.args.ForceOwner != nil {
		a.Owner = *f.fs.args.ForceOwner
	}

	return fuse.OK
}

// Utimens FUSE call
func (f *File) Utimens(a *time.Time, m *time.Time) fuse.Status {
	f.fdLock.RLock()
	defer f.fdLock.RUnlock()
	return f.loopbackFile.Utimens(a, m)
}