Rename internal "toggledlog" package to "tlog"

tlog is used heavily everywhere and deserves a shorter name.

Renamed using sed magic, without any manual rework:

   find * -type f -exec sed -i 's/toggledlog/tlog/g' {} +
This commit is contained in:
Jakob Unterwurzacher 2016-06-15 23:30:44 +02:00
parent 09e88f31d1
commit 6c3f97399a
25 changed files with 186 additions and 186 deletions

View File

@ -7,7 +7,7 @@ import (
"os/signal" "os/signal"
"syscall" "syscall"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// The child sends us USR1 if the mount was successful // The child sends us USR1 if the mount was successful
@ -32,7 +32,7 @@ func forkChild() {
c.Stdin = os.Stdin c.Stdin = os.Stdin
err := c.Start() err := c.Start()
if err != nil { if err != nil {
toggledlog.Fatal.Printf("forkChild: starting %s failed: %v\n", name, err) tlog.Fatal.Printf("forkChild: starting %s failed: %v\n", name, err)
os.Exit(1) os.Exit(1)
} }
err = c.Wait() err = c.Wait()
@ -42,7 +42,7 @@ func forkChild() {
os.Exit(waitstat.ExitStatus()) os.Exit(waitstat.ExitStatus())
} }
} }
toggledlog.Fatal.Printf("forkChild: wait returned an unknown error: %v\n", err) tlog.Fatal.Printf("forkChild: wait returned an unknown error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
// The child exited with 0 - let's do the same. // The child exited with 0 - let's do the same.

View File

@ -7,7 +7,7 @@ import (
"github.com/rfjakob/gocryptfs/internal/contentenc" "github.com/rfjakob/gocryptfs/internal/contentenc"
"github.com/rfjakob/gocryptfs/internal/cryptocore" "github.com/rfjakob/gocryptfs/internal/cryptocore"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
import "os" import "os"
@ -84,7 +84,7 @@ func LoadConfFile(filename string, password string) ([]byte, *ConfFile, error) {
// Unmarshal // Unmarshal
err = json.Unmarshal(js, &cf) err = json.Unmarshal(js, &cf)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Failed to unmarshal config file") tlog.Warn.Printf("Failed to unmarshal config file")
return nil, nil, err return nil, nil, err
} }
@ -135,11 +135,11 @@ func LoadConfFile(filename string, password string) ([]byte, *ConfFile, error) {
cc := cryptocore.New(scryptHash, false, false) cc := cryptocore.New(scryptHash, false, false)
ce := contentenc.New(cc, 4096) ce := contentenc.New(cc, 4096)
toggledlog.Warn.Enabled = false // Silence DecryptBlock() error messages on incorrect password tlog.Warn.Enabled = false // Silence DecryptBlock() error messages on incorrect password
key, err := ce.DecryptBlock(cf.EncryptedKey, 0, nil) key, err := ce.DecryptBlock(cf.EncryptedKey, 0, nil)
toggledlog.Warn.Enabled = true tlog.Warn.Enabled = true
if err != nil { if err != nil {
toggledlog.Warn.Printf("failed to unlock master key: %s", err.Error()) tlog.Warn.Printf("failed to unlock master key: %s", err.Error())
return nil, nil, fmt.Errorf("Password incorrect.") return nil, nil, fmt.Errorf("Password incorrect.")
} }

View File

@ -5,7 +5,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
func TestLoadV1(t *testing.T) { func TestLoadV1(t *testing.T) {
@ -35,7 +35,7 @@ func TestLoadV2(t *testing.T) {
func TestLoadV2PwdError(t *testing.T) { func TestLoadV2PwdError(t *testing.T) {
if !testing.Verbose() { if !testing.Verbose() {
toggledlog.Warn.Enabled = false tlog.Warn.Enabled = false
} }
_, _, err := LoadConfFile("config_test/v2.conf", "wrongpassword") _, _, err := LoadConfFile("config_test/v2.conf", "wrongpassword")
if err == nil { if err == nil {

View File

@ -8,7 +8,7 @@ import (
"golang.org/x/crypto/scrypt" "golang.org/x/crypto/scrypt"
"github.com/rfjakob/gocryptfs/internal/cryptocore" "github.com/rfjakob/gocryptfs/internal/cryptocore"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
const ( const (
@ -32,7 +32,7 @@ func NewScryptKdf(logN int) scryptKdf {
s.N = 1 << ScryptDefaultLogN s.N = 1 << ScryptDefaultLogN
} else { } else {
if logN < 10 { if logN < 10 {
toggledlog.Fatal.Println("Error: scryptn below 10 is too low to make sense. Aborting.") tlog.Fatal.Println("Error: scryptn below 10 is too low to make sense. Aborting.")
os.Exit(1) os.Exit(1)
} }
s.N = 1 << uint32(logN) s.N = 1 << uint32(logN)

View File

@ -8,7 +8,7 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// DecryptBlocks - Decrypt a number of blocks // DecryptBlocks - Decrypt a number of blocks
@ -42,12 +42,12 @@ func (be *ContentEnc) DecryptBlock(ciphertext []byte, blockNo uint64, fileId []b
// All-zero block? // All-zero block?
if bytes.Equal(ciphertext, be.allZeroBlock) { if bytes.Equal(ciphertext, be.allZeroBlock) {
toggledlog.Debug.Printf("DecryptBlock: file hole encountered") tlog.Debug.Printf("DecryptBlock: file hole encountered")
return make([]byte, be.plainBS), nil return make([]byte, be.plainBS), nil
} }
if len(ciphertext) < be.cryptoCore.IVLen { if len(ciphertext) < be.cryptoCore.IVLen {
toggledlog.Warn.Printf("DecryptBlock: Block is too short: %d bytes", len(ciphertext)) tlog.Warn.Printf("DecryptBlock: Block is too short: %d bytes", len(ciphertext))
return nil, errors.New("Block is too short") return nil, errors.New("Block is too short")
} }
@ -64,8 +64,8 @@ func (be *ContentEnc) DecryptBlock(ciphertext []byte, blockNo uint64, fileId []b
plaintext, err := be.cryptoCore.Gcm.Open(plaintext, nonce, ciphertext, aData) plaintext, err := be.cryptoCore.Gcm.Open(plaintext, nonce, ciphertext, aData)
if err != nil { if err != nil {
toggledlog.Warn.Printf("DecryptBlock: %s, len=%d", err.Error(), len(ciphertextOrig)) tlog.Warn.Printf("DecryptBlock: %s, len=%d", err.Error(), len(ciphertextOrig))
toggledlog.Debug.Println(hex.Dump(ciphertextOrig)) tlog.Debug.Println(hex.Dump(ciphertextOrig))
return nil, err return nil, err
} }

View File

@ -1,7 +1,7 @@
package contentenc package contentenc
import ( import (
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// Contentenc methods that translate offsets between ciphertext and plaintext // Contentenc methods that translate offsets between ciphertext and plaintext
@ -35,12 +35,12 @@ func (be *ContentEnc) CipherSizeToPlainSize(cipherSize uint64) uint64 {
} }
if cipherSize == HEADER_LEN { if cipherSize == HEADER_LEN {
toggledlog.Warn.Printf("cipherSize %d == header size: interrupted write?\n", cipherSize) tlog.Warn.Printf("cipherSize %d == header size: interrupted write?\n", cipherSize)
return 0 return 0
} }
if cipherSize < HEADER_LEN { if cipherSize < HEADER_LEN {
toggledlog.Warn.Printf("cipherSize %d < header size %d: corrupt file\n", cipherSize, HEADER_LEN) tlog.Warn.Printf("cipherSize %d < header size %d: corrupt file\n", cipherSize, HEADER_LEN)
return 0 return 0
} }

View File

@ -7,7 +7,7 @@ import (
"crypto/cipher" "crypto/cipher"
"fmt" "fmt"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// goGCMWrapper - This wrapper makes sure gocryptfs can be compiled on Go // goGCMWrapper - This wrapper makes sure gocryptfs can be compiled on Go
@ -16,8 +16,8 @@ import (
// compiled on 1.4. // compiled on 1.4.
func goGCMWrapper(bc cipher.Block, nonceSize int) (cipher.AEAD, error) { func goGCMWrapper(bc cipher.Block, nonceSize int) (cipher.AEAD, error) {
if nonceSize != 12 { if nonceSize != 12 {
toggledlog.Warn.Printf("128 bit GCM IVs are not supported by Go 1.4 and lower.") tlog.Warn.Printf("128 bit GCM IVs are not supported by Go 1.4 and lower.")
toggledlog.Warn.Printf("Please use openssl crypto or recompile using a newer Go runtime.") tlog.Warn.Printf("Please use openssl crypto or recompile using a newer Go runtime.")
return nil, fmt.Errorf("128 bit GCM IVs are not supported by Go 1.4 and lower") return nil, fmt.Errorf("128 bit GCM IVs are not supported by Go 1.4 and lower")
} }
return cipher.NewGCM(bc) return cipher.NewGCM(bc)

View File

@ -7,7 +7,7 @@ import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// Get "n" random bytes from /dev/urandom or panic // Get "n" random bytes from /dev/urandom or panic
@ -34,7 +34,7 @@ type nonceGenerator struct {
// Get a random "nonceLen"-byte nonce // Get a random "nonceLen"-byte nonce
func (n *nonceGenerator) Get() []byte { func (n *nonceGenerator) Get() []byte {
nonce := RandBytes(n.nonceLen) nonce := RandBytes(n.nonceLen)
toggledlog.Debug.Printf("nonceGenerator.Get(): %s\n", hex.EncodeToString(nonce)) tlog.Debug.Printf("nonceGenerator.Get(): %s\n", hex.EncodeToString(nonce))
if bytes.Equal(nonce, n.lastNonce) { if bytes.Equal(nonce, n.lastNonce) {
m := fmt.Sprintf("Got the same nonce twice: %s. This should never happen!", hex.EncodeToString(nonce)) m := fmt.Sprintf("Got the same nonce twice: %s. This should never happen!", hex.EncodeToString(nonce))
panic(m) panic(m)

View File

@ -5,7 +5,7 @@ import (
"syscall" "syscall"
) )
import "github.com/rfjakob/gocryptfs/internal/toggledlog" import "github.com/rfjakob/gocryptfs/internal/tlog"
var preallocWarn sync.Once var preallocWarn sync.Once
@ -24,7 +24,7 @@ func prealloc(fd int, off int64, len int64) (err error) {
// ZFS does not support fallocate which caused gocryptfs to abort // ZFS does not support fallocate which caused gocryptfs to abort
// every write operation: https://github.com/rfjakob/gocryptfs/issues/22 // every write operation: https://github.com/rfjakob/gocryptfs/issues/22
preallocWarn.Do(func() { preallocWarn.Do(func() {
toggledlog.Warn.Printf("Warning: The underlying filesystem " + tlog.Warn.Printf("Warning: The underlying filesystem " +
"does not support fallocate(2). gocryptfs will continue working " + "does not support fallocate(2). gocryptfs will continue working " +
"but is no longer resistant against out-of-space errors.\n") "but is no longer resistant against out-of-space errors.\n")
}) })

View File

@ -16,7 +16,7 @@ import (
"github.com/hanwen/go-fuse/fuse/nodefs" "github.com/hanwen/go-fuse/fuse/nodefs"
"github.com/rfjakob/gocryptfs/internal/contentenc" "github.com/rfjakob/gocryptfs/internal/contentenc"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// File - based on loopbackFile in go-fuse/fuse/nodefs/files.go // File - based on loopbackFile in go-fuse/fuse/nodefs/files.go
@ -50,7 +50,7 @@ func NewFile(fd *os.File, writeOnly bool, contentEnc *contentenc.ContentEnc) (no
var st syscall.Stat_t var st syscall.Stat_t
err := syscall.Fstat(int(fd.Fd()), &st) err := syscall.Fstat(int(fd.Fd()), &st)
if err != nil { if err != nil {
toggledlog.Warn.Printf("NewFile: Fstat on fd %d failed: %v\n", fd.Fd(), err) tlog.Warn.Printf("NewFile: Fstat on fd %d failed: %v\n", fd.Fd(), err)
return nil, fuse.ToStatus(err) return nil, fuse.ToStatus(err)
} }
wlock.register(st.Ino) wlock.register(st.Ino)
@ -102,7 +102,7 @@ func (f *file) createHeader() error {
// Prevent partially written (=corrupt) header by preallocating the space beforehand // Prevent partially written (=corrupt) header by preallocating the space beforehand
err := prealloc(int(f.fd.Fd()), 0, contentenc.HEADER_LEN) err := prealloc(int(f.fd.Fd()), 0, contentenc.HEADER_LEN)
if err != nil { if err != nil {
toggledlog.Warn.Printf("ino%d: createHeader: prealloc failed: %s\n", f.ino, err.Error()) tlog.Warn.Printf("ino%d: createHeader: prealloc failed: %s\n", f.ino, err.Error())
return err return err
} }
@ -145,18 +145,18 @@ func (f *file) doRead(off uint64, length uint64) ([]byte, fuse.Status) {
blocks := f.contentEnc.ExplodePlainRange(off, length) blocks := f.contentEnc.ExplodePlainRange(off, length)
alignedOffset, alignedLength := blocks[0].JointCiphertextRange(blocks) alignedOffset, alignedLength := blocks[0].JointCiphertextRange(blocks)
skip := blocks[0].Skip skip := blocks[0].Skip
toggledlog.Debug.Printf("JointCiphertextRange(%d, %d) -> %d, %d, %d", off, length, alignedOffset, alignedLength, skip) tlog.Debug.Printf("JointCiphertextRange(%d, %d) -> %d, %d, %d", off, length, alignedOffset, alignedLength, skip)
ciphertext := make([]byte, int(alignedLength)) ciphertext := make([]byte, int(alignedLength))
n, err := f.fd.ReadAt(ciphertext, int64(alignedOffset)) n, err := f.fd.ReadAt(ciphertext, int64(alignedOffset))
if err != nil && err != io.EOF { if err != nil && err != io.EOF {
toggledlog.Warn.Printf("read: ReadAt: %s", err.Error()) tlog.Warn.Printf("read: ReadAt: %s", err.Error())
return nil, fuse.ToStatus(err) return nil, fuse.ToStatus(err)
} }
// Truncate ciphertext buffer down to actually read bytes // Truncate ciphertext buffer down to actually read bytes
ciphertext = ciphertext[0:n] ciphertext = ciphertext[0:n]
firstBlockNo := blocks[0].BlockNo firstBlockNo := blocks[0].BlockNo
toggledlog.Debug.Printf("ReadAt offset=%d bytes (%d blocks), want=%d, got=%d", alignedOffset, firstBlockNo, alignedLength, n) tlog.Debug.Printf("ReadAt offset=%d bytes (%d blocks), want=%d, got=%d", alignedOffset, firstBlockNo, alignedLength, n)
// Decrypt it // Decrypt it
plaintext, err := f.contentEnc.DecryptBlocks(ciphertext, firstBlockNo, f.header.Id) plaintext, err := f.contentEnc.DecryptBlocks(ciphertext, firstBlockNo, f.header.Id)
@ -164,7 +164,7 @@ func (f *file) doRead(off uint64, length uint64) ([]byte, fuse.Status) {
curruptBlockNo := firstBlockNo + f.contentEnc.PlainOffToBlockNo(uint64(len(plaintext))) curruptBlockNo := firstBlockNo + f.contentEnc.PlainOffToBlockNo(uint64(len(plaintext)))
cipherOff := f.contentEnc.BlockNoToCipherOff(curruptBlockNo) cipherOff := f.contentEnc.BlockNoToCipherOff(curruptBlockNo)
plainOff := f.contentEnc.BlockNoToPlainOff(curruptBlockNo) plainOff := f.contentEnc.BlockNoToPlainOff(curruptBlockNo)
toggledlog.Warn.Printf("ino%d: doRead: corrupt block #%d (plainOff=%d, cipherOff=%d)", tlog.Warn.Printf("ino%d: doRead: corrupt block #%d (plainOff=%d, cipherOff=%d)",
f.ino, curruptBlockNo, plainOff, cipherOff) f.ino, curruptBlockNo, plainOff, cipherOff)
return nil, fuse.EIO return nil, fuse.EIO
} }
@ -188,23 +188,23 @@ func (f *file) Read(buf []byte, off int64) (resultData fuse.ReadResult, code fus
f.fdLock.RLock() f.fdLock.RLock()
defer f.fdLock.RUnlock() defer f.fdLock.RUnlock()
toggledlog.Debug.Printf("ino%d: FUSE Read: offset=%d length=%d", f.ino, len(buf), off) tlog.Debug.Printf("ino%d: FUSE Read: offset=%d length=%d", f.ino, len(buf), off)
if f.writeOnly { if f.writeOnly {
toggledlog.Warn.Printf("ino%d: Tried to read from write-only file", f.ino) tlog.Warn.Printf("ino%d: Tried to read from write-only file", f.ino)
return nil, fuse.EBADF return nil, fuse.EBADF
} }
out, status := f.doRead(uint64(off), uint64(len(buf))) out, status := f.doRead(uint64(off), uint64(len(buf)))
if status == fuse.EIO { if status == fuse.EIO {
toggledlog.Warn.Printf("ino%d: Read failed with EIO, offset=%d, length=%d", f.ino, len(buf), off) tlog.Warn.Printf("ino%d: Read failed with EIO, offset=%d, length=%d", f.ino, len(buf), off)
} }
if status != fuse.OK { if status != fuse.OK {
return nil, status return nil, status
} }
toggledlog.Debug.Printf("ino%d: Read: status %v, returning %d bytes", f.ino, status, len(out)) tlog.Debug.Printf("ino%d: Read: status %v, returning %d bytes", f.ino, status, len(out))
return fuse.ReadResultData(out), status return fuse.ReadResultData(out), status
} }
@ -246,24 +246,24 @@ func (f *file) doWrite(data []byte, off int64) (uint32, fuse.Status) {
var oldData []byte var oldData []byte
oldData, status = f.doRead(o, f.contentEnc.PlainBS()) oldData, status = f.doRead(o, f.contentEnc.PlainBS())
if status != fuse.OK { if status != fuse.OK {
toggledlog.Warn.Printf("ino%d fh%d: RMW read failed: %s", f.ino, f.intFd(), status.String()) tlog.Warn.Printf("ino%d fh%d: RMW read failed: %s", f.ino, f.intFd(), status.String())
return written, status return written, status
} }
// Modify // Modify
blockData = f.contentEnc.MergeBlocks(oldData, blockData, int(b.Skip)) blockData = f.contentEnc.MergeBlocks(oldData, blockData, int(b.Skip))
toggledlog.Debug.Printf("len(oldData)=%d len(blockData)=%d", len(oldData), len(blockData)) tlog.Debug.Printf("len(oldData)=%d len(blockData)=%d", len(oldData), len(blockData))
} }
// Encrypt // Encrypt
blockOffset, blockLen := b.CiphertextRange() blockOffset, blockLen := b.CiphertextRange()
blockData = f.contentEnc.EncryptBlock(blockData, b.BlockNo, f.header.Id) blockData = f.contentEnc.EncryptBlock(blockData, b.BlockNo, f.header.Id)
toggledlog.Debug.Printf("ino%d: Writing %d bytes to block #%d", tlog.Debug.Printf("ino%d: Writing %d bytes to block #%d",
f.ino, uint64(len(blockData))-f.contentEnc.BlockOverhead(), b.BlockNo) f.ino, uint64(len(blockData))-f.contentEnc.BlockOverhead(), b.BlockNo)
// Prevent partially written (=corrupt) blocks by preallocating the space beforehand // Prevent partially written (=corrupt) blocks by preallocating the space beforehand
err := prealloc(int(f.fd.Fd()), int64(blockOffset), int64(blockLen)) err := prealloc(int(f.fd.Fd()), int64(blockOffset), int64(blockLen))
if err != nil { if err != nil {
toggledlog.Warn.Printf("ino%d fh%d: doWrite: prealloc failed: %s", f.ino, f.intFd(), err.Error()) tlog.Warn.Printf("ino%d fh%d: doWrite: prealloc failed: %s", f.ino, f.intFd(), err.Error())
status = fuse.ToStatus(err) status = fuse.ToStatus(err)
break break
} }
@ -272,7 +272,7 @@ func (f *file) doWrite(data []byte, off int64) (uint32, fuse.Status) {
_, err = f.fd.WriteAt(blockData, int64(blockOffset)) _, err = f.fd.WriteAt(blockData, int64(blockOffset))
if err != nil { if err != nil {
toggledlog.Warn.Printf("doWrite: Write failed: %s", err.Error()) tlog.Warn.Printf("doWrite: Write failed: %s", err.Error())
status = fuse.ToStatus(err) status = fuse.ToStatus(err)
break break
} }
@ -289,24 +289,24 @@ func (f *file) Write(data []byte, off int64) (uint32, fuse.Status) {
// The file descriptor has been closed concurrently, which also means // 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 // the wlock has been freed. Exit here so we don't crash trying to access
// it. // it.
toggledlog.Warn.Printf("ino%d fh%d: Write on released file", f.ino, f.intFd()) tlog.Warn.Printf("ino%d fh%d: Write on released file", f.ino, f.intFd())
return 0, fuse.EBADF return 0, fuse.EBADF
} }
wlock.lock(f.ino) wlock.lock(f.ino)
defer wlock.unlock(f.ino) defer wlock.unlock(f.ino)
toggledlog.Debug.Printf("ino%d: FUSE Write: offset=%d length=%d", f.ino, off, len(data)) tlog.Debug.Printf("ino%d: FUSE Write: offset=%d length=%d", f.ino, off, len(data))
fi, err := f.fd.Stat() fi, err := f.fd.Stat()
if err != nil { if err != nil {
toggledlog.Warn.Printf("Write: Fstat failed: %v", err) tlog.Warn.Printf("Write: Fstat failed: %v", err)
return 0, fuse.ToStatus(err) return 0, fuse.ToStatus(err)
} }
plainSize := f.contentEnc.CipherSizeToPlainSize(uint64(fi.Size())) plainSize := f.contentEnc.CipherSizeToPlainSize(uint64(fi.Size()))
if f.createsHole(plainSize, off) { if f.createsHole(plainSize, off) {
status := f.zeroPad(plainSize) status := f.zeroPad(plainSize)
if status != fuse.OK { if status != fuse.OK {
toggledlog.Warn.Printf("zeroPad returned error %v", status) tlog.Warn.Printf("zeroPad returned error %v", status)
return 0, status return 0, status
} }
} }
@ -356,7 +356,7 @@ func (f *file) Truncate(newSize uint64) fuse.Status {
defer f.fdLock.RUnlock() defer f.fdLock.RUnlock()
if f.released { if f.released {
// The file descriptor has been closed concurrently. // The file descriptor has been closed concurrently.
toggledlog.Warn.Printf("ino%d fh%d: Truncate on released file", f.ino, f.intFd()) tlog.Warn.Printf("ino%d fh%d: Truncate on released file", f.ino, f.intFd())
return fuse.EBADF return fuse.EBADF
} }
wlock.lock(f.ino) wlock.lock(f.ino)
@ -367,7 +367,7 @@ func (f *file) Truncate(newSize uint64) fuse.Status {
if newSize == 0 { if newSize == 0 {
err = syscall.Ftruncate(int(f.fd.Fd()), 0) err = syscall.Ftruncate(int(f.fd.Fd()), 0)
if err != nil { if err != nil {
toggledlog.Warn.Printf("ino%d fh%d: Ftruncate(fd, 0) returned error: %v", f.ino, f.intFd(), err) tlog.Warn.Printf("ino%d fh%d: Ftruncate(fd, 0) returned error: %v", f.ino, f.intFd(), err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
// Truncate to zero kills the file header // Truncate to zero kills the file header
@ -379,14 +379,14 @@ func (f *file) Truncate(newSize uint64) fuse.Status {
// the file // the file
fi, err := f.fd.Stat() fi, err := f.fd.Stat()
if err != nil { if err != nil {
toggledlog.Warn.Printf("ino%d fh%d: Truncate: Fstat failed: %v", f.ino, f.intFd(), err) tlog.Warn.Printf("ino%d fh%d: Truncate: Fstat failed: %v", f.ino, f.intFd(), err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
oldSize := f.contentEnc.CipherSizeToPlainSize(uint64(fi.Size())) oldSize := f.contentEnc.CipherSizeToPlainSize(uint64(fi.Size()))
{ {
oldB := float32(oldSize) / float32(f.contentEnc.PlainBS()) oldB := float32(oldSize) / float32(f.contentEnc.PlainBS())
newB := float32(newSize) / float32(f.contentEnc.PlainBS()) newB := float32(newSize) / float32(f.contentEnc.PlainBS())
toggledlog.Debug.Printf("ino%d: FUSE Truncate from %.2f to %.2f blocks (%d to %d bytes)", f.ino, oldB, newB, oldSize, newSize) tlog.Debug.Printf("ino%d: FUSE Truncate from %.2f to %.2f blocks (%d to %d bytes)", f.ino, oldB, newB, oldSize, newSize)
} }
// File size stays the same - nothing to do // File size stays the same - nothing to do
@ -419,7 +419,7 @@ func (f *file) Truncate(newSize uint64) fuse.Status {
off, length := b.CiphertextRange() off, length := b.CiphertextRange()
err = syscall.Ftruncate(int(f.fd.Fd()), int64(off+length)) err = syscall.Ftruncate(int(f.fd.Fd()), int64(off+length))
if err != nil { if err != nil {
toggledlog.Warn.Printf("grow Ftruncate returned error: %v", err) tlog.Warn.Printf("grow Ftruncate returned error: %v", err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
} }
@ -436,14 +436,14 @@ func (f *file) Truncate(newSize uint64) fuse.Status {
var status fuse.Status var status fuse.Status
data, status = f.doRead(plainOff, lastBlockLen) data, status = f.doRead(plainOff, lastBlockLen)
if status != fuse.OK { if status != fuse.OK {
toggledlog.Warn.Printf("shrink doRead returned error: %v", err) tlog.Warn.Printf("shrink doRead returned error: %v", err)
return status return status
} }
} }
// Truncate down to last complete block // Truncate down to last complete block
err = syscall.Ftruncate(int(f.fd.Fd()), int64(cipherOff)) err = syscall.Ftruncate(int(f.fd.Fd()), int64(cipherOff))
if err != nil { if err != nil {
toggledlog.Warn.Printf("shrink Ftruncate returned error: %v", err) tlog.Warn.Printf("shrink Ftruncate returned error: %v", err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
// Append partial block // Append partial block
@ -473,7 +473,7 @@ func (f *file) GetAttr(a *fuse.Attr) fuse.Status {
f.fdLock.RLock() f.fdLock.RLock()
defer f.fdLock.RUnlock() defer f.fdLock.RUnlock()
toggledlog.Debug.Printf("file.GetAttr()") tlog.Debug.Printf("file.GetAttr()")
st := syscall.Stat_t{} st := syscall.Stat_t{}
err := syscall.Fstat(int(f.fd.Fd()), &st) err := syscall.Fstat(int(f.fd.Fd()), &st)
if err != nil { if err != nil {
@ -491,7 +491,7 @@ var allocateWarnOnce sync.Once
// Allocate - FUSE call, fallocate(2) // Allocate - FUSE call, fallocate(2)
func (f *file) Allocate(off uint64, sz uint64, mode uint32) fuse.Status { func (f *file) Allocate(off uint64, sz uint64, mode uint32) fuse.Status {
allocateWarnOnce.Do(func() { allocateWarnOnce.Do(func() {
toggledlog.Warn.Printf("fallocate(2) is not supported, returning ENOSYS - see https://github.com/rfjakob/gocryptfs/issues/1") tlog.Warn.Printf("fallocate(2) is not supported, returning ENOSYS - see https://github.com/rfjakob/gocryptfs/issues/1")
}) })
return fuse.ENOSYS return fuse.ENOSYS
} }
@ -519,7 +519,7 @@ func (f *file) Utimens(a *time.Time, m *time.Time) fuse.Status {
fn := fmt.Sprintf("/proc/self/fd/%d", f.fd.Fd()) fn := fmt.Sprintf("/proc/self/fd/%d", f.fd.Fd())
err := syscall.UtimesNano(fn, ts) err := syscall.UtimesNano(fn, ts)
if err != nil { if err != nil {
toggledlog.Debug.Printf("UtimesNano on %q failed: %v", fn, err) tlog.Debug.Printf("UtimesNano on %q failed: %v", fn, err)
} }
if err == syscall.ENOENT { if err == syscall.ENOENT {
// If /proc/self/fd/X did not exist, the actual error is that the file // If /proc/self/fd/X did not exist, the actual error is that the file

View File

@ -5,7 +5,7 @@ package fusefrontend
import ( import (
"github.com/hanwen/go-fuse/fuse" "github.com/hanwen/go-fuse/fuse"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// Will a write to offset "off" create a file hole? // Will a write to offset "off" create a file hole?
@ -23,7 +23,7 @@ func (f *file) zeroPad(plainSize uint64) fuse.Status {
lastBlockLen := plainSize % f.contentEnc.PlainBS() lastBlockLen := plainSize % f.contentEnc.PlainBS()
missing := f.contentEnc.PlainBS() - lastBlockLen missing := f.contentEnc.PlainBS() - lastBlockLen
pad := make([]byte, missing) pad := make([]byte, missing)
toggledlog.Debug.Printf("zeroPad: Writing %d bytes\n", missing) tlog.Debug.Printf("zeroPad: Writing %d bytes\n", missing)
_, status := f.doWrite(pad, int64(plainSize)) _, status := f.doWrite(pad, int64(plainSize))
return status return status
} }

View File

@ -17,7 +17,7 @@ import (
"github.com/rfjakob/gocryptfs/internal/contentenc" "github.com/rfjakob/gocryptfs/internal/contentenc"
"github.com/rfjakob/gocryptfs/internal/cryptocore" "github.com/rfjakob/gocryptfs/internal/cryptocore"
"github.com/rfjakob/gocryptfs/internal/nametransform" "github.com/rfjakob/gocryptfs/internal/nametransform"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
type FS struct { type FS struct {
@ -49,7 +49,7 @@ func NewFS(args Args) *FS {
} }
func (fs *FS) GetAttr(name string, context *fuse.Context) (*fuse.Attr, fuse.Status) { func (fs *FS) GetAttr(name string, context *fuse.Context) (*fuse.Attr, fuse.Status) {
toggledlog.Debug.Printf("FS.GetAttr('%s')", name) tlog.Debug.Printf("FS.GetAttr('%s')", name)
if fs.isFiltered(name) { if fs.isFiltered(name) {
return nil, fuse.EPERM return nil, fuse.EPERM
} }
@ -59,7 +59,7 @@ func (fs *FS) GetAttr(name string, context *fuse.Context) (*fuse.Attr, fuse.Stat
} }
a, status := fs.FileSystem.GetAttr(cName, context) a, status := fs.FileSystem.GetAttr(cName, context)
if a == nil { if a == nil {
toggledlog.Debug.Printf("FS.GetAttr failed: %s", status.String()) tlog.Debug.Printf("FS.GetAttr failed: %s", status.String())
return a, status return a, status
} }
if a.IsRegular() { if a.IsRegular() {
@ -91,10 +91,10 @@ func (fs *FS) Open(path string, flags uint32, context *fuse.Context) (fuseFile n
iflags, writeOnly := fs.mangleOpenFlags(flags) iflags, writeOnly := fs.mangleOpenFlags(flags)
cPath, err := fs.getBackingPath(path) cPath, err := fs.getBackingPath(path)
if err != nil { if err != nil {
toggledlog.Debug.Printf("Open: getBackingPath: %v", err) tlog.Debug.Printf("Open: getBackingPath: %v", err)
return nil, fuse.ToStatus(err) return nil, fuse.ToStatus(err)
} }
toggledlog.Debug.Printf("Open: %s", cPath) tlog.Debug.Printf("Open: %s", cPath)
f, err := os.OpenFile(cPath, iflags, 0666) f, err := os.OpenFile(cPath, iflags, 0666)
if err != nil { if err != nil {
return nil, fuse.ToStatus(err) return nil, fuse.ToStatus(err)
@ -213,7 +213,7 @@ var truncateWarnOnce sync.Once
func (fs *FS) Truncate(path string, offset uint64, context *fuse.Context) (code fuse.Status) { func (fs *FS) Truncate(path string, offset uint64, context *fuse.Context) (code fuse.Status) {
truncateWarnOnce.Do(func() { truncateWarnOnce.Do(func() {
toggledlog.Warn.Printf("truncate(2) is not supported, returning ENOSYS - use ftruncate(2)") tlog.Warn.Printf("truncate(2) is not supported, returning ENOSYS - use ftruncate(2)")
}) })
return fuse.ENOSYS return fuse.ENOSYS
} }
@ -254,7 +254,7 @@ func (fs *FS) Readlink(path string, context *fuse.Context) (out string, status f
var target string var target string
target, err = fs.decryptPath(cTarget) target, err = fs.decryptPath(cTarget)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Readlink: CBC decryption failed: %v", err) tlog.Warn.Printf("Readlink: CBC decryption failed: %v", err)
return "", fuse.EIO return "", fuse.EIO
} }
return target, fuse.OK return target, fuse.OK
@ -262,12 +262,12 @@ func (fs *FS) Readlink(path string, context *fuse.Context) (out string, status f
// Since gocryptfs v0.5 symlinks are encrypted like file contents (GCM) // Since gocryptfs v0.5 symlinks are encrypted like file contents (GCM)
cBinTarget, err := base64.URLEncoding.DecodeString(cTarget) cBinTarget, err := base64.URLEncoding.DecodeString(cTarget)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Readlink: %v", err) tlog.Warn.Printf("Readlink: %v", err)
return "", fuse.EIO return "", fuse.EIO
} }
target, err := fs.contentEnc.DecryptBlock([]byte(cBinTarget), 0, nil) target, err := fs.contentEnc.DecryptBlock([]byte(cBinTarget), 0, nil)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Readlink: %v", err) tlog.Warn.Printf("Readlink: %v", err)
return "", fuse.EIO return "", fuse.EIO
} }
return string(target), fuse.OK return string(target), fuse.OK
@ -298,7 +298,7 @@ func (fs *FS) Unlink(path string, context *fuse.Context) (code fuse.Status) {
// Delete ".name" // Delete ".name"
err = nametransform.DeleteLongName(dirfd, cName) err = nametransform.DeleteLongName(dirfd, cName)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Unlink: could not delete .name file: %v", err) tlog.Warn.Printf("Unlink: could not delete .name file: %v", err)
} }
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
@ -308,7 +308,7 @@ func (fs *FS) Unlink(path string, context *fuse.Context) (code fuse.Status) {
} }
func (fs *FS) Symlink(target string, linkName string, context *fuse.Context) (code fuse.Status) { func (fs *FS) Symlink(target string, linkName string, context *fuse.Context) (code fuse.Status) {
toggledlog.Debug.Printf("Symlink(\"%s\", \"%s\")", target, linkName) tlog.Debug.Printf("Symlink(\"%s\", \"%s\")", target, linkName)
if fs.isFiltered(linkName) { if fs.isFiltered(linkName) {
return fuse.EPERM return fuse.EPERM
} }
@ -322,7 +322,7 @@ func (fs *FS) Symlink(target string, linkName string, context *fuse.Context) (co
var cTarget string var cTarget string
cTarget, err = fs.encryptPath(target) cTarget, err = fs.encryptPath(target)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Symlink: BUG: we should not get an error here: %v", err) tlog.Warn.Printf("Symlink: BUG: we should not get an error here: %v", err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
err = os.Symlink(cTarget, cPath) err = os.Symlink(cTarget, cPath)
@ -417,7 +417,7 @@ func (fs *FS) Rename(oldPath string, newPath string, context *fuse.Context) (cod
// If an empty directory is overwritten we will always get ENOTEMPTY as // If an empty directory is overwritten we will always get ENOTEMPTY as
// the "empty" directory will still contain gocryptfs.diriv. // the "empty" directory will still contain gocryptfs.diriv.
// Handle that case by removing the target directory and trying again. // Handle that case by removing the target directory and trying again.
toggledlog.Debug.Printf("Rename: Handling ENOTEMPTY") tlog.Debug.Printf("Rename: Handling ENOTEMPTY")
if fs.Rmdir(newPath, context) == fuse.OK { if fs.Rmdir(newPath, context) == fuse.OK {
err = syscall.Renameat(finalOldDirFd, finalOldPath, finalNewDirFd, finalNewPath) err = syscall.Renameat(finalOldDirFd, finalOldPath, finalNewDirFd, finalNewPath)
} }

View File

@ -13,7 +13,7 @@ import (
"github.com/rfjakob/gocryptfs/internal/configfile" "github.com/rfjakob/gocryptfs/internal/configfile"
"github.com/rfjakob/gocryptfs/internal/cryptocore" "github.com/rfjakob/gocryptfs/internal/cryptocore"
"github.com/rfjakob/gocryptfs/internal/nametransform" "github.com/rfjakob/gocryptfs/internal/nametransform"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
func (fs *FS) mkdirWithIv(cPath string, mode uint32) error { func (fs *FS) mkdirWithIv(cPath string, mode uint32) error {
@ -32,7 +32,7 @@ func (fs *FS) mkdirWithIv(cPath string, mode uint32) error {
if err != nil { if err != nil {
err2 := syscall.Rmdir(cPath) err2 := syscall.Rmdir(cPath)
if err2 != nil { if err2 != nil {
toggledlog.Warn.Printf("mkdirWithIv: rollback failed: %v", err2) tlog.Warn.Printf("mkdirWithIv: rollback failed: %v", err2)
} }
} }
return err return err
@ -86,7 +86,7 @@ func (fs *FS) Mkdir(newPath string, mode uint32, context *fuse.Context) (code fu
if origMode != mode { if origMode != mode {
err = os.Chmod(cPath, os.FileMode(origMode)) err = os.Chmod(cPath, os.FileMode(origMode))
if err != nil { if err != nil {
toggledlog.Warn.Printf("Mkdir: Chmod failed: %v", err) tlog.Warn.Printf("Mkdir: Chmod failed: %v", err)
} }
} }
@ -114,19 +114,19 @@ func (fs *FS) Rmdir(path string, context *fuse.Context) (code fuse.Status) {
syscall.O_RDONLY, 0) syscall.O_RDONLY, 0)
if err == syscall.EACCES { if err == syscall.EACCES {
// We need permission to read and modify the directory // We need permission to read and modify the directory
toggledlog.Debug.Printf("Rmdir: handling EACCESS") tlog.Debug.Printf("Rmdir: handling EACCESS")
// TODO use syscall.Fstatat once it is available in Go // TODO use syscall.Fstatat once it is available in Go
var fi os.FileInfo var fi os.FileInfo
fi, err = os.Lstat(cPath) fi, err = os.Lstat(cPath)
if err != nil { if err != nil {
toggledlog.Debug.Printf("Rmdir: Stat: %v", err) tlog.Debug.Printf("Rmdir: Stat: %v", err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
origMode := fi.Mode() origMode := fi.Mode()
// TODO use syscall.Chmodat once it is available in Go // TODO use syscall.Chmodat once it is available in Go
err = os.Chmod(cPath, origMode|0700) err = os.Chmod(cPath, origMode|0700)
if err != nil { if err != nil {
toggledlog.Debug.Printf("Rmdir: Chmod failed: %v", err) tlog.Debug.Printf("Rmdir: Chmod failed: %v", err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
// Retry open // Retry open
@ -139,13 +139,13 @@ func (fs *FS) Rmdir(path string, context *fuse.Context) (code fuse.Status) {
if code != fuse.OK { if code != fuse.OK {
err = os.Chmod(cPath, origMode) err = os.Chmod(cPath, origMode)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Rmdir: Chmod rollback failed: %v", err) tlog.Warn.Printf("Rmdir: Chmod rollback failed: %v", err)
} }
} }
}() }()
} }
if err != nil { if err != nil {
toggledlog.Debug.Printf("Rmdir: Open: %v", err) tlog.Debug.Printf("Rmdir: Open: %v", err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
dirfd := os.NewFile(uintptr(dirfdRaw), cName) dirfd := os.NewFile(uintptr(dirfdRaw), cName)
@ -153,7 +153,7 @@ func (fs *FS) Rmdir(path string, context *fuse.Context) (code fuse.Status) {
children, err := dirfd.Readdirnames(10) children, err := dirfd.Readdirnames(10)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Rmdir: Readdirnames: %v", err) tlog.Warn.Printf("Rmdir: Readdirnames: %v", err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
// If the directory is not empty besides gocryptfs.diriv, do not even // If the directory is not empty besides gocryptfs.diriv, do not even
@ -164,7 +164,7 @@ func (fs *FS) Rmdir(path string, context *fuse.Context) (code fuse.Status) {
// Move "gocryptfs.diriv" to the parent dir as "gocryptfs.diriv.rmdir.XYZ" // Move "gocryptfs.diriv" to the parent dir as "gocryptfs.diriv.rmdir.XYZ"
tmpName := fmt.Sprintf("gocryptfs.diriv.rmdir.%d", cryptocore.RandUint64()) tmpName := fmt.Sprintf("gocryptfs.diriv.rmdir.%d", cryptocore.RandUint64())
toggledlog.Debug.Printf("Rmdir: Renaming %s to %s", nametransform.DirIVFilename, tmpName) tlog.Debug.Printf("Rmdir: Renaming %s to %s", nametransform.DirIVFilename, tmpName)
// The directory is in an inconsistent state between rename and rmdir. // The directory is in an inconsistent state between rename and rmdir.
// Protect against concurrent readers. // Protect against concurrent readers.
fs.dirIVLock.Lock() fs.dirIVLock.Lock()
@ -172,7 +172,7 @@ func (fs *FS) Rmdir(path string, context *fuse.Context) (code fuse.Status) {
err = syscall.Renameat(int(dirfd.Fd()), nametransform.DirIVFilename, err = syscall.Renameat(int(dirfd.Fd()), nametransform.DirIVFilename,
int(parentDirFd.Fd()), tmpName) int(parentDirFd.Fd()), tmpName)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Rmdir: Renaming %s to %s failed: %v", tlog.Warn.Printf("Rmdir: Renaming %s to %s failed: %v",
nametransform.DirIVFilename, tmpName, err) nametransform.DirIVFilename, tmpName, err)
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
@ -186,14 +186,14 @@ func (fs *FS) Rmdir(path string, context *fuse.Context) (code fuse.Status) {
err2 := syscall.Renameat(int(parentDirFd.Fd()), tmpName, err2 := syscall.Renameat(int(parentDirFd.Fd()), tmpName,
int(dirfd.Fd()), nametransform.DirIVFilename) int(dirfd.Fd()), nametransform.DirIVFilename)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Rmdir: Rename rollback failed: %v", err2) tlog.Warn.Printf("Rmdir: Rename rollback failed: %v", err2)
} }
return fuse.ToStatus(err) return fuse.ToStatus(err)
} }
// Delete "gocryptfs.diriv.rmdir.XYZ" // Delete "gocryptfs.diriv.rmdir.XYZ"
err = syscall.Unlinkat(int(parentDirFd.Fd()), tmpName) err = syscall.Unlinkat(int(parentDirFd.Fd()), tmpName)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Rmdir: Could not clean up %s: %v", tmpName, err) tlog.Warn.Printf("Rmdir: Could not clean up %s: %v", tmpName, err)
} }
// Delete .name file // Delete .name file
if nametransform.IsLongContent(cName) { if nametransform.IsLongContent(cName) {
@ -205,7 +205,7 @@ func (fs *FS) Rmdir(path string, context *fuse.Context) (code fuse.Status) {
} }
func (fs *FS) OpenDir(dirName string, context *fuse.Context) ([]fuse.DirEntry, fuse.Status) { func (fs *FS) OpenDir(dirName string, context *fuse.Context) ([]fuse.DirEntry, fuse.Status) {
toggledlog.Debug.Printf("OpenDir(%s)", dirName) tlog.Debug.Printf("OpenDir(%s)", dirName)
cDirName, err := fs.encryptPath(dirName) cDirName, err := fs.encryptPath(dirName)
if err != nil { if err != nil {
return nil, fuse.ToStatus(err) return nil, fuse.ToStatus(err)
@ -255,7 +255,7 @@ func (fs *FS) OpenDir(dirName string, context *fuse.Context) ([]fuse.DirEntry, f
if isLong == nametransform.LongNameContent { if isLong == nametransform.LongNameContent {
cNameLong, err := nametransform.ReadLongName(filepath.Join(cDirAbsPath, cName)) cNameLong, err := nametransform.ReadLongName(filepath.Join(cDirAbsPath, cName))
if err != nil { if err != nil {
toggledlog.Warn.Printf("Skipping file %q in dir %q: Could not read .name: %v", tlog.Warn.Printf("Skipping file %q in dir %q: Could not read .name: %v",
cName, cDirName, err) cName, cDirName, err)
errorCount++ errorCount++
continue continue
@ -268,7 +268,7 @@ func (fs *FS) OpenDir(dirName string, context *fuse.Context) ([]fuse.DirEntry, f
name, err := fs.nameTransform.DecryptName(cName, cachedIV) name, err := fs.nameTransform.DecryptName(cName, cachedIV)
if err != nil { if err != nil {
toggledlog.Warn.Printf("Skipping invalid name %q in dir %q: %s", tlog.Warn.Printf("Skipping invalid name %q in dir %q: %s",
cName, cDirName, err) cName, cDirName, err)
errorCount++ errorCount++
continue continue
@ -281,7 +281,7 @@ func (fs *FS) OpenDir(dirName string, context *fuse.Context) ([]fuse.DirEntry, f
if errorCount > 0 && len(plain) == 0 { if errorCount > 0 && len(plain) == 0 {
// Don't let the user stare on an empty directory. Report that things went // Don't let the user stare on an empty directory. Report that things went
// wrong. // wrong.
toggledlog.Warn.Printf("All %d entries in directory %q were invalid, returning EIO", tlog.Warn.Printf("All %d entries in directory %q were invalid, returning EIO",
errorCount, cDirName) errorCount, cDirName)
status = fuse.EIO status = fuse.EIO
} }

View File

@ -6,7 +6,7 @@ import (
"path/filepath" "path/filepath"
"github.com/rfjakob/gocryptfs/internal/configfile" "github.com/rfjakob/gocryptfs/internal/configfile"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// isFiltered - check if plaintext "path" should be forbidden // isFiltered - check if plaintext "path" should be forbidden
@ -18,7 +18,7 @@ func (fs *FS) isFiltered(path string) bool {
} }
// gocryptfs.conf in the root directory is forbidden // gocryptfs.conf in the root directory is forbidden
if path == configfile.ConfDefaultName { if path == configfile.ConfDefaultName {
toggledlog.Info.Printf("The name /%s is reserved when -plaintextnames is used\n", tlog.Info.Printf("The name /%s is reserved when -plaintextnames is used\n",
configfile.ConfDefaultName) configfile.ConfDefaultName)
return true return true
} }
@ -35,7 +35,7 @@ func (fs *FS) getBackingPath(relPath string) (string, error) {
return "", err return "", err
} }
cAbsPath := filepath.Join(fs.args.Cipherdir, cPath) cAbsPath := filepath.Join(fs.args.Cipherdir, cPath)
toggledlog.Debug.Printf("getBackingPath: %s + %s -> %s", fs.args.Cipherdir, relPath, cAbsPath) tlog.Debug.Printf("getBackingPath: %s + %s -> %s", fs.args.Cipherdir, relPath, cAbsPath)
return cAbsPath, nil return cAbsPath, nil
} }
@ -49,7 +49,7 @@ func (fs *FS) encryptPath(plainPath string) (string, error) {
} }
fs.dirIVLock.RLock() fs.dirIVLock.RLock()
cPath, err := fs.nameTransform.EncryptPathDirIV(plainPath, fs.args.Cipherdir) cPath, err := fs.nameTransform.EncryptPathDirIV(plainPath, fs.args.Cipherdir)
toggledlog.Debug.Printf("encryptPath '%s' -> '%s' (err: %v)", plainPath, cPath, err) tlog.Debug.Printf("encryptPath '%s' -> '%s' (err: %v)", plainPath, cPath, err)
fs.dirIVLock.RUnlock() fs.dirIVLock.RUnlock()
return cPath, err return cPath, err
} }

View File

@ -9,7 +9,7 @@ import (
"strings" "strings"
"syscall" "syscall"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
const ( const (
@ -58,7 +58,7 @@ func IsLongContent(cName string) bool {
func ReadLongName(path string) (string, error) { func ReadLongName(path string) (string, error) {
content, err := ioutil.ReadFile(path + LongNameSuffix) content, err := ioutil.ReadFile(path + LongNameSuffix)
if err != nil { if err != nil {
toggledlog.Warn.Printf("ReadLongName: %v", err) tlog.Warn.Printf("ReadLongName: %v", err)
} }
return string(content), err return string(content), err
} }
@ -67,7 +67,7 @@ func ReadLongName(path string) (string, error) {
func DeleteLongName(dirfd *os.File, hashName string) error { func DeleteLongName(dirfd *os.File, hashName string) error {
err := syscall.Unlinkat(int(dirfd.Fd()), hashName+LongNameSuffix) err := syscall.Unlinkat(int(dirfd.Fd()), hashName+LongNameSuffix)
if err != nil { if err != nil {
toggledlog.Warn.Printf("DeleteLongName: %v", err) tlog.Warn.Printf("DeleteLongName: %v", err)
} }
return err return err
} }
@ -89,14 +89,14 @@ func (n *NameTransform) WriteLongName(dirfd *os.File, hashName string, plainName
fdRaw, err := syscall.Openat(int(dirfd.Fd()), hashName+LongNameSuffix, fdRaw, err := syscall.Openat(int(dirfd.Fd()), hashName+LongNameSuffix,
syscall.O_WRONLY|syscall.O_CREAT|syscall.O_EXCL, 0600) syscall.O_WRONLY|syscall.O_CREAT|syscall.O_EXCL, 0600)
if err != nil { if err != nil {
toggledlog.Warn.Printf("WriteLongName: Openat: %v", err) tlog.Warn.Printf("WriteLongName: Openat: %v", err)
return err return err
} }
fd := os.NewFile(uintptr(fdRaw), hashName+LongNameSuffix) fd := os.NewFile(uintptr(fdRaw), hashName+LongNameSuffix)
defer fd.Close() defer fd.Close()
_, err = fd.Write([]byte(cName)) _, err = fd.Write([]byte(cName))
if err != nil { if err != nil {
toggledlog.Warn.Printf("WriteLongName: Write: %v", err) tlog.Warn.Printf("WriteLongName: Write: %v", err)
} }
return err return err
} }

View File

@ -9,7 +9,7 @@ import (
"syscall" "syscall"
"github.com/rfjakob/gocryptfs/internal/cryptocore" "github.com/rfjakob/gocryptfs/internal/cryptocore"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
const ( const (
@ -37,7 +37,7 @@ func ReadDirIV(dir string) (iv []byte, err error) {
func ReadDirIVAt(dirfd *os.File) (iv []byte, err error) { func ReadDirIVAt(dirfd *os.File) (iv []byte, err error) {
fdRaw, err := syscall.Openat(int(dirfd.Fd()), DirIVFilename, syscall.O_RDONLY, 0) fdRaw, err := syscall.Openat(int(dirfd.Fd()), DirIVFilename, syscall.O_RDONLY, 0)
if err != nil { if err != nil {
toggledlog.Warn.Printf("ReadDirIVAt: opening %q in dir %q failed: %v", tlog.Warn.Printf("ReadDirIVAt: opening %q in dir %q failed: %v",
DirIVFilename, dirfd.Name(), err) DirIVFilename, dirfd.Name(), err)
return nil, err return nil, err
} }
@ -47,12 +47,12 @@ func ReadDirIVAt(dirfd *os.File) (iv []byte, err error) {
iv = make([]byte, dirIVLen+1) iv = make([]byte, dirIVLen+1)
n, err := fd.Read(iv) n, err := fd.Read(iv)
if err != nil { if err != nil {
toggledlog.Warn.Printf("ReadDirIVAt: Read failed: %v", err) tlog.Warn.Printf("ReadDirIVAt: Read failed: %v", err)
return nil, err return nil, err
} }
iv = iv[0:n] iv = iv[0:n]
if len(iv) != dirIVLen { if len(iv) != dirIVLen {
toggledlog.Warn.Printf("ReadDirIVAt: wanted %d bytes, got %d", dirIVLen, len(iv)) tlog.Warn.Printf("ReadDirIVAt: wanted %d bytes, got %d", dirIVLen, len(iv))
return nil, errors.New("invalid iv length") return nil, errors.New("invalid iv length")
} }
return iv, nil return iv, nil
@ -66,7 +66,7 @@ func WriteDirIV(dir string) error {
file := filepath.Join(dir, DirIVFilename) file := filepath.Join(dir, DirIVFilename)
err := ioutil.WriteFile(file, iv, 0400) err := ioutil.WriteFile(file, iv, 0400)
if err != nil { if err != nil {
toggledlog.Warn.Printf("WriteDirIV: %v", err) tlog.Warn.Printf("WriteDirIV: %v", err)
} }
return err return err
} }
@ -126,7 +126,7 @@ func (be *NameTransform) DecryptPathDirIV(encryptedPath string, rootDir string)
var wd = rootDir var wd = rootDir
var plainNames []string var plainNames []string
encryptedNames := strings.Split(encryptedPath, "/") encryptedNames := strings.Split(encryptedPath, "/")
toggledlog.Debug.Printf("DecryptPathDirIV: decrypting %v\n", encryptedNames) tlog.Debug.Printf("DecryptPathDirIV: decrypting %v\n", encryptedNames)
for _, encryptedName := range encryptedNames { for _, encryptedName := range encryptedNames {
iv, err := ReadDirIV(wd) iv, err := ReadDirIV(wd)
if err != nil { if err != nil {

View File

@ -4,7 +4,7 @@ import (
"io/ioutil" "io/ioutil"
"regexp" "regexp"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// filePreferOpenSSL tells us if OpenSSL is faster than Go GCM on this machine. // filePreferOpenSSL tells us if OpenSSL is faster than Go GCM on this machine.
@ -18,12 +18,12 @@ import (
func filePreferOpenSSL(file string) bool { func filePreferOpenSSL(file string) bool {
ci, err := ioutil.ReadFile(file) ci, err := ioutil.ReadFile(file)
if err != nil { if err != nil {
toggledlog.Warn.Println(err) tlog.Warn.Println(err)
return true return true
} }
haveAes, err := regexp.Match(`(?m)^flags.*\baes\b`, ci) haveAes, err := regexp.Match(`(?m)^flags.*\baes\b`, ci)
if err != nil { if err != nil {
toggledlog.Warn.Println(err) tlog.Warn.Println(err)
return true return true
} }
return !haveAes return !haveAes

View File

@ -5,12 +5,12 @@ import (
"os/exec" "os/exec"
"testing" "testing"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
// Shut up info output // Shut up info output
toggledlog.Info.Enabled = false tlog.Info.Enabled = false
m.Run() m.Run()
} }

View File

@ -9,7 +9,7 @@ import (
"golang.org/x/crypto/ssh/terminal" "golang.org/x/crypto/ssh/terminal"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
const ( const (
@ -40,7 +40,7 @@ func Twice(extpass string) string {
p1 := readPasswordTerminal("Password: ") p1 := readPasswordTerminal("Password: ")
p2 := readPasswordTerminal("Repeat: ") p2 := readPasswordTerminal("Repeat: ")
if p1 != p2 { if p1 != p2 {
toggledlog.Fatal.Println("Passwords do not match") tlog.Fatal.Println("Passwords do not match")
os.Exit(exitCode) os.Exit(exitCode)
} }
return p1 return p1
@ -54,12 +54,12 @@ func readPasswordTerminal(prompt string) string {
// terminal.ReadPassword removes the trailing newline // terminal.ReadPassword removes the trailing newline
p, err := terminal.ReadPassword(fd) p, err := terminal.ReadPassword(fd)
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Could not read password from terminal: %v\n", err) tlog.Fatal.Printf("Could not read password from terminal: %v\n", err)
os.Exit(exitCode) os.Exit(exitCode)
} }
fmt.Fprintf(os.Stderr, "\n") fmt.Fprintf(os.Stderr, "\n")
if len(p) == 0 { if len(p) == 0 {
toggledlog.Fatal.Println("Password is empty") tlog.Fatal.Println("Password is empty")
os.Exit(exitCode) os.Exit(exitCode)
} }
return string(p) return string(p)
@ -68,11 +68,11 @@ func readPasswordTerminal(prompt string) string {
// readPasswordStdin reads a line from stdin // readPasswordStdin reads a line from stdin
// Exits on read error or empty result. // Exits on read error or empty result.
func readPasswordStdin() string { func readPasswordStdin() string {
toggledlog.Info.Println("Reading password from stdin") tlog.Info.Println("Reading password from stdin")
p := readLineUnbuffered(os.Stdin) p := readLineUnbuffered(os.Stdin)
if len(p) == 0 { if len(p) == 0 {
fmt.Fprintf(os.Stderr, "FOOOOOO\n") fmt.Fprintf(os.Stderr, "FOOOOOO\n")
toggledlog.Fatal.Println("Got empty password from stdin") tlog.Fatal.Println("Got empty password from stdin")
os.Exit(exitCode) os.Exit(exitCode)
} }
return p return p
@ -82,25 +82,25 @@ func readPasswordStdin() string {
// of the output. // of the output.
// Exits on read error or empty result. // Exits on read error or empty result.
func readPasswordExtpass(extpass string) string { func readPasswordExtpass(extpass string) string {
toggledlog.Info.Println("Reading password from extpass program") tlog.Info.Println("Reading password from extpass program")
parts := strings.Split(extpass, " ") parts := strings.Split(extpass, " ")
cmd := exec.Command(parts[0], parts[1:]...) cmd := exec.Command(parts[0], parts[1:]...)
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
pipe, err := cmd.StdoutPipe() pipe, err := cmd.StdoutPipe()
if err != nil { if err != nil {
toggledlog.Fatal.Printf("extpass pipe setup failed: %v", err) tlog.Fatal.Printf("extpass pipe setup failed: %v", err)
os.Exit(exitCode) os.Exit(exitCode)
} }
err = cmd.Start() err = cmd.Start()
if err != nil { if err != nil {
toggledlog.Fatal.Printf("extpass cmd start failed: %v", err) tlog.Fatal.Printf("extpass cmd start failed: %v", err)
os.Exit(exitCode) os.Exit(exitCode)
} }
p := readLineUnbuffered(pipe) p := readLineUnbuffered(pipe)
pipe.Close() pipe.Close()
cmd.Wait() cmd.Wait()
if len(p) == 0 { if len(p) == 0 {
toggledlog.Fatal.Println("extpass: password is empty") tlog.Fatal.Println("extpass: password is empty")
os.Exit(exitCode) os.Exit(exitCode)
} }
return p return p
@ -116,7 +116,7 @@ func readLineUnbuffered(r io.Reader) (l string) {
return l return l
} }
if err != nil { if err != nil {
toggledlog.Fatal.Printf("readLineUnbuffered: %v", err) tlog.Fatal.Printf("readLineUnbuffered: %v", err)
os.Exit(exitCode) os.Exit(exitCode)
} }
if n == 0 { if n == 0 {

View File

@ -1,4 +1,4 @@
package toggledlog package tlog
import ( import (
"encoding/json" "encoding/json"

View File

@ -1,7 +1,7 @@
// +build !go1.5 // +build !go1.5
// = go 1.4 or lower // = go 1.4 or lower
package toggledlog package tlog
import ( import (
"log/syslog" "log/syslog"

View File

@ -1,7 +1,7 @@
// +build go1.5 // +build go1.5
// = go 1.5 or higher // = go 1.5 or higher
package toggledlog package tlog
import ( import (
"log/syslog" "log/syslog"

110
main.go
View File

@ -27,7 +27,7 @@ import (
"github.com/rfjakob/gocryptfs/internal/nametransform" "github.com/rfjakob/gocryptfs/internal/nametransform"
"github.com/rfjakob/gocryptfs/internal/prefer_openssl" "github.com/rfjakob/gocryptfs/internal/prefer_openssl"
"github.com/rfjakob/gocryptfs/internal/readpassword" "github.com/rfjakob/gocryptfs/internal/readpassword"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
const ( const (
@ -59,21 +59,21 @@ var GitVersionFuse = "[version not set - please compile using ./build.bash]"
func initDir(args *argContainer) { func initDir(args *argContainer) {
err := checkDirEmpty(args.cipherdir) err := checkDirEmpty(args.cipherdir)
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Invalid cipherdir: %v", err) tlog.Fatal.Printf("Invalid cipherdir: %v", err)
os.Exit(ERREXIT_INIT) os.Exit(ERREXIT_INIT)
} }
// Create gocryptfs.conf // Create gocryptfs.conf
if args.extpass == "" { if args.extpass == "" {
toggledlog.Info.Printf("Choose a password for protecting your files.") tlog.Info.Printf("Choose a password for protecting your files.")
} else { } else {
toggledlog.Info.Printf("Using password provided via -extpass.") tlog.Info.Printf("Using password provided via -extpass.")
} }
password := readpassword.Twice(args.extpass) password := readpassword.Twice(args.extpass)
creator := toggledlog.ProgramName + " " + GitVersion creator := tlog.ProgramName + " " + GitVersion
err = configfile.CreateConfFile(args.config, password, args.plaintextnames, args.scryptn, creator) err = configfile.CreateConfFile(args.config, password, args.plaintextnames, args.scryptn, creator)
if err != nil { if err != nil {
toggledlog.Fatal.Println(err) tlog.Fatal.Println(err)
os.Exit(ERREXIT_INIT) os.Exit(ERREXIT_INIT)
} }
@ -81,12 +81,12 @@ func initDir(args *argContainer) {
// Create gocryptfs.diriv in the root dir // Create gocryptfs.diriv in the root dir
err = nametransform.WriteDirIV(args.cipherdir) err = nametransform.WriteDirIV(args.cipherdir)
if err != nil { if err != nil {
toggledlog.Fatal.Println(err) tlog.Fatal.Println(err)
os.Exit(ERREXIT_INIT) os.Exit(ERREXIT_INIT)
} }
} }
toggledlog.Info.Printf(toggledlog.ColorGreen + "The filesystem has been created successfully." + toggledlog.ColorReset) tlog.Info.Printf(tlog.ColorGreen + "The filesystem has been created successfully." + tlog.ColorReset)
wd, _ := os.Getwd() wd, _ := os.Getwd()
friendlyPath, _ := filepath.Rel(wd, args.cipherdir) friendlyPath, _ := filepath.Rel(wd, args.cipherdir)
if strings.HasPrefix(friendlyPath, "../") { if strings.HasPrefix(friendlyPath, "../") {
@ -94,8 +94,8 @@ func initDir(args *argContainer) {
// keep the absolute path. // keep the absolute path.
friendlyPath = args.cipherdir friendlyPath = args.cipherdir
} }
toggledlog.Info.Printf(toggledlog.ColorGrey+"You can now mount it using: %s %s MOUNTPOINT"+toggledlog.ColorReset, tlog.Info.Printf(tlog.ColorGrey+"You can now mount it using: %s %s MOUNTPOINT"+tlog.ColorReset,
toggledlog.ProgramName, friendlyPath) tlog.ProgramName, friendlyPath)
os.Exit(0) os.Exit(0)
} }
@ -106,7 +106,7 @@ Usage: %s -init|-passwd [OPTIONS] CIPHERDIR
or %s [OPTIONS] CIPHERDIR MOUNTPOINT or %s [OPTIONS] CIPHERDIR MOUNTPOINT
Options: Options:
`, toggledlog.ProgramName, toggledlog.ProgramName) `, tlog.ProgramName, tlog.ProgramName)
flagSet.PrintDefaults() flagSet.PrintDefaults()
} }
@ -116,14 +116,14 @@ func loadConfig(args *argContainer) (masterkey []byte, confFile *configfile.Conf
// Check if the file exists at all before prompting for a password // Check if the file exists at all before prompting for a password
_, err := os.Stat(args.config) _, err := os.Stat(args.config)
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Config file not found: %v", err) tlog.Fatal.Printf("Config file not found: %v", err)
os.Exit(ERREXIT_LOADCONF) os.Exit(ERREXIT_LOADCONF)
} }
pw := readpassword.Once(args.extpass) pw := readpassword.Once(args.extpass)
toggledlog.Info.Println("Decrypting master key") tlog.Info.Println("Decrypting master key")
masterkey, confFile, err = configfile.LoadConfFile(args.config, pw) masterkey, confFile, err = configfile.LoadConfFile(args.config, pw)
if err != nil { if err != nil {
toggledlog.Fatal.Println(err.Error()) tlog.Fatal.Println(err.Error())
os.Exit(ERREXIT_LOADCONF) os.Exit(ERREXIT_LOADCONF)
} }
@ -133,15 +133,15 @@ func loadConfig(args *argContainer) (masterkey []byte, confFile *configfile.Conf
// changePassword - change the password of config file "filename" // changePassword - change the password of config file "filename"
func changePassword(args *argContainer) { func changePassword(args *argContainer) {
masterkey, confFile := loadConfig(args) masterkey, confFile := loadConfig(args)
toggledlog.Info.Println("Please enter your new password.") tlog.Info.Println("Please enter your new password.")
newPw := readpassword.Twice(args.extpass) newPw := readpassword.Twice(args.extpass)
confFile.EncryptKey(masterkey, newPw, confFile.ScryptObject.LogN()) confFile.EncryptKey(masterkey, newPw, confFile.ScryptObject.LogN())
err := confFile.WriteFile() err := confFile.WriteFile()
if err != nil { if err != nil {
toggledlog.Fatal.Println(err) tlog.Fatal.Println(err)
os.Exit(ERREXIT_INIT) os.Exit(ERREXIT_INIT)
} }
toggledlog.Info.Printf("Password changed.") tlog.Info.Printf("Password changed.")
os.Exit(0) os.Exit(0)
} }
@ -149,7 +149,7 @@ func changePassword(args *argContainer) {
// "gocryptfs v0.3.1-31-g6736212-dirty; on-disk format 2" // "gocryptfs v0.3.1-31-g6736212-dirty; on-disk format 2"
func printVersion() { func printVersion() {
fmt.Printf("%s %s; on-disk format %d; go-fuse %s\n", fmt.Printf("%s %s; on-disk format %d; go-fuse %s\n",
toggledlog.ProgramName, GitVersion, contentenc.CurrentVersion, GitVersionFuse) tlog.ProgramName, GitVersion, contentenc.CurrentVersion, GitVersionFuse)
} }
func main() { func main() {
@ -159,7 +159,7 @@ func main() {
// Parse command line arguments // Parse command line arguments
var opensslAuto string var opensslAuto string
flagSet = flag.NewFlagSet(toggledlog.ProgramName, flag.ExitOnError) flagSet = flag.NewFlagSet(tlog.ProgramName, flag.ExitOnError)
flagSet.Usage = usageText flagSet.Usage = usageText
flagSet.BoolVar(&args.debug, "d", false, "") flagSet.BoolVar(&args.debug, "d", false, "")
flagSet.BoolVar(&args.debug, "debug", false, "Enable debug output") flagSet.BoolVar(&args.debug, "debug", false, "Enable debug output")
@ -199,7 +199,7 @@ func main() {
} else { } else {
args.openssl, err = strconv.ParseBool(opensslAuto) args.openssl, err = strconv.ParseBool(opensslAuto)
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Invalid \"-openssl\" setting: %v", err) tlog.Fatal.Printf("Invalid \"-openssl\" setting: %v", err)
os.Exit(ERREXIT_USAGE) os.Exit(ERREXIT_USAGE)
} }
} }
@ -209,24 +209,24 @@ func main() {
forkChild() // does not return forkChild() // does not return
} }
if args.debug { if args.debug {
toggledlog.Debug.Enabled = true tlog.Debug.Enabled = true
} }
// "-v" // "-v"
if args.version { if args.version {
toggledlog.Debug.Printf("openssl=%v\n", args.openssl) tlog.Debug.Printf("openssl=%v\n", args.openssl)
printVersion() printVersion()
os.Exit(0) os.Exit(0)
} }
if args.wpanic { if args.wpanic {
toggledlog.Warn.Wpanic = true tlog.Warn.Wpanic = true
toggledlog.Debug.Printf("Panicing on warnings") tlog.Debug.Printf("Panicing on warnings")
} }
// Every operation below requires CIPHERDIR. Check that we have it. // Every operation below requires CIPHERDIR. Check that we have it.
if flagSet.NArg() >= 1 { if flagSet.NArg() >= 1 {
args.cipherdir, _ = filepath.Abs(flagSet.Arg(0)) args.cipherdir, _ = filepath.Abs(flagSet.Arg(0))
err = checkDir(args.cipherdir) err = checkDir(args.cipherdir)
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Invalid cipherdir: %v", err) tlog.Fatal.Printf("Invalid cipherdir: %v", err)
os.Exit(ERREXIT_CIPHERDIR) os.Exit(ERREXIT_CIPHERDIR)
} }
} else { } else {
@ -235,26 +235,26 @@ func main() {
} }
// "-q" // "-q"
if args.quiet { if args.quiet {
toggledlog.Info.Enabled = false tlog.Info.Enabled = false
} }
// "-config" // "-config"
if args.config != "" { if args.config != "" {
args.config, err = filepath.Abs(args.config) args.config, err = filepath.Abs(args.config)
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Invalid \"-config\" setting: %v", err) tlog.Fatal.Printf("Invalid \"-config\" setting: %v", err)
os.Exit(ERREXIT_INIT) os.Exit(ERREXIT_INIT)
} }
toggledlog.Info.Printf("Using config file at custom location %s", args.config) tlog.Info.Printf("Using config file at custom location %s", args.config)
} else { } else {
args.config = filepath.Join(args.cipherdir, configfile.ConfDefaultName) args.config = filepath.Join(args.cipherdir, configfile.ConfDefaultName)
} }
// "-cpuprofile" // "-cpuprofile"
if args.cpuprofile != "" { if args.cpuprofile != "" {
toggledlog.Info.Printf("Writing CPU profile to %s", args.cpuprofile) tlog.Info.Printf("Writing CPU profile to %s", args.cpuprofile)
var f *os.File var f *os.File
f, err = os.Create(args.cpuprofile) f, err = os.Create(args.cpuprofile)
if err != nil { if err != nil {
toggledlog.Fatal.Println(err) tlog.Fatal.Println(err)
os.Exit(ERREXIT_INIT) os.Exit(ERREXIT_INIT)
} }
pprof.StartCPUProfile(f) pprof.StartCPUProfile(f)
@ -262,11 +262,11 @@ func main() {
} }
// "-memprofile" // "-memprofile"
if args.memprofile != "" { if args.memprofile != "" {
toggledlog.Info.Printf("Writing mem profile to %s", args.memprofile) tlog.Info.Printf("Writing mem profile to %s", args.memprofile)
var f *os.File var f *os.File
f, err = os.Create(args.memprofile) f, err = os.Create(args.memprofile)
if err != nil { if err != nil {
toggledlog.Fatal.Println(err) tlog.Fatal.Println(err)
os.Exit(ERREXIT_INIT) os.Exit(ERREXIT_INIT)
} }
defer func() { defer func() {
@ -276,19 +276,19 @@ func main() {
}() }()
} }
if args.cpuprofile != "" || args.memprofile != "" { if args.cpuprofile != "" || args.memprofile != "" {
toggledlog.Info.Printf("Note: You must unmount gracefully, otherwise the profile file(s) will stay empty!\n") tlog.Info.Printf("Note: You must unmount gracefully, otherwise the profile file(s) will stay empty!\n")
} }
// "-openssl" // "-openssl"
if args.openssl == false { if args.openssl == false {
toggledlog.Debug.Printf("OpenSSL disabled, using Go GCM") tlog.Debug.Printf("OpenSSL disabled, using Go GCM")
} else { } else {
toggledlog.Debug.Printf("OpenSSL enabled") tlog.Debug.Printf("OpenSSL enabled")
} }
// Operation flags: init, passwd or mount // Operation flags: init, passwd or mount
// "-init" // "-init"
if args.init { if args.init {
if flagSet.NArg() > 1 { if flagSet.NArg() > 1 {
toggledlog.Fatal.Printf("Usage: %s -init [OPTIONS] CIPHERDIR", toggledlog.ProgramName) tlog.Fatal.Printf("Usage: %s -init [OPTIONS] CIPHERDIR", tlog.ProgramName)
os.Exit(ERREXIT_USAGE) os.Exit(ERREXIT_USAGE)
} }
initDir(&args) // does not return initDir(&args) // does not return
@ -296,7 +296,7 @@ func main() {
// "-passwd" // "-passwd"
if args.passwd { if args.passwd {
if flagSet.NArg() > 1 { if flagSet.NArg() > 1 {
toggledlog.Fatal.Printf("Usage: %s -passwd [OPTIONS] CIPHERDIR", toggledlog.ProgramName) tlog.Fatal.Printf("Usage: %s -passwd [OPTIONS] CIPHERDIR", tlog.ProgramName)
os.Exit(ERREXIT_USAGE) os.Exit(ERREXIT_USAGE)
} }
changePassword(&args) // does not return changePassword(&args) // does not return
@ -304,17 +304,17 @@ func main() {
// Mount // Mount
// Check mountpoint // Check mountpoint
if flagSet.NArg() != 2 { if flagSet.NArg() != 2 {
toggledlog.Fatal.Printf("Usage: %s [OPTIONS] CIPHERDIR MOUNTPOINT", toggledlog.ProgramName) tlog.Fatal.Printf("Usage: %s [OPTIONS] CIPHERDIR MOUNTPOINT", tlog.ProgramName)
os.Exit(ERREXIT_USAGE) os.Exit(ERREXIT_USAGE)
} }
args.mountpoint, err = filepath.Abs(flagSet.Arg(1)) args.mountpoint, err = filepath.Abs(flagSet.Arg(1))
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Invalid mountpoint: %v", err) tlog.Fatal.Printf("Invalid mountpoint: %v", err)
os.Exit(ERREXIT_MOUNTPOINT) os.Exit(ERREXIT_MOUNTPOINT)
} }
err = checkDirEmpty(args.mountpoint) err = checkDirEmpty(args.mountpoint)
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Invalid mountpoint: %v", err) tlog.Fatal.Printf("Invalid mountpoint: %v", err)
os.Exit(ERREXIT_MOUNTPOINT) os.Exit(ERREXIT_MOUNTPOINT)
} }
// Get master key // Get master key
@ -322,13 +322,13 @@ func main() {
var confFile *configfile.ConfFile var confFile *configfile.ConfFile
if args.masterkey != "" { if args.masterkey != "" {
// "-masterkey" // "-masterkey"
toggledlog.Info.Printf("Using explicit master key.") tlog.Info.Printf("Using explicit master key.")
masterkey = parseMasterKey(args.masterkey) masterkey = parseMasterKey(args.masterkey)
toggledlog.Info.Printf("THE MASTER KEY IS VISIBLE VIA \"ps -auxwww\", ONLY USE THIS MODE FOR EMERGENCIES.") tlog.Info.Printf("THE MASTER KEY IS VISIBLE VIA \"ps -auxwww\", ONLY USE THIS MODE FOR EMERGENCIES.")
} else if args.zerokey { } else if args.zerokey {
// "-zerokey" // "-zerokey"
toggledlog.Info.Printf("Using all-zero dummy master key.") tlog.Info.Printf("Using all-zero dummy master key.")
toggledlog.Info.Printf("ZEROKEY MODE PROVIDES NO SECURITY AT ALL AND SHOULD ONLY BE USED FOR TESTING.") tlog.Info.Printf("ZEROKEY MODE PROVIDES NO SECURITY AT ALL AND SHOULD ONLY BE USED FOR TESTING.")
masterkey = make([]byte, cryptocore.KeyLen) masterkey = make([]byte, cryptocore.KeyLen)
} else { } else {
// Load master key from config file // Load master key from config file
@ -336,17 +336,17 @@ func main() {
printMasterKey(masterkey) printMasterKey(masterkey)
} }
// Initialize FUSE server // Initialize FUSE server
toggledlog.Debug.Printf("cli args: %v", args) tlog.Debug.Printf("cli args: %v", args)
srv := initFuseFrontend(masterkey, args, confFile) srv := initFuseFrontend(masterkey, args, confFile)
toggledlog.Info.Println(toggledlog.ColorGreen + "Filesystem mounted and ready." + toggledlog.ColorReset) tlog.Info.Println(tlog.ColorGreen + "Filesystem mounted and ready." + tlog.ColorReset)
// We are ready - send USR1 signal to our parent and switch to syslog // We are ready - send USR1 signal to our parent and switch to syslog
if args.notifypid > 0 { if args.notifypid > 0 {
sendUsr1(args.notifypid) sendUsr1(args.notifypid)
if !args.nosyslog { if !args.nosyslog {
toggledlog.Info.SwitchToSyslog(syslog.LOG_USER | syslog.LOG_INFO) tlog.Info.SwitchToSyslog(syslog.LOG_USER | syslog.LOG_INFO)
toggledlog.Debug.SwitchToSyslog(syslog.LOG_USER | syslog.LOG_DEBUG) tlog.Debug.SwitchToSyslog(syslog.LOG_USER | syslog.LOG_DEBUG)
toggledlog.Warn.SwitchToSyslog(syslog.LOG_USER | syslog.LOG_WARNING) tlog.Warn.SwitchToSyslog(syslog.LOG_USER | syslog.LOG_WARNING)
} }
} }
// Wait for SIGINT in the background and unmount ourselves if we get it. // Wait for SIGINT in the background and unmount ourselves if we get it.
@ -391,7 +391,7 @@ func initFuseFrontend(key []byte, args argContainer, confFile *configfile.ConfFi
frontendArgs.EMENames = false frontendArgs.EMENames = false
} }
jsonBytes, _ := json.MarshalIndent(frontendArgs, "", "\t") jsonBytes, _ := json.MarshalIndent(frontendArgs, "", "\t")
toggledlog.Debug.Printf("frontendArgs: %s", string(jsonBytes)) tlog.Debug.Printf("frontendArgs: %s", string(jsonBytes))
finalFs := fusefrontend.NewFS(frontendArgs) finalFs := fusefrontend.NewFS(frontendArgs)
pathFsOpts := &pathfs.PathNodeFsOptions{ClientInodes: true} pathFsOpts := &pathfs.PathNodeFsOptions{ClientInodes: true}
@ -407,8 +407,8 @@ func initFuseFrontend(key []byte, args argContainer, confFile *configfile.ConfFi
var mOpts fuse.MountOptions var mOpts fuse.MountOptions
mOpts.AllowOther = false mOpts.AllowOther = false
if args.allow_other { if args.allow_other {
toggledlog.Info.Printf(toggledlog.ColorYellow + "The option \"-allow_other\" is set. Make sure the file " + tlog.Info.Printf(tlog.ColorYellow + "The option \"-allow_other\" is set. Make sure the file " +
"permissions protect your data from unwanted access." + toggledlog.ColorReset) "permissions protect your data from unwanted access." + tlog.ColorReset)
mOpts.AllowOther = true mOpts.AllowOther = true
// Make the kernel check the file permissions for us // Make the kernel check the file permissions for us
mOpts.Options = append(mOpts.Options, "default_permissions") mOpts.Options = append(mOpts.Options, "default_permissions")
@ -421,7 +421,7 @@ func initFuseFrontend(key []byte, args argContainer, confFile *configfile.ConfFi
srv, err := fuse.NewServer(conn.RawFS(), args.mountpoint, &mOpts) srv, err := fuse.NewServer(conn.RawFS(), args.mountpoint, &mOpts)
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Mount failed: %v", err) tlog.Fatal.Printf("Mount failed: %v", err)
os.Exit(ERREXIT_MOUNT) os.Exit(ERREXIT_MOUNT)
} }
srv.SetDebug(args.fusedebug) srv.SetDebug(args.fusedebug)
@ -442,8 +442,8 @@ func handleSigint(srv *fuse.Server, mountpoint string) {
<-ch <-ch
err := srv.Unmount() err := srv.Unmount()
if err != nil { if err != nil {
toggledlog.Warn.Print(err) tlog.Warn.Print(err)
toggledlog.Info.Printf("Trying lazy unmount") tlog.Info.Printf("Trying lazy unmount")
cmd := exec.Command("fusermount", "-u", "-z", mountpoint) cmd := exec.Command("fusermount", "-u", "-z", mountpoint)
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr

View File

@ -6,7 +6,7 @@ import (
"strings" "strings"
"github.com/rfjakob/gocryptfs/internal/cryptocore" "github.com/rfjakob/gocryptfs/internal/cryptocore"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// printMasterKey - remind the user that he should store the master key in // printMasterKey - remind the user that he should store the master key in
@ -26,7 +26,7 @@ func printMasterKey(key []byte) {
} }
} }
toggledlog.Info.Printf(` tlog.Info.Printf(`
Your master key is: Your master key is:
%s %s
@ -35,7 +35,7 @@ If the gocryptfs.conf file becomes corrupted or you ever forget your password,
there is only one hope for recovery: The master key. Print it to a piece of there is only one hope for recovery: The master key. Print it to a piece of
paper and store it in a drawer. paper and store it in a drawer.
`, toggledlog.ColorGrey+hChunked+toggledlog.ColorReset) `, tlog.ColorGrey+hChunked+tlog.ColorReset)
} }
// parseMasterKey - Parse a hex-encoded master key that was passed on the command line // parseMasterKey - Parse a hex-encoded master key that was passed on the command line
@ -44,11 +44,11 @@ func parseMasterKey(masterkey string) []byte {
masterkey = strings.Replace(masterkey, "-", "", -1) masterkey = strings.Replace(masterkey, "-", "", -1)
key, err := hex.DecodeString(masterkey) key, err := hex.DecodeString(masterkey)
if err != nil { if err != nil {
toggledlog.Fatal.Printf("Could not parse master key: %v\n", err) tlog.Fatal.Printf("Could not parse master key: %v\n", err)
os.Exit(1) os.Exit(1)
} }
if len(key) != cryptocore.KeyLen { if len(key) != cryptocore.KeyLen {
toggledlog.Fatal.Printf("Master key has length %d but we require length %d\n", len(key), cryptocore.KeyLen) tlog.Fatal.Printf("Master key has length %d but we require length %d\n", len(key), cryptocore.KeyLen)
os.Exit(1) os.Exit(1)
} }
return key return key

View File

@ -4,7 +4,7 @@ import (
"os" "os"
"syscall" "syscall"
"github.com/rfjakob/gocryptfs/internal/toggledlog" "github.com/rfjakob/gocryptfs/internal/tlog"
) )
// Send signal USR1 to "pid" (usually our parent process). This notifies it // Send signal USR1 to "pid" (usually our parent process). This notifies it
@ -12,11 +12,11 @@ import (
func sendUsr1(pid int) { func sendUsr1(pid int) {
p, err := os.FindProcess(pid) p, err := os.FindProcess(pid)
if err != nil { if err != nil {
toggledlog.Warn.Printf("sendUsr1: FindProcess: %v\n", err) tlog.Warn.Printf("sendUsr1: FindProcess: %v\n", err)
return return
} }
err = p.Signal(syscall.SIGUSR1) err = p.Signal(syscall.SIGUSR1)
if err != nil { if err != nil {
toggledlog.Warn.Printf("sendUsr1: Signal: %v\n", err) tlog.Warn.Printf("sendUsr1: Signal: %v\n", err)
} }
} }