libkbfs

package
v2.13.1+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2019 License: BSD-3-Clause, BSD-3-Clause, BSD-3-Clause Imports: 73 Imported by: 0

README

The core logic for KBFS. Presentation layers should using the interfaces in this library, particularly KBFSOps, to interact with KBFS.

(TODO: Fill in more details.)

Documentation

Index

Constants

View Source
const (
	// BServerDefaultPingIntervalSeconds is the default interval on which the
	// client should contact the block server.
	BServerDefaultPingIntervalSeconds = 10
	// BServerPingTimeout is how long to wait for a ping response
	// before breaking the connection and trying to reconnect.
	BServerPingTimeout = 30 * time.Second
)
View Source
const (
	KeybaseServiceName     = "keybase-service"
	MDServiceName          = "md-server"
	GregorServiceName      = "gregor"
	LoginStatusUpdateName  = "login"
	LogoutStatusUpdateName = "logout"
)

Service names used in ConnectionStatus.

View Source
const (
	// StatusCodeDiskBlockCacheError is a generic disk cache error.
	StatusCodeDiskBlockCacheError = 0x666
	// StatusCodeDiskMDCacheError is a generic disk cache error.
	StatusCodeDiskMDCacheError = 0x667
	// StatusCodeDiskQuotaCacheError is a generic disk cache error.
	StatusCodeDiskQuotaCacheError = 0x668
)

Disk Cache Errors

View Source
const (
	// InitDefaultString is the normal mode for when KBFS data will be
	// read and written.
	InitDefaultString string = "default"
	// InitMinimalString is for when KBFS will only be used as a MD
	// lookup layer (e.g., for chat on mobile).
	InitMinimalString = "minimal"
	// InitSingleOpString is for when KBFS will only be used for a
	// single logical operation (e.g., as a git remote helper).
	InitSingleOpString = "singleOp"
	// InitConstrainedString is for when KBFS will use constrained
	// resources.
	InitConstrainedString = "constrained"
	// InitMemoryLimitedString is for when KBFS will use memory limited
	// resources.
	InitMemoryLimitedString = "memoryLimited"
)
View Source
const (
	// MdServerBackgroundRekeyPeriod is how long the rekey checker
	// waits between runs on average. The timer gets reset after
	// every incoming FolderNeedsRekey RPC.
	// The amount of wait is calculated in nextRekeyTime.
	MdServerBackgroundRekeyPeriod = 1 * time.Hour
	// MdServerDefaultPingIntervalSeconds is the default interval on which the
	// client should contact the MD Server
	MdServerDefaultPingIntervalSeconds = 10
	// MdServerPingTimeout is how long to wait for a ping response
	// before breaking the connection and trying to reconnect.
	MdServerPingTimeout = 30 * time.Second
)
View Source
const (
	// EnvTestMDServerAddr is the environment variable name for an
	// mdserver address.
	EnvTestMDServerAddr = "KEYBASE_TEST_MDSERVER_ADDR"
	// EnvTestBServerAddr is the environment variable name for a block
	// server address.
	EnvTestBServerAddr = "KEYBASE_TEST_BSERVER_ADDR"
	// TempdirServerAddr is the special value of the
	// EnvTest{B,MD}ServerAddr environment value to signify that
	// an on-disk implementation of the {b,md}server should be
	// used with a temporary directory.
	TempdirServerAddr = "tempdir"
)
View Source
const (
	StallableBlockGet StallableBlockOp = "Get"
	StallableBlockPut StallableBlockOp = "Put"

	StallableMDGetForTLF                    StallableMDOp = "GetForTLF"
	StallableMDGetForTLFByTime              StallableMDOp = "GetForTLFByTime"
	StallableMDGetLatestHandleForTLF        StallableMDOp = "GetLatestHandleForTLF"
	StallableMDValidateLatestHandleNotFinal StallableMDOp = "ValidateLatestHandleNotFinal"
	StallableMDGetUnmergedForTLF            StallableMDOp = "GetUnmergedForTLF"
	StallableMDGetRange                     StallableMDOp = "GetRange"
	StallableMDAfterGetRange                StallableMDOp = "AfterGetRange"
	StallableMDGetUnmergedRange             StallableMDOp = "GetUnmergedRange"
	StallableMDPut                          StallableMDOp = "Put"
	StallableMDAfterPut                     StallableMDOp = "AfterPut"
	StallableMDPutUnmerged                  StallableMDOp = "PutUnmerged"
	StallableMDAfterPutUnmerged             StallableMDOp = "AfterPutUnmerged"
	StallableMDPruneBranch                  StallableMDOp = "PruneBranch"
	StallableMDResolveBranch                StallableMDOp = "ResolveBranch"
)

stallable Block Ops and MD Ops

View Source
const (

	// ForcedBranchSquashRevThreshold is the minimum number of MD
	// revisions in the journal that will trigger an automatic branch
	// conversion (and subsequent resolution).
	ForcedBranchSquashRevThreshold = 20
	// ForcedBranchSquashBytesThresholdDefault is the minimum number of
	// unsquashed MD bytes in the journal that will trigger an
	// automatic branch conversion (and subsequent resolution).
	ForcedBranchSquashBytesThresholdDefault = uint64(25 << 20) // 25 MB

)
View Source
const CtxCROpID = "CRID"

CtxCROpID is the display name for the unique operation conflict resolution ID tag.

View Source
const CtxFBMOpID = "FBMID"

CtxFBMOpID is the display name for the unique operation folderBlockManager ID tag.

View Source
const CtxFBOOpID = "FBOID"

CtxFBOOpID is the display name for the unique operation folderBranchOps ID tag.

View Source
const CtxJournalOpID = "JID"

CtxJournalOpID is the display name for the unique operation enqueued journal ID tag.

View Source
const CtxKeybaseServiceOpID = "KSID"

CtxKeybaseServiceOpID is the display name for the unique operation enqueued rekey ID tag.

View Source
const CtxMDSROpID = "MDSRID"

CtxMDSROpID is the display name for the unique operation MDServerRemote ID tag.

View Source
const CtxRekeyOpID = "REKEYID"

CtxRekeyOpID is the display name for the unique operation enqueued rekey ID tag.

View Source
const DefaultBlocksInMemCache = 1024

DefaultBlocksInMemCache is the number of blocks we should keep in the cache.

View Source
const ECMRID = "ECMR"

ECMRID is used in EventuallyConsistentMerkleRoot for only background RPCs. More specifically, when we need to spawn a background goroutine for GetCurrentMerkleRoot, a new context with this tag is created and used. This is also used as a prefix for the logger module name in EventuallyConsistentMerkleRoot.

View Source
const ECQUID = "ECQU"

ECQUID is used in EventuallyConsistentQuotaUsage for only background RPCs. More specifically, when we need to spawn a background goroutine for GetUserQuotaInfo, a new context with this tag is created and used. This is also used as a prefix for the logger module name in EventuallyConsistentQuotaUsage.

View Source
const (
	// MaxBlockSizeBytesDefault is the default maximum block size for KBFS.
	// 512K blocks by default, block changes embedded max == 8K.
	// Block size was chosen somewhat arbitrarily by trying to
	// minimize the overall size of the history written by a user when
	// appending 1KB writes to a file, up to a 1GB total file.  Here
	// is the output of a simple script that approximates that
	// calculation:
	//
	// Total history size for 0065536-byte blocks: 1134341128192 bytes
	// Total history size for 0131072-byte blocks: 618945052672 bytes
	// Total history size for 0262144-byte blocks: 412786622464 bytes
	// Total history size for 0524288-byte blocks: 412786622464 bytes
	// Total history size for 1048576-byte blocks: 618945052672 bytes
	// Total history size for 2097152-byte blocks: 1134341128192 bytes
	// Total history size for 4194304-byte blocks: 2216672886784 bytes
	MaxBlockSizeBytesDefault = 512 << 10
)

Constants used in this file. TODO: Make these configurable?

View Source
const (
	// PublicUIDName is the name given to keybase1.PublicUID.  This string
	// should correspond to an illegal or reserved Keybase user name.
	PublicUIDName = "_public"
)
View Source
const RPCReconnectInterval = 2 * time.Second

RPCReconnectInterval specifies the time between reconnect attempts for RPC Connections.

View Source
const Version = "1.0.2"

Version is the current version (should be MAJOR.MINOR.PATCH)

Variables

View Source
var ErrUnrecognizedPrefetchStatus = errors.New(
	"Unrecognized PrefetchStatus value")

ErrUnrecognizedPrefetchStatus is returned when trying to unmarshal a prefetch status from JSON if the prefetch status is unrecognized.

View Source
var ErrorFile = ".kbfs_error"

ErrorFile is the name of the virtual file in KBFS that should contain the last reported error(s).

View Source
var NoCurrentSessionExpectedError = "no current session"

NoCurrentSessionExpectedError is the error text that will get converted into a NoCurrentSessionError.

View Source
var PrereleaseBuild string

PrereleaseBuild is set at compile time for prerelease builds

Functions

func AddDeviceForLocalUserOrBust

func AddDeviceForLocalUserOrBust(t logger.TestLogBackend, config Config,
	uid keybase1.UID) int

AddDeviceForLocalUserOrBust creates a new device for a user and returns the index for that device.

func AddImplicitTeamForTest

func AddImplicitTeamForTest(
	config Config, name, suffix string, teamNumber byte, ty tlf.Type) (
	keybase1.TeamID, error)

AddImplicitTeamForTest adds an implicit team with a TLF ID.

func AddImplicitTeamForTestOrBust

func AddImplicitTeamForTestOrBust(t logger.TestLogBackend,
	config Config, name, suffix string, teamNumber byte,
	ty tlf.Type) keybase1.TeamID

AddImplicitTeamForTestOrBust is like AddImplicitTeamForTest, but dies if there's an error.

func AddNewAssertionForTest

func AddNewAssertionForTest(
	config Config, oldAssertion, newAssertion string) error

AddNewAssertionForTest makes newAssertion, which should be a single assertion that doesn't already resolve to anything, resolve to the same UID as oldAssertion, which should be an arbitrary assertion that does already resolve to something. It only applies to the given config.

func AddNewAssertionForTestOrBust

func AddNewAssertionForTestOrBust(t logger.TestLogBackend, config Config,
	oldAssertion, newAssertion string)

AddNewAssertionForTestOrBust is like AddNewAssertionForTest, but dies if there's an error.

func AddTeamKeyForTest

func AddTeamKeyForTest(config Config, tid keybase1.TeamID) error

AddTeamKeyForTest adds a new key for the given team.

func AddTeamKeyForTestOrBust

func AddTeamKeyForTestOrBust(t logger.TestLogBackend, config Config,
	tid keybase1.TeamID)

AddTeamKeyForTestOrBust is like AddTeamKeyForTest, but dies if there's an error.

func AddTeamReaderForTest

func AddTeamReaderForTest(
	config Config, tid keybase1.TeamID, uid keybase1.UID) error

AddTeamReaderForTest makes the given user a team reader.

func AddTeamReaderForTestOrBust

func AddTeamReaderForTestOrBust(t logger.TestLogBackend, config Config,
	tid keybase1.TeamID, uid keybase1.UID)

AddTeamReaderForTestOrBust is like AddTeamWriterForTest, but dies if there's an error.

func AddTeamWriterForTest

func AddTeamWriterForTest(
	config Config, tid keybase1.TeamID, uid keybase1.UID) error

AddTeamWriterForTest makes the given user a team writer.

func AddTeamWriterForTestOrBust

func AddTeamWriterForTestOrBust(t logger.TestLogBackend, config Config,
	tid keybase1.TeamID, uid keybase1.UID)

AddTeamWriterForTestOrBust is like AddTeamWriterForTest, but dies if there's an error.

func BackgroundContextWithCancellationDelayer

func BackgroundContextWithCancellationDelayer() context.Context

BackgroundContextWithCancellationDelayer generate a "Background" context that is cancellation delayable

func BoolForString

func BoolForString(s string) bool

BoolForString returns false if trimmed string is "" (empty), "0", "false", or "no"

func BuildCanonicalPath

func BuildCanonicalPath(pathType PathType, paths ...string) string

BuildCanonicalPath returns a canonical path for a path components. This a canonical path and may need to be converted to a platform specific path, for example, on Windows, this might correspond to k:\private\username.

func ChangeTeamNameForTest

func ChangeTeamNameForTest(
	config Config, oldName, newName string) error

ChangeTeamNameForTest renames a team.

func ChangeTeamNameForTestOrBust

func ChangeTeamNameForTestOrBust(t logger.TestLogBackend, config Config,
	oldName, newName string)

ChangeTeamNameForTestOrBust is like ChangeTeamNameForTest, but dies if there's an error.

func CheckConfigAndShutdown

func CheckConfigAndShutdown(
	ctx context.Context, t logger.TestLogBackend, config Config)

CheckConfigAndShutdown shuts down the given config, but fails the test if there's an error.

func CheckTlfHandleOffline

func CheckTlfHandleOffline(
	ctx context.Context, name string, t tlf.Type) error

CheckTlfHandleOffline does light checks whether a TLF handle looks ok, it avoids all network calls.

func CleanupCancellationDelayer

func CleanupCancellationDelayer(ctx context.Context) error

CleanupCancellationDelayer cleans up a context (ctx) that is cancellation delayable and makes the go routine spawned in NewContextWithCancellationDelayer exit. As part of the cleanup, this also causes the cancellation delayable context to be canceled, no matter whether the timeout passed into the EnableDelayedCancellationWithGracePeriod has passed or not.

Ideally, the parent ctx's cancelFunc is always called upon completion of handling a request, in which case this wouldn't be necessary.

func ConvertIdentifyError

func ConvertIdentifyError(assertion string, err error) error

ConvertIdentifyError converts a errors during identify into KBFS errors

func CtxWithRandomIDReplayable

func CtxWithRandomIDReplayable(ctx context.Context, tagKey interface{},
	tagName string, log Warninger) context.Context

CtxWithRandomIDReplayable returns a replayable context with a random id associated with the given log key.

func DisableCRForTesting

func DisableCRForTesting(config Config, folderBranch FolderBranch) error

DisableCRForTesting stops conflict resolution for the given folder. RestartCRForTesting should be called to restart it.

func DisableUpdatesForTesting

func DisableUpdatesForTesting(config Config, folderBranch FolderBranch) (
	chan<- struct{}, error)

DisableUpdatesForTesting stops the given folder from acting on new updates. Send a struct{}{} down the returned channel to restart notifications

func DumpPrivateMetadata

func DumpPrivateMetadata(
	codec kbfscodec.Codec, serializedPMDLength int, pmd PrivateMetadata) (string, error)

DumpPrivateMetadata returns a detailed dump of the given PrivateMetadata's contents.

func EnableAdminFeature

func EnableAdminFeature(ctx context.Context, runMode kbconst.RunMode, config Config) bool

EnableAdminFeature returns true if admin features should be enabled for the currently-logged-in user.

func EnableDelayedCancellationWithGracePeriod

func EnableDelayedCancellationWithGracePeriod(ctx context.Context, timeout time.Duration) error

EnableDelayedCancellationWithGracePeriod can be called on a "cancellation delayable" context produced by NewContextWithCancellationDelayer, to enable delayed cancellation for ctx. This is useful to indicate that the operation(s) associated with the context has entered a critical state, and it should not be canceled until after timeout or CleanupCancellationDelayer is called.

Note that if EnableDelayedCancellationWithGracePeriod is called for the second time, and the grace period has started due to a cancellation, the grace period would not be extended (i.e. timeout has no effect in this case). Although in this case, no error is returned, since the delayed cancellation is already enabled.

func EnableImplicitTeamsForTest

func EnableImplicitTeamsForTest(config Config) error

EnableImplicitTeamsForTest causes the mdserver to stop returning random TLF IDs for new TLFs.

func FillInJournalStatusUnflushedPaths

func FillInJournalStatusUnflushedPaths(ctx context.Context, config Config,
	jStatus *JournalServerStatus, tlfIDs []tlf.ID) error

FillInJournalStatusUnflushedPaths adds the unflushed paths to the given journal status.

func ForceQuotaReclamationForTesting

func ForceQuotaReclamationForTesting(config Config,
	folderBranch FolderBranch) error

ForceQuotaReclamationForTesting kicks off quota reclamation under the given config, for the given folder-branch.

func GetDefaultsUsageString

func GetDefaultsUsageString(ctx Context) string

GetDefaultsUsageString returns a string describing the default values of flags based on the run mode.

func GetLocalUsageString

func GetLocalUsageString() string

GetLocalUsageString returns a string describing the flags to use to run in a local testing environment.

func GetMDRevisionByTime

func GetMDRevisionByTime(
	ctx context.Context, config Config, handle *TlfHandle,
	serverTime time.Time) (kbfsmd.Revision, error)

GetMDRevisionByTime returns the revision number of the earliest merged MD of `handle` with a server timestamp greater or equal to `serverTime`.

func GetRemoteUsageString

func GetRemoteUsageString() string

GetRemoteUsageString returns a string describing the flags to use to run against remote KBFS servers.

func InitLog

func InitLog(params InitParams, ctx Context) (logger.Logger, error)

InitLog sets up logging switching to a log file if necessary. Returns a valid logger even on error, which are non-fatal, thus errors from this function may be ignored. Possible errors are logged to the logger returned.

func InitLogWithPrefix

func InitLogWithPrefix(
	params InitParams, ctx Context, prefix string,
	defaultLogPath string) (logger.Logger, error)

InitLogWithPrefix sets up logging switching to a log file if necessary, given a prefix and a default log path. Returns a valid logger even on error, which are non-fatal, thus errors from this function may be ignored. Possible errors are logged to the logger returned.

func IsOnlyWriterInNonTeamTlf

func IsOnlyWriterInNonTeamTlf(ctx context.Context, kbpki KBPKI,
	h *TlfHandle) bool

IsOnlyWriterInNonTeamTlf returns true if and only if the TLF described by h is a non-team TLF, and the currently logged-in user is the only writer for the TLF. In case of any error false is returned.

func MakeExtendedIdentify

func MakeExtendedIdentify(ctx context.Context,
	behavior keybase1.TLFIdentifyBehavior) (context.Context, error)

MakeExtendedIdentify populates a context with an extendedIdentify directive.

func MakeLocalTLFCryptKeyOrBust

func MakeLocalTLFCryptKeyOrBust(
	name string, keyGen kbfsmd.KeyGen) kbfscrypto.TLFCryptKey

MakeLocalTLFCryptKeyOrBust returns a unique private symmetric key for a TLF.

func MakeLocalUserCryptPrivateKeyOrBust

func MakeLocalUserCryptPrivateKeyOrBust(
	name kbname.NormalizedUsername) kbfscrypto.CryptPrivateKey

MakeLocalUserCryptPrivateKeyOrBust returns a unique private encryption key for this user.

func MakeLocalUserCryptPublicKeyOrBust

func MakeLocalUserCryptPublicKeyOrBust(
	name kbname.NormalizedUsername) kbfscrypto.CryptPublicKey

MakeLocalUserCryptPublicKeyOrBust returns the public key corresponding to the crypt private key for this user.

func MakeLocalUserSigningKeyOrBust

func MakeLocalUserSigningKeyOrBust(
	name kbname.NormalizedUsername) kbfscrypto.SigningKey

MakeLocalUserSigningKeyOrBust returns a unique signing key for this user.

func MakeLocalUserVerifyingKeyOrBust

func MakeLocalUserVerifyingKeyOrBust(
	name kbname.NormalizedUsername) kbfscrypto.VerifyingKey

MakeLocalUserVerifyingKeyOrBust makes a new verifying key corresponding to the signing key for this user.

func MakeRandomRequestID

func MakeRandomRequestID() (string, error)

MakeRandomRequestID generates a random ID suitable for tagging a request in KBFS, and very likely to be universally unique.

func NewContextReplayable

func NewContextReplayable(
	ctx context.Context, change CtxReplayFunc) context.Context

NewContextReplayable creates a new context from ctx, with change applied. It also makes this change replayable by NewContextWithReplayFrom. When replayed, the resulting context is replayable as well.

It is important that all WithValue-ish mutations on ctx is done "replayably" (with NewContextReplayable) if any delayed cancellation is used, e.g. through EnableDelayedCancellationWithGracePeriod,

func NewContextWithCancellationDelayer

func NewContextWithCancellationDelayer(
	ctx context.Context) (newCtx context.Context, err error)

NewContextWithCancellationDelayer creates a new context out of ctx. All replay functions attached to ctx are run on the new context. In addition, the new context is made "cancellation delayable". That is, it disconnects the cancelFunc from ctx, and watch for the cancellation. When cancellation happens, it checks if delayed cancellation is enabled for the associated context. If so, it waits until it's disabled before cancelling the new context. This provides a hacky way to allow finer control over cancellation.

Note that, it's important to call context.WithCancel (or its friends) before this function if those cancellations need to be controllable ("cancellation delayable"). Otherwise, the new cancelFunc is inherently NOT ("cancellation delayable").

If this function is called, it is caller's responsibility to either 1) cancel ctx (the context passed in); or 2) call CleanupCancellationDelayer; when operations associated with the context is done. Otherwise it leaks go routines!

func NewContextWithReplayFrom

func NewContextWithReplayFrom(ctx context.Context) (context.Context, error)

NewContextWithReplayFrom constructs a new context out of ctx by calling all attached replay functions. This disconnects any existing context.CancelFunc.

func NewEmptyTLFReaderKeyBundle

func NewEmptyTLFReaderKeyBundle() kbfsmd.TLFReaderKeyBundleV2

NewEmptyTLFReaderKeyBundle creates a new empty kbfsmd.TLFReaderKeyBundleV2

func NewEmptyTLFWriterKeyBundle

func NewEmptyTLFWriterKeyBundle() kbfsmd.TLFWriterKeyBundleV2

NewEmptyTLFWriterKeyBundle creates a new empty kbfsmd.TLFWriterKeyBundleV2

func NewReadAccessError

func NewReadAccessError(h *TlfHandle, username kbname.NormalizedUsername, filename string) error

NewReadAccessError constructs a ReadAccessError for the given directory and user.

func NewRekeyPermissionError

func NewRekeyPermissionError(
	dir *TlfHandle, username kbname.NormalizedUsername) error

NewRekeyPermissionError constructs a RekeyPermissionError for the given directory and user.

func NewSharedKeybaseConnection

func NewSharedKeybaseConnection(kbCtx Context, config Config,
	handler rpc.ConnectionHandler) *rpc.Connection

NewSharedKeybaseConnection returns a connection that tries to connect to the local keybase daemon.

func NewWriteAccessError

func NewWriteAccessError(h *TlfHandle, username kbname.NormalizedUsername, filename string) error

NewWriteAccessError is an access error trying to write a file

func NewWriteUnsupportedError

func NewWriteUnsupportedError(filename string) error

NewWriteUnsupportedError returns unsupported error trying to write a file

func PutBlockCheckLimitErrs

func PutBlockCheckLimitErrs(ctx context.Context, bserv BlockServer,
	reporter Reporter, tlfID tlf.ID, blockPtr BlockPointer,
	readyBlockData ReadyBlockData, tlfName tlf.CanonicalName,
	cacheType DiskBlockCacheType) error

PutBlockCheckLimitErrs is a thin wrapper around putBlockToServer (which calls either bserver.Put or bserver.AddBlockReference) that reports quota and disk limit errors.

func ReadyBlock

func ReadyBlock(ctx context.Context, bcache BlockCache, bops BlockOps,
	crypto cryptoPure, kmd KeyMetadata, block Block,
	chargedTo keybase1.UserOrTeamID, bType keybase1.BlockType) (
	info BlockInfo, plainSize int, readyBlockData ReadyBlockData, err error)

ReadyBlock is a thin wrapper around BlockOps.Ready() that handles checking for duplicates.

func RegisterOps

func RegisterOps(codec kbfscodec.Codec)

RegisterOps registers all op types with the given codec.

func RemoveTeamWriterForTest

func RemoveTeamWriterForTest(
	config Config, tid keybase1.TeamID, uid keybase1.UID) error

RemoveTeamWriterForTest removes the given user from a team.

func RemoveTeamWriterForTestOrBust

func RemoveTeamWriterForTestOrBust(t logger.TestLogBackend, config Config,
	tid keybase1.TeamID, uid keybase1.UID)

RemoveTeamWriterForTestOrBust is like RemoveTeamWriterForTest, but dies if there's an error.

func ResetRootBlock

func ResetRootBlock(ctx context.Context, config Config,
	rmd *RootMetadata) (Block, BlockInfo, ReadyBlockData, error)

ResetRootBlock creates a new empty dir block and sets the given metadata's root block to it.

func RestartCRForTesting

func RestartCRForTesting(baseCtx context.Context, config Config,
	folderBranch FolderBranch) error

RestartCRForTesting re-enables conflict resolution for the given folder. baseCtx must have a cancellation delayer.

func RevokeDeviceForLocalUserOrBust

func RevokeDeviceForLocalUserOrBust(t logger.TestLogBackend, config Config,
	uid keybase1.UID, index int)

RevokeDeviceForLocalUserOrBust revokes a device for a user in the given index.

func SetGlobalMerkleRootForTest

func SetGlobalMerkleRootForTest(
	config Config, root keybase1.MerkleRootV2, rootTime time.Time) error

SetGlobalMerkleRootForTest sets the global Merkle root and time.

func SetGlobalMerkleRootForTestOrBust

func SetGlobalMerkleRootForTestOrBust(
	t logger.TestLogBackend, config Config, root keybase1.MerkleRootV2,
	rootTime time.Time)

SetGlobalMerkleRootForTestOrBust is like SetGlobalMerkleRootForTest, but dies if there's an error.

func SetKbfsMerkleRootForTest

func SetKbfsMerkleRootForTest(
	config Config, treeID keybase1.MerkleTreeID,
	root *kbfsmd.MerkleRoot) error

SetKbfsMerkleRootForTest sets a Merkle root for the given KBFS tree ID.

func SetKbfsMerkleRootForTestOrBust

func SetKbfsMerkleRootForTestOrBust(
	t logger.TestLogBackend, config Config, treeID keybase1.MerkleTreeID,
	root *kbfsmd.MerkleRoot)

SetKbfsMerkleRootForTestOrBust is like SetKbfsMerkleRootForTest, but dies if there's an error.

func Shutdown

func Shutdown()

Shutdown does any necessary shutdown tasks for libkbfs. Shutdown should be called at the end of main.

func StallBlockOp

func StallBlockOp(ctx context.Context, config Config,
	stalledOp StallableBlockOp, maxStalls int) (
	onStalled <-chan struct{}, unstall chan<- struct{}, newCtx context.Context)

StallBlockOp sets a wrapped BlockOps in config so that the specified Op, stalledOp, is stalled. Caller should use the returned newCtx for subsequent operations for the stall to be effective. onStalled is a channel to notify the caller when the stall has happened. unstall is a channel for caller to unstall an Op.

func StallMDOp

func StallMDOp(ctx context.Context, config Config, stalledOp StallableMDOp,
	maxStalls int) (
	onStalled <-chan struct{}, unstall chan<- struct{}, newCtx context.Context)

StallMDOp sets a wrapped MDOps in config so that the specified Op, stalledOp, is stalled. Caller should use the returned newCtx for subsequent operations for the stall to be effective. onStalled is a channel to notify the caller when the stall has happened. unstall is a channel for caller to unstall an Op.

func SwitchDeviceForLocalUserOrBust

func SwitchDeviceForLocalUserOrBust(t logger.TestLogBackend, config Config, index int)

SwitchDeviceForLocalUserOrBust switches the current user's current device

func TLFJournalEnabled

func TLFJournalEnabled(config Config, tlfID tlf.ID) bool

TLFJournalEnabled returns true if journaling is enabled for the given TLF.

func VersionString

func VersionString() string

VersionString returns semantic version string

func WaitForTLFJournal

func WaitForTLFJournal(ctx context.Context, config Config, tlfID tlf.ID,
	log logger.Logger) error

WaitForTLFJournal waits for the corresponding journal to flush, if one exists.

Types

type AdditionalProtocolCreator

type AdditionalProtocolCreator func(Context, Config) (rpc.Protocol, error)

AdditionalProtocolCreator creates an additional protocol.

type BadCryptoError

type BadCryptoError struct {
	ID kbfsblock.ID
}

BadCryptoError indicates that KBFS performed a bad crypto operation.

func (BadCryptoError) Error

func (e BadCryptoError) Error() string

Error implements the error interface for BadCryptoError

type BadCryptoMDError

type BadCryptoMDError struct {
	ID tlf.ID
}

BadCryptoMDError indicates that KBFS performed a bad crypto operation, specifically on a MD object.

func (BadCryptoMDError) Error

func (e BadCryptoMDError) Error() string

Error implements the error interface for BadCryptoMDError

type BadDataError

type BadDataError struct {
	ID kbfsblock.ID
}

BadDataError indicates that KBFS is storing corrupt data for a block.

func (BadDataError) Error

func (e BadDataError) Error() string

Error implements the error interface for BadDataError

type BadMDError

type BadMDError struct {
	ID tlf.ID
}

BadMDError indicates that the system is storing corrupt MD object for the given TLF ID.

func (BadMDError) Error

func (e BadMDError) Error() string

Error implements the error interface for BadMDError

type BadSplitError

type BadSplitError struct {
}

BadSplitError indicates that the BlockSplitter has an error.

func (BadSplitError) Error

func (e BadSplitError) Error() string

Error implements the error interface for BadSplitError

type BadTLFNameError

type BadTLFNameError struct {
	Name string
}

BadTLFNameError indicates a top-level folder name that has an incorrect format.

func (BadTLFNameError) Error

func (e BadTLFNameError) Error() string

Error implements the error interface for BadTLFNameError.

type Block

type Block interface {

	// GetEncodedSize returns the encoded size of this block, but only
	// if it has been previously set; otherwise it returns 0.
	GetEncodedSize() uint32
	// SetEncodedSize sets the encoded size of this block, locally
	// caching it.  The encoded size is not serialized.
	SetEncodedSize(size uint32)
	// NewEmpty returns a new block of the same type as this block
	NewEmpty() Block
	// NewEmptier returns a function that creates a new block of the
	// same type as this block.
	NewEmptier() func() Block
	// Set sets this block to the same value as the passed-in block
	Set(other Block)
	// ToCommonBlock retrieves this block as a *CommonBlock.
	ToCommonBlock() *CommonBlock
	// IsIndirect indicates whether this block contains indirect pointers.
	IsIndirect() bool
	// IsTail returns true if this block doesn't point to any other
	// blocks, either indirectly or in child directory entries.
	IsTail() bool
	// OffsetExceedsData returns true if `off` is greater than the
	// data contained in a direct block, assuming it starts at
	// `startOff`.  Note that the offset of the next block isn't
	// relevant; this function should only indicate whether the offset
	// is greater than what currently could be stored in this block.
	OffsetExceedsData(startOff, off Offset) bool
	// BytesCanBeDirtied returns the number of bytes that should be
	// marked as dirtied if this block is dirtied.
	BytesCanBeDirtied() int64
	// contains filtered or unexported methods
}

Block just needs to be (de)serialized using msgpack

func NewCommonBlock

func NewCommonBlock() Block

NewCommonBlock returns a generic block, unsuitable for caching.

func NewDirBlock

func NewDirBlock() Block

NewDirBlock creates a new, empty DirBlock.

func NewFileBlock

func NewFileBlock() Block

NewFileBlock creates a new, empty FileBlock.

type BlockCache

type BlockCache interface {
	BlockCacheSimple
	// CheckForKnownPtr sees whether this cache has a transient
	// entry for the given file block, which must be a direct file
	// block containing data).  Returns the full BlockPointer
	// associated with that ID, including key and data versions.
	// If no ID is known, return an uninitialized BlockPointer and
	// a nil error.
	CheckForKnownPtr(tlf tlf.ID, block *FileBlock) (BlockPointer, error)
	// DeleteTransient removes the transient entry for the given
	// ID from the cache, as well as any cached IDs so the block
	// won't be reused.
	DeleteTransient(id kbfsblock.ID, tlf tlf.ID) error
	// Delete removes the permanent entry for the non-dirty block
	// associated with the given block ID from the cache.  No
	// error is returned if no block exists for the given ID.
	DeletePermanent(id kbfsblock.ID) error
	// DeleteKnownPtr removes the cached ID for the given file
	// block. It does not remove the block itself.
	DeleteKnownPtr(tlf tlf.ID, block *FileBlock) error
	// GetWithLifetime retrieves a block from the cache, along with
	// the block's lifetime.
	GetWithLifetime(ptr BlockPointer) (
		block Block, lifetime BlockCacheLifetime, err error)

	// SetCleanBytesCapacity atomically sets clean bytes capacity for block
	// cache.
	SetCleanBytesCapacity(capacity uint64)

	// GetCleanBytesCapacity atomically gets clean bytes capacity for block
	// cache.
	GetCleanBytesCapacity() (capacity uint64)
}

BlockCache specifies the interface of BlockCacheSimple, and also more advanced and internal methods.

type BlockCacheLifetime

type BlockCacheLifetime int

BlockCacheLifetime denotes the lifetime of an entry in BlockCache.

const (
	// NoCacheEntry means that the entry will not be cached.
	NoCacheEntry BlockCacheLifetime = iota
	// TransientEntry means that the cache entry may be evicted at
	// any time.
	TransientEntry
	// PermanentEntry means that the cache entry must remain until
	// explicitly removed from the cache.
	PermanentEntry
)

func (BlockCacheLifetime) String

func (l BlockCacheLifetime) String() string

type BlockCacheSimple

type BlockCacheSimple interface {
	// Get gets the block associated with the given block ID.
	Get(ptr BlockPointer) (Block, error)
	// Put stores the final (content-addressable) block associated
	// with the given block ID. If lifetime is TransientEntry,
	// then it is assumed that the block exists on the server and
	// the entry may be evicted from the cache at any time. If
	// lifetime is PermanentEntry, then it is assumed that the
	// block doesn't exist on the server and must remain in the
	// cache until explicitly removed. As an intermediary state,
	// as when a block is being sent to the server, the block may
	// be put into the cache both with TransientEntry and
	// PermanentEntry -- these are two separate entries. This is
	// fine, since the block should be the same.
	Put(ptr BlockPointer, tlf tlf.ID, block Block,
		lifetime BlockCacheLifetime) error
}

BlockCacheSimple gets and puts plaintext dir blocks and file blocks into a cache. These blocks are immutable and identified by their content hash.

type BlockCacheStandard

type BlockCacheStandard struct {
	// contains filtered or unexported fields
}

BlockCacheStandard implements the BlockCache interface by storing blocks in an in-memory LRU cache. Clean blocks are identified internally by just their block ID (since blocks are immutable and content-addressable).

func NewBlockCacheStandard

func NewBlockCacheStandard(transientCapacity int,
	cleanBytesCapacity uint64) *BlockCacheStandard

NewBlockCacheStandard constructs a new BlockCacheStandard instance with the given transient capacity (in number of entries) and the clean bytes capacity, which is the total of number of bytes allowed between the transient and permanent clean caches. If putting a block will exceed this bytes capacity, transient entries are evicted until the block will fit in capacity.

func (*BlockCacheStandard) CheckForKnownPtr

func (b *BlockCacheStandard) CheckForKnownPtr(tlf tlf.ID, block *FileBlock) (
	BlockPointer, error)

CheckForKnownPtr implements the BlockCache interface for BlockCacheStandard.

func (*BlockCacheStandard) DeleteKnownPtr

func (b *BlockCacheStandard) DeleteKnownPtr(tlf tlf.ID, block *FileBlock) error

DeleteKnownPtr implements the BlockCache interface for BlockCacheStandard.

func (*BlockCacheStandard) DeletePermanent

func (b *BlockCacheStandard) DeletePermanent(id kbfsblock.ID) error

DeletePermanent implements the BlockCache interface for BlockCacheStandard.

func (*BlockCacheStandard) DeleteTransient

func (b *BlockCacheStandard) DeleteTransient(
	id kbfsblock.ID, tlf tlf.ID) error

DeleteTransient implements the BlockCache interface for BlockCacheStandard.

func (*BlockCacheStandard) Get

func (b *BlockCacheStandard) Get(ptr BlockPointer) (Block, error)

Get implements the BlockCache interface for BlockCacheStandard.

func (*BlockCacheStandard) GetCleanBytesCapacity

func (b *BlockCacheStandard) GetCleanBytesCapacity() (capacity uint64)

GetCleanBytesCapacity implements the BlockCache interface for BlockCacheStandard.

func (*BlockCacheStandard) GetWithLifetime

func (b *BlockCacheStandard) GetWithLifetime(ptr BlockPointer) (
	Block, BlockCacheLifetime, error)

GetWithLifetime implements the BlockCache interface for BlockCacheStandard.

func (*BlockCacheStandard) Put

func (b *BlockCacheStandard) Put(
	ptr BlockPointer, tlf tlf.ID, block Block,
	lifetime BlockCacheLifetime) error

Put implements the BlockCache interface for BlockCacheStandard. This method is idempotent for a given ptr, but that invariant is not currently goroutine-safe, and it does not hold if a block size changes between Puts. That is, we assume that a cached block associated with a given pointer will never change its size, even when it gets Put into the cache again.

func (*BlockCacheStandard) SetCleanBytesCapacity

func (b *BlockCacheStandard) SetCleanBytesCapacity(capacity uint64)

SetCleanBytesCapacity implements the BlockCache interface for BlockCacheStandard.

type BlockChanges

type BlockChanges struct {
	// If this is set, the actual changes are stored in a block (where
	// the block contains a serialized version of BlockChanges)
	//
	// Ideally, we'd omit Info if it's empty. However, old clients
	// rely on encoded BlockChanges always having an encoded Info,
	// so that decoding into an existing BlockChanges object
	// clobbers any existing Info, so we can't omit Info until all
	// clients have upgraded to a version that explicitly clears
	// Info on decode, and we've verified that there's nothing
	// else that relies on Info always being filled.
	Info BlockInfo `codec:"p"`
	// An ordered list of operations completed in this update
	Ops opsList `codec:"o,omitempty"`
	// contains filtered or unexported fields
}

BlockChanges tracks the set of blocks that changed in a commit, and the operations that made the changes. It might consist of just a BlockPointer if the list is too big to embed in the MD structure directly.

If this commit represents a conflict-resolution merge, which may comprise multiple individual operations, then there will be an ordered list of the changes for individual operations. This lets the notification and conflict resolution strategies figure out the difference between a renamed file and a modified file, for example.

NOTE: Don't add or modify anything in this struct without considering how old clients will handle them.

func (*BlockChanges) AddOp

func (bc *BlockChanges) AddOp(o op)

AddOp starts a new operation for this BlockChanges. Subsequent Add* calls will populate this operation.

func (*BlockChanges) AddRefBlock

func (bc *BlockChanges) AddRefBlock(ptr BlockPointer)

AddRefBlock adds the newly-referenced block to this BlockChanges and updates the size estimate.

func (*BlockChanges) AddUnrefBlock

func (bc *BlockChanges) AddUnrefBlock(ptr BlockPointer)

AddUnrefBlock adds the newly unreferenced block to this BlockChanges and updates the size estimate.

func (*BlockChanges) AddUpdate

func (bc *BlockChanges) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer)

AddUpdate adds the newly updated block to this BlockChanges and updates the size estimate.

func (BlockChanges) Equals

func (bc BlockChanges) Equals(other BlockChanges) bool

Equals returns true if the given BlockChanges is equal to this BlockChanges. Currently does not check for equality at the operation level.

func (*BlockChanges) SizeEstimate

func (bc *BlockChanges) SizeEstimate() uint64

SizeEstimate calculates the estimated size of the encoded version of this BlockChanges.

type BlockDecodeError

type BlockDecodeError struct {
	// contains filtered or unexported fields
}

BlockDecodeError indicates that a block couldn't be decoded as expected; probably it is the wrong type.

func (BlockDecodeError) Error

func (e BlockDecodeError) Error() string

Error implements the error interface for BlockDecodeError

type BlockDirectType

type BlockDirectType int

BlockDirectType indicates to what kind of block (direct or indirect) a BlockPointer points.

const (
	// UnknownDirectType indicates an old block that was written
	// before we started labeling pointers.
	UnknownDirectType BlockDirectType = 0
	// DirectBlock indicates the pointed-to block has no indirect
	// pointers.
	DirectBlock BlockDirectType = 1
	// IndirectBlock indicates the pointed-to block has indirect
	// pointers.
	IndirectBlock BlockDirectType = 2
)

func (BlockDirectType) String

func (bdt BlockDirectType) String() string

type BlockInfo

type BlockInfo struct {
	BlockPointer
	// When non-zero, the size of the encoded (and possibly
	// encrypted) data contained in the block. When non-zero,
	// always at least the size of the plaintext data contained in
	// the block.
	EncodedSize uint32 `codec:"e"`
}

BlockInfo contains all information about a block in KBFS and its contents.

NOTE: Don't add or modify anything in this struct without considering how old clients will handle them.

func (BlockInfo) String

func (bi BlockInfo) String() string

type BlockMetadataStore

type BlockMetadataStore interface {
	// GetMetadata looks for and returns the block metadata for blockID if it's
	// found, and an error whose Cause is ldberrors.ErrNotFound if it's not
	// found.
	GetMetadata(ctx context.Context, blockID kbfsblock.ID) (BlockMetadataValue, error)
	// UpdateMetadata updates the block metadata for blockID using updater.
	// Specifically, it looks for existing block metdata for blockID. If it's
	// found, it's passed into updater. Otherwise, a zero value of
	// BlockMetadataValue is passed into the updater. After if updater returns
	// nil, the updated metadata is stored.
	UpdateMetadata(ctx context.Context, blockID kbfsblock.ID, updater BlockMetadataUpdater) error
	// Shutdown cleanly shuts down the disk block metadata cache.
	Shutdown()
}

BlockMetadataStore defines a type that stores block metadata locally on device.

type BlockMetadataUpdater

type BlockMetadataUpdater func(*BlockMetadataValue) error

BlockMetadataUpdater defines a function to update a BlockMetadataValue.

type BlockMetadataValue

type BlockMetadataValue struct {
	// Xattr contains all xattrs stored in association with the block. This is
	// useful for stuff that's contingent to content of the block, such as
	// quarantine data.
	Xattr map[XattrType][]byte
}

BlockMetadataValue represents the value stored in the block metadata store. This is usually locally stored, and is separate from block metadata stored on bserver.

type BlockOps

type BlockOps interface {

	// Get gets the block associated with the given block pointer
	// (which belongs to the TLF with the given key metadata),
	// decrypts it if necessary, and fills in the provided block
	// object with its contents, if the logged-in user has read
	// permission for that block. cacheLifetime controls the behavior of the
	// write-through cache once a Get completes.
	Get(ctx context.Context, kmd KeyMetadata, blockPtr BlockPointer,
		block Block, cacheLifetime BlockCacheLifetime) error

	// GetEncodedSize gets the encoded size of the block associated
	// with the given block pointer (which belongs to the TLF with the
	// given key metadata).
	GetEncodedSize(ctx context.Context, kmd KeyMetadata,
		blockPtr BlockPointer) (uint32, keybase1.BlockStatus, error)

	// Ready turns the given block (which belongs to the TLF with
	// the given key metadata) into encoded (and encrypted) data,
	// and calculates its ID and size, so that we can do a bunch
	// of block puts in parallel for every write. Ready() must
	// guarantee that plainSize <= readyBlockData.QuotaSize().
	Ready(ctx context.Context, kmd KeyMetadata, block Block) (
		id kbfsblock.ID, plainSize int, readyBlockData ReadyBlockData, err error)

	// Delete instructs the server to delete the given block references.
	// It returns the number of not-yet deleted references to
	// each block reference
	Delete(ctx context.Context, tlfID tlf.ID, ptrs []BlockPointer) (
		liveCounts map[kbfsblock.ID]int, err error)

	// Archive instructs the server to mark the given block references
	// as "archived"; that is, they are not being used in the current
	// view of the folder, and shouldn't be served to anyone other
	// than folder writers.
	Archive(ctx context.Context, tlfID tlf.ID, ptrs []BlockPointer) error

	// GetLiveCount returns the number of "live"
	// (non-archived, non-deleted) references for each given block.
	GetLiveCount(
		ctx context.Context, tlfID tlf.ID, ptrs []BlockPointer) (
		liveCounts map[kbfsblock.ID]int, err error)

	// TogglePrefetcher activates or deactivates the prefetcher.
	TogglePrefetcher(enable bool) <-chan struct{}

	// Prefetcher retrieves this BlockOps' Prefetcher.
	Prefetcher() Prefetcher

	// Shutdown shuts down all the workers performing Get operations
	Shutdown()
	// contains filtered or unexported methods
}

BlockOps gets and puts data blocks to a BlockServer. It performs the necessary crypto operations on each block.

type BlockOpsConstrained

type BlockOpsConstrained struct {
	BlockOps
	// contains filtered or unexported fields
}

BlockOpsConstrained implements the BlockOps interface by relaying requests to a delegate BlockOps, but it delays all Puts by simulating a bottleneck of the given bandwidth.

func NewBlockOpsConstrained

func NewBlockOpsConstrained(delegate BlockOps, bwKBps int) *BlockOpsConstrained

NewBlockOpsConstrained constructs a new BlockOpsConstrained.

type BlockOpsStandard

type BlockOpsStandard struct {
	// contains filtered or unexported fields
}

BlockOpsStandard implements the BlockOps interface by relaying requests to the block server.

func NewBlockOpsStandard

func NewBlockOpsStandard(
	config blockOpsConfig, queueSize, prefetchQueueSize int,
	throttledPrefetchPeriod time.Duration) *BlockOpsStandard

NewBlockOpsStandard creates a new BlockOpsStandard

func (*BlockOpsStandard) Archive

func (b *BlockOpsStandard) Archive(ctx context.Context, tlfID tlf.ID,
	ptrs []BlockPointer) error

Archive implements the BlockOps interface for BlockOpsStandard.

func (*BlockOpsStandard) BlockRetriever

func (b *BlockOpsStandard) BlockRetriever() BlockRetriever

BlockRetriever implements the BlockOps interface for BlockOpsStandard.

func (*BlockOpsStandard) Delete

func (b *BlockOpsStandard) Delete(ctx context.Context, tlfID tlf.ID,
	ptrs []BlockPointer) (liveCounts map[kbfsblock.ID]int, err error)

Delete implements the BlockOps interface for BlockOpsStandard.

func (*BlockOpsStandard) Get

func (b *BlockOpsStandard) Get(ctx context.Context, kmd KeyMetadata,
	blockPtr BlockPointer, block Block, lifetime BlockCacheLifetime) error

Get implements the BlockOps interface for BlockOpsStandard.

func (*BlockOpsStandard) GetEncodedSize

func (b *BlockOpsStandard) GetEncodedSize(ctx context.Context, kmd KeyMetadata,
	blockPtr BlockPointer) (uint32, keybase1.BlockStatus, error)

GetEncodedSize implements the BlockOps interface for BlockOpsStandard.

func (*BlockOpsStandard) GetLiveCount

func (b *BlockOpsStandard) GetLiveCount(
	ctx context.Context, tlfID tlf.ID, ptrs []BlockPointer) (
	liveCounts map[kbfsblock.ID]int, err error)

GetLiveCount implements the BlockOps interface for BlockOpsStandard.

func (*BlockOpsStandard) Prefetcher

func (b *BlockOpsStandard) Prefetcher() Prefetcher

Prefetcher implements the BlockOps interface for BlockOpsStandard.

func (*BlockOpsStandard) Ready

func (b *BlockOpsStandard) Ready(ctx context.Context, kmd KeyMetadata,
	block Block) (id kbfsblock.ID, plainSize int, readyBlockData ReadyBlockData,
	err error)

Ready implements the BlockOps interface for BlockOpsStandard.

func (*BlockOpsStandard) Shutdown

func (b *BlockOpsStandard) Shutdown()

Shutdown implements the BlockOps interface for BlockOpsStandard.

func (*BlockOpsStandard) TogglePrefetcher

func (b *BlockOpsStandard) TogglePrefetcher(enable bool) <-chan struct{}

TogglePrefetcher implements the BlockOps interface for BlockOpsStandard.

type BlockPointer

type BlockPointer struct {
	ID         kbfsblock.ID    `codec:"i"`
	KeyGen     kbfsmd.KeyGen   `codec:"k"`           // if valid, which generation of the TLF{Writer,Reader}KeyBundle to use.
	DataVer    DataVer         `codec:"d"`           // if valid, which version of the KBFS data structures is pointed to
	DirectType BlockDirectType `codec:"t,omitempty"` // the type (direct, indirect, or unknown [if omitted]) of the pointed-to block
	kbfsblock.Context
}

BlockPointer contains the identifying information for a block in KBFS.

NOTE: Don't add or modify anything in this struct without considering how old clients will handle them.

func (BlockPointer) IsInitialized

func (p BlockPointer) IsInitialized() bool

IsInitialized returns whether or not this BlockPointer has non-nil data.

func (BlockPointer) IsValid

func (p BlockPointer) IsValid() bool

IsValid returns whether the block pointer is valid. A zero block pointer is considered invalid.

func (BlockPointer) Ref

func (p BlockPointer) Ref() BlockRef

Ref returns the BlockRef equivalent of this pointer.

func (BlockPointer) String

func (p BlockPointer) String() string

type BlockRef

type BlockRef struct {
	ID       kbfsblock.ID
	RefNonce kbfsblock.RefNonce
}

BlockRef is a block ID/ref nonce pair, which defines a unique reference to a block.

func (BlockRef) IsValid

func (r BlockRef) IsValid() bool

IsValid returns true exactly when ID.IsValid() does.

func (BlockRef) String

func (r BlockRef) String() string

type BlockRequestAction

type BlockRequestAction int

BlockRequestAction indicates what kind of action should be taken after successfully fetching a block. This is a bit mask filled with `blockRequestFlag`s.

const (

	// BlockRequestSolo indicates that no action should take place
	// after fetching the block.  However, a TLF that is configured to
	// be fully-synced will still be prefetched and synced.
	BlockRequestSolo BlockRequestAction = 0
	// BlockRequestSoloWithSync indicates the the requested block
	// should be put in the sync cache, but no prefetching should be
	// triggered.
	BlockRequestSoloWithSync BlockRequestAction = blockRequestSync
	// BlockRequestPrefetchTail indicates that the block is being
	// tracked in the prefetcher, but shouldn't kick off any more
	// prefetches.
	BlockRequestPrefetchTail BlockRequestAction = blockRequestTrackedInPrefetch
	// BlockRequestPrefetchTailWithSync indicates that the block is
	// being tracked in the prefetcher and goes in the sync cache, but
	// shouldn't kick off any more prefetches.
	BlockRequestPrefetchTailWithSync BlockRequestAction = blockRequestTrackedInPrefetch | blockRequestSync
	// BlockRequestWithPrefetch indicates that a prefetch should be
	// triggered after fetching the block.  If a TLF is configured to
	// be fully-synced, the block will still be put in the sync cache.
	BlockRequestWithPrefetch BlockRequestAction = blockRequestTrackedInPrefetch | blockRequestPrefetch
	// BlockRequestWithSyncAndPrefetch indicates that the block should
	// be stored in the sync cache after fetching it, as well as
	// triggering a prefetch of one level of child blocks (and the
	// syncing doesn't propagate to the child blocks).
	BlockRequestWithSyncAndPrefetch BlockRequestAction = blockRequestTrackedInPrefetch | blockRequestPrefetch | blockRequestSync
	// BlockRequestPrefetchUntilFull prefetches starting from the
	// given block (but does not sync the blocks) until the working
	// set cache is full, and then it stops prefetching.
	BlockRequestPrefetchUntilFull BlockRequestAction = blockRequestTrackedInPrefetch | blockRequestPrefetch | blockRequestStopIfFull
	// BlockRequestWithDeepSync is the same as above, except both the
	// prefetching and the sync flags propagate to the child, so the
	// whole tree root at the block is prefetched and synced.
	BlockRequestWithDeepSync BlockRequestAction = blockRequestTrackedInPrefetch | blockRequestPrefetch | blockRequestSync | blockRequestDeepSync
)

func (BlockRequestAction) AddSync

func (bra BlockRequestAction) AddSync() BlockRequestAction

AddSync returns a new action that adds syncing in addition to the original request. For prefetch requests, it returns a deep-sync request (unlike `Combine`, which just adds the regular sync bit).

func (BlockRequestAction) CacheType

func (bra BlockRequestAction) CacheType() DiskBlockCacheType

CacheType returns the disk block cache type that should be used, according to the type of action.

func (BlockRequestAction) ChildAction

func (bra BlockRequestAction) ChildAction(block Block) BlockRequestAction

ChildAction returns the action that should propagate down to any children of this block.

func (BlockRequestAction) Combine

Combine returns a new action by taking `other` into account.

func (BlockRequestAction) DeepPrefetch

func (bra BlockRequestAction) DeepPrefetch() bool

DeepPrefetch returns true if the prefetcher should continue prefetching the children of this block all the way to the leafs of the tree.

func (BlockRequestAction) DeepSync

func (bra BlockRequestAction) DeepSync() bool

DeepSync returns true if the action indicates a deep-syncing of the block tree rooted at the given block.

func (BlockRequestAction) Prefetch

func (bra BlockRequestAction) Prefetch(block Block) bool

Prefetch returns true if the action indicates the block should trigger a prefetch.

func (BlockRequestAction) PrefetchTracked

func (bra BlockRequestAction) PrefetchTracked() bool

PrefetchTracked returns true if this block is being tracked by the prefetcher.

func (BlockRequestAction) SoloAction

func (bra BlockRequestAction) SoloAction() BlockRequestAction

SoloAction returns a solo-fetch action based on `bra` (e.g., preserving the sync bit but nothing else).

func (BlockRequestAction) StopIfFull

func (bra BlockRequestAction) StopIfFull() bool

StopIfFull returns true if prefetching should stop for good (i.e., not get rescheduled) when the corresponding disk cache is full.

func (BlockRequestAction) String

func (bra BlockRequestAction) String() string

func (BlockRequestAction) Sync

func (bra BlockRequestAction) Sync() bool

Sync returns true if the action indicates the block should go into the sync cache.

type BlockRetriever

type BlockRetriever interface {
	// Request retrieves blocks asynchronously.  `action` determines
	// what happens after the block is fetched successfully.
	Request(ctx context.Context, priority int, kmd KeyMetadata,
		ptr BlockPointer, block Block, lifetime BlockCacheLifetime,
		action BlockRequestAction) <-chan error
	// PutInCaches puts the block into the in-memory cache, and ensures that
	// the disk cache metadata is updated.
	PutInCaches(ctx context.Context, ptr BlockPointer, tlfID tlf.ID,
		block Block, lifetime BlockCacheLifetime,
		prefetchStatus PrefetchStatus) error
	// TogglePrefetcher creates a new prefetcher.
	TogglePrefetcher(enable bool, syncCh <-chan struct{}) <-chan struct{}
}

BlockRetriever specifies how to retrieve blocks.

type BlockServer

type BlockServer interface {

	// Get gets the (encrypted) block data associated with the given
	// block ID and context, uses the provided block key to decrypt
	// the block, and fills in the provided block object with its
	// contents, if the logged-in user has read permission for that
	// block.
	Get(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
		context kbfsblock.Context, cacheType DiskBlockCacheType) (
		[]byte, kbfscrypto.BlockCryptKeyServerHalf, error)

	// GetEncodedSize gets the encoded size of the block associated
	// with the given block pointer (which belongs to the TLF with the
	// given key metadata).
	GetEncodedSize(
		ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
		context kbfsblock.Context) (uint32, keybase1.BlockStatus, error)

	// Put stores the (encrypted) block data under the given ID
	// and context on the server, along with the server half of
	// the block key.  context should contain a kbfsblock.RefNonce
	// of zero.  There will be an initial reference for this block
	// for the given context.
	//
	// Put should be idempotent, although it should also return an
	// error if, for a given ID, any of the other arguments differ
	// from previous Put calls with the same ID.
	//
	// If this returns a kbfsblock.ServerErrorOverQuota, with
	// Throttled=false, the caller can treat it as informational
	// and otherwise ignore the error.
	Put(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
		context kbfsblock.Context, buf []byte,
		serverHalf kbfscrypto.BlockCryptKeyServerHalf,
		cacheType DiskBlockCacheType) error

	// PutAgain re-stores a previously deleted block under the same ID
	// with the same data.
	PutAgain(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
		context kbfsblock.Context, buf []byte,
		serverHalf kbfscrypto.BlockCryptKeyServerHalf,
		cacheType DiskBlockCacheType) error

	// AddBlockReference adds a new reference to the given block,
	// defined by the given context (which should contain a
	// non-zero kbfsblock.RefNonce).  (Contexts with a
	// kbfsblock.RefNonce of zero should be used when putting the
	// block for the first time via Put().)  Returns a
	// kbfsblock.ServerErrorBlockNonExistent if id is unknown within this
	// folder.
	//
	// AddBlockReference should be idempotent, although it should
	// also return an error if, for a given ID and refnonce, any
	// of the other fields of context differ from previous
	// AddBlockReference calls with the same ID and refnonce.
	//
	// If this returns a kbfsblock.ServerErrorOverQuota, with
	// Throttled=false, the caller can treat it as informational
	// and otherwise ignore the error.
	AddBlockReference(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
		context kbfsblock.Context) error
	// RemoveBlockReferences removes the references to the given block
	// ID defined by the given contexts.  If no references to the block
	// remain after this call, the server is allowed to delete the
	// corresponding block permanently.  If the reference defined by
	// the count has already been removed, the call is a no-op.
	// It returns the number of remaining not-yet-deleted references after this
	// reference has been removed
	RemoveBlockReferences(ctx context.Context, tlfID tlf.ID,
		contexts kbfsblock.ContextMap) (liveCounts map[kbfsblock.ID]int, err error)

	// ArchiveBlockReferences marks the given block references as
	// "archived"; that is, they are not being used in the current
	// view of the folder, and shouldn't be served to anyone other
	// than folder writers.
	//
	// For a given ID/refnonce pair, ArchiveBlockReferences should
	// be idempotent, although it should also return an error if
	// any of the other fields of the context differ from previous
	// calls with the same ID/refnonce pair.
	ArchiveBlockReferences(ctx context.Context, tlfID tlf.ID,
		contexts kbfsblock.ContextMap) error

	// GetLiveBlockReferences returns the number of "live"
	// (non-archived, non-deleted) references for each given block.
	GetLiveBlockReferences(ctx context.Context, tlfID tlf.ID,
		contexts kbfsblock.ContextMap) (
		liveCounts map[kbfsblock.ID]int, err error)

	// IsUnflushed returns whether a given block is being queued
	// locally for later flushing to another block server.  If the
	// block is currently being flushed to the server, this should
	// return `true`, so that the caller will try to clean it up from
	// the server if it's no longer needed.
	IsUnflushed(ctx context.Context, tlfID tlf.ID, id kbfsblock.ID) (
		bool, error)

	// Shutdown is called to shutdown a BlockServer connection.
	Shutdown(ctx context.Context)

	// GetUserQuotaInfo returns the quota for the logged-in user.
	GetUserQuotaInfo(ctx context.Context) (info *kbfsblock.QuotaInfo, err error)

	// GetTeamQuotaInfo returns the quota for a team.
	GetTeamQuotaInfo(ctx context.Context, tid keybase1.TeamID) (
		info *kbfsblock.QuotaInfo, err error)
	// contains filtered or unexported methods
}

BlockServer gets and puts opaque data blocks. The instantiation should be able to fetch session/user details via KBPKI. On a put/delete, the server is reponsible for: 1) checking that the ID matches the hash of the buffer; and 2) enforcing writer quotas.

func MakeTestBlockServerOrBust

func MakeTestBlockServerOrBust(t logger.TestLogBackend,
	config blockServerRemoteConfig,
	rpcLogFactory rpc.LogFactory) BlockServer

MakeTestBlockServerOrBust makes a block server from the given arguments and environment variables.

type BlockServerDisk

type BlockServerDisk struct {
	// contains filtered or unexported fields
}

BlockServerDisk implements the BlockServer interface by just storing blocks in a local disk store.

func NewBlockServerDir

func NewBlockServerDir(codec kbfscodec.Codec,
	log logger.Logger, dirPath string) *BlockServerDisk

NewBlockServerDir constructs a new BlockServerDisk that stores its data in the given directory.

func NewBlockServerTempDir

func NewBlockServerTempDir(codec kbfscodec.Codec,
	log logger.Logger) (*BlockServerDisk, error)

NewBlockServerTempDir constructs a new BlockServerDisk that stores its data in a temp directory which is cleaned up on shutdown.

func (*BlockServerDisk) AddBlockReference

func (b *BlockServerDisk) AddBlockReference(ctx context.Context, tlfID tlf.ID,
	id kbfsblock.ID, context kbfsblock.Context) error

AddBlockReference implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) ArchiveBlockReferences

func (b *BlockServerDisk) ArchiveBlockReferences(ctx context.Context,
	tlfID tlf.ID, contexts kbfsblock.ContextMap) (err error)

ArchiveBlockReferences implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) Get

func (b *BlockServerDisk) Get(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, _ DiskBlockCacheType) (
	data []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf, err error)

Get implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) GetEncodedSize

func (b *BlockServerDisk) GetEncodedSize(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context) (
	size uint32, status keybase1.BlockStatus, err error)

GetEncodedSize implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) GetLiveBlockReferences

func (b *BlockServerDisk) GetLiveBlockReferences(
	ctx context.Context, tlfID tlf.ID, contexts kbfsblock.ContextMap) (
	liveCounts map[kbfsblock.ID]int, err error)

GetLiveBlockReferences implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) GetTeamQuotaInfo

func (b *BlockServerDisk) GetTeamQuotaInfo(
	ctx context.Context, _ keybase1.TeamID) (
	info *kbfsblock.QuotaInfo, err error)

GetTeamQuotaInfo implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) GetUserQuotaInfo

func (b *BlockServerDisk) GetUserQuotaInfo(ctx context.Context) (info *kbfsblock.QuotaInfo, err error)

GetUserQuotaInfo implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) IsUnflushed

func (b *BlockServerDisk) IsUnflushed(ctx context.Context, tlfID tlf.ID,
	_ kbfsblock.ID) (bool, error)

IsUnflushed implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) Put

func (b *BlockServerDisk) Put(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	_ DiskBlockCacheType) (err error)

Put implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) PutAgain

func (b *BlockServerDisk) PutAgain(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	_ DiskBlockCacheType) (err error)

PutAgain implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) RefreshAuthToken

func (b *BlockServerDisk) RefreshAuthToken(_ context.Context)

RefreshAuthToken implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) RemoveBlockReferences

func (b *BlockServerDisk) RemoveBlockReferences(ctx context.Context,
	tlfID tlf.ID, contexts kbfsblock.ContextMap) (
	liveCounts map[kbfsblock.ID]int, err error)

RemoveBlockReferences implements the BlockServer interface for BlockServerDisk.

func (*BlockServerDisk) Shutdown

func (b *BlockServerDisk) Shutdown(ctx context.Context)

Shutdown implements the BlockServer interface for BlockServerDisk.

type BlockServerMeasured

type BlockServerMeasured struct {
	// contains filtered or unexported fields
}

BlockServerMeasured delegates to another BlockServer instance but also keeps track of stats.

func NewBlockServerMeasured

func NewBlockServerMeasured(delegate BlockServer, r metrics.Registry) BlockServerMeasured

NewBlockServerMeasured creates and returns a new BlockServerMeasured instance with the given delegate and registry.

func (BlockServerMeasured) AddBlockReference

func (b BlockServerMeasured) AddBlockReference(ctx context.Context, tlfID tlf.ID,
	id kbfsblock.ID, context kbfsblock.Context) (err error)

AddBlockReference implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) ArchiveBlockReferences

func (b BlockServerMeasured) ArchiveBlockReferences(ctx context.Context,
	tlfID tlf.ID, contexts kbfsblock.ContextMap) (err error)

ArchiveBlockReferences implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) Get

func (b BlockServerMeasured) Get(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, cacheType DiskBlockCacheType) (
	buf []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf, err error)

Get implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) GetEncodedSize

func (b BlockServerMeasured) GetEncodedSize(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context) (
	size uint32, status keybase1.BlockStatus, err error)

GetEncodedSize implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) GetLiveBlockReferences

func (b BlockServerMeasured) GetLiveBlockReferences(
	ctx context.Context, tlfID tlf.ID, contexts kbfsblock.ContextMap) (
	liveCounts map[kbfsblock.ID]int, err error)

GetLiveBlockReferences implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) GetTeamQuotaInfo

func (b BlockServerMeasured) GetTeamQuotaInfo(
	ctx context.Context, tid keybase1.TeamID) (
	info *kbfsblock.QuotaInfo, err error)

GetTeamQuotaInfo implements the BlockServer interface for BlockServerMeasured

func (BlockServerMeasured) GetUserQuotaInfo

func (b BlockServerMeasured) GetUserQuotaInfo(ctx context.Context) (info *kbfsblock.QuotaInfo, err error)

GetUserQuotaInfo implements the BlockServer interface for BlockServerMeasured

func (BlockServerMeasured) IsUnflushed

func (b BlockServerMeasured) IsUnflushed(ctx context.Context, tlfID tlf.ID,
	id kbfsblock.ID) (isUnflushed bool, err error)

IsUnflushed implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) Put

func (b BlockServerMeasured) Put(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	cacheType DiskBlockCacheType) (err error)

Put implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) PutAgain

func (b BlockServerMeasured) PutAgain(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	cacheType DiskBlockCacheType) (err error)

PutAgain implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) RefreshAuthToken

func (b BlockServerMeasured) RefreshAuthToken(ctx context.Context)

RefreshAuthToken implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) RemoveBlockReferences

func (b BlockServerMeasured) RemoveBlockReferences(ctx context.Context,
	tlfID tlf.ID, contexts kbfsblock.ContextMap) (
	liveCounts map[kbfsblock.ID]int, err error)

RemoveBlockReferences implements the BlockServer interface for BlockServerMeasured.

func (BlockServerMeasured) Shutdown

func (b BlockServerMeasured) Shutdown(ctx context.Context)

Shutdown implements the BlockServer interface for BlockServerMeasured.

type BlockServerMemory

type BlockServerMemory struct {
	// contains filtered or unexported fields
}

BlockServerMemory implements the BlockServer interface by just storing blocks in memory.

func NewBlockServerMemory

func NewBlockServerMemory(log logger.Logger) *BlockServerMemory

NewBlockServerMemory constructs a new BlockServerMemory that stores its data in memory.

func (*BlockServerMemory) AddBlockReference

func (b *BlockServerMemory) AddBlockReference(ctx context.Context, tlfID tlf.ID,
	id kbfsblock.ID, context kbfsblock.Context) (err error)

AddBlockReference implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) ArchiveBlockReferences

func (b *BlockServerMemory) ArchiveBlockReferences(ctx context.Context,
	tlfID tlf.ID, contexts kbfsblock.ContextMap) (err error)

ArchiveBlockReferences implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) Get

func (b *BlockServerMemory) Get(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, _ DiskBlockCacheType) (
	data []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf, err error)

Get implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) GetEncodedSize

func (b *BlockServerMemory) GetEncodedSize(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context) (
	size uint32, status keybase1.BlockStatus, err error)

GetEncodedSize implements the BlockServer interface for BlockServerDisk.

func (*BlockServerMemory) GetLiveBlockReferences

func (b *BlockServerMemory) GetLiveBlockReferences(
	ctx context.Context, tlfID tlf.ID, contexts kbfsblock.ContextMap) (
	liveCounts map[kbfsblock.ID]int, err error)

GetLiveBlockReferences implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) GetTeamQuotaInfo

func (b *BlockServerMemory) GetTeamQuotaInfo(
	ctx context.Context, _ keybase1.TeamID) (
	info *kbfsblock.QuotaInfo, err error)

GetTeamQuotaInfo implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) GetUserQuotaInfo

func (b *BlockServerMemory) GetUserQuotaInfo(ctx context.Context) (info *kbfsblock.QuotaInfo, err error)

GetUserQuotaInfo implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) IsUnflushed

func (b *BlockServerMemory) IsUnflushed(ctx context.Context, tlfID tlf.ID,
	_ kbfsblock.ID) (bool, error)

IsUnflushed implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) Put

func (b *BlockServerMemory) Put(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	_ DiskBlockCacheType) (err error)

Put implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) PutAgain

func (b *BlockServerMemory) PutAgain(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	_ DiskBlockCacheType) (err error)

PutAgain implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) RefreshAuthToken

func (b *BlockServerMemory) RefreshAuthToken(_ context.Context)

RefreshAuthToken implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) RemoveBlockReferences

func (b *BlockServerMemory) RemoveBlockReferences(ctx context.Context,
	tlfID tlf.ID, contexts kbfsblock.ContextMap) (
	liveCounts map[kbfsblock.ID]int, err error)

RemoveBlockReferences implements the BlockServer interface for BlockServerMemory.

func (*BlockServerMemory) Shutdown

func (b *BlockServerMemory) Shutdown(ctx context.Context)

Shutdown implements the BlockServer interface for BlockServerMemory.

type BlockServerRemote

type BlockServerRemote struct {
	// contains filtered or unexported fields
}

BlockServerRemote implements the BlockServer interface and represents a remote KBFS block server.

func NewBlockServerRemote

func NewBlockServerRemote(config blockServerRemoteConfig,
	blkSrvRemote rpc.Remote, rpcLogFactory rpc.LogFactory) *BlockServerRemote

NewBlockServerRemote constructs a new BlockServerRemote for the given address.

func (*BlockServerRemote) AddBlockReference

func (b *BlockServerRemote) AddBlockReference(ctx context.Context, tlfID tlf.ID,
	id kbfsblock.ID, context kbfsblock.Context) (err error)

AddBlockReference implements the BlockServer interface for BlockServerRemote

func (*BlockServerRemote) ArchiveBlockReferences

func (b *BlockServerRemote) ArchiveBlockReferences(ctx context.Context,
	tlfID tlf.ID, contexts kbfsblock.ContextMap) (err error)

ArchiveBlockReferences implements the BlockServer interface for BlockServerRemote

func (*BlockServerRemote) Get

func (b *BlockServerRemote) Get(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context, cacheType DiskBlockCacheType) (
	buf []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf, err error)

Get implements the BlockServer interface for BlockServerRemote.

func (*BlockServerRemote) GetEncodedSize

func (b *BlockServerRemote) GetEncodedSize(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	context kbfsblock.Context) (
	size uint32, status keybase1.BlockStatus, err error)

GetEncodedSize implements the BlockServer interface for BlockServerRemote.

func (*BlockServerRemote) GetLiveBlockReferences

func (b *BlockServerRemote) GetLiveBlockReferences(
	ctx context.Context, tlfID tlf.ID, contexts kbfsblock.ContextMap) (
	liveCounts map[kbfsblock.ID]int, err error)

GetLiveBlockReferences implements the BlockServer interface for BlockServerRemote.

func (*BlockServerRemote) GetTeamQuotaInfo

func (b *BlockServerRemote) GetTeamQuotaInfo(
	ctx context.Context, tid keybase1.TeamID) (
	info *kbfsblock.QuotaInfo, err error)

GetTeamQuotaInfo implements the BlockServer interface for BlockServerRemote

func (*BlockServerRemote) GetUserQuotaInfo

func (b *BlockServerRemote) GetUserQuotaInfo(ctx context.Context) (info *kbfsblock.QuotaInfo, err error)

GetUserQuotaInfo implements the BlockServer interface for BlockServerRemote

func (*BlockServerRemote) IsUnflushed

func (b *BlockServerRemote) IsUnflushed(
	_ context.Context, _ tlf.ID, _ kbfsblock.ID) (
	bool, error)

IsUnflushed implements the BlockServer interface for BlockServerRemote.

func (*BlockServerRemote) Put

func (b *BlockServerRemote) Put(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	bContext kbfsblock.Context, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	cacheType DiskBlockCacheType) (err error)

Put implements the BlockServer interface for BlockServerRemote.

func (*BlockServerRemote) PutAgain

func (b *BlockServerRemote) PutAgain(
	ctx context.Context, tlfID tlf.ID, id kbfsblock.ID,
	bContext kbfsblock.Context, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	cacheType DiskBlockCacheType) (err error)

PutAgain implements the BlockServer interface for BlockServerRemote

func (*BlockServerRemote) RefreshAuthToken

func (b *BlockServerRemote) RefreshAuthToken(ctx context.Context)

RefreshAuthToken implements the AuthTokenRefreshHandler interface.

func (*BlockServerRemote) RemoteAddress

func (b *BlockServerRemote) RemoteAddress() string

RemoteAddress returns the remote bserver this client is talking to

func (*BlockServerRemote) RemoveBlockReferences

func (b *BlockServerRemote) RemoveBlockReferences(ctx context.Context,
	tlfID tlf.ID, contexts kbfsblock.ContextMap) (liveCounts map[kbfsblock.ID]int, err error)

RemoveBlockReferences implements the BlockServer interface for BlockServerRemote

func (*BlockServerRemote) Shutdown

func (b *BlockServerRemote) Shutdown(ctx context.Context)

Shutdown implements the BlockServer interface for BlockServerRemote.

type BlockSplitter

type BlockSplitter interface {
	// CopyUntilSplit copies data into the block until we reach the
	// point where we should split, but only if writing to the end of
	// the last block.  If this is writing into the middle of a file,
	// just copy everything that will fit into the block, and assume
	// that block boundaries will be fixed later. Return how much was
	// copied.
	CopyUntilSplit(
		block *FileBlock, lastBlock bool, data []byte, off int64) int64

	// CheckSplit, given a block, figures out whether it ends at the
	// right place.  If so, return 0.  If not, return either the
	// offset in the block where it should be split, or -1 if more
	// bytes from the next block should be appended.
	CheckSplit(block *FileBlock) int64

	// MaxPtrsPerBlock describes the number of indirect pointers we
	// can fit into one indirect block.
	MaxPtrsPerBlock() int

	// ShouldEmbedBlockChanges decides whether we should keep the
	// block changes embedded in the MD or not.
	ShouldEmbedBlockChanges(bc *BlockChanges) bool

	// SplitDirIfNeeded splits a direct DirBlock into multiple blocks
	// if needed.  It may modify `block`.  If a split isn't needed, it
	// returns a one-element slice containing `block`.  If a split is
	// needed, it returns a non-nil offset for the new block.
	SplitDirIfNeeded(block *DirBlock) ([]*DirBlock, *StringOffset)
}

BlockSplitter decides when a file block needs to be split

type BlockSplitterSimple

type BlockSplitterSimple struct {
	// contains filtered or unexported fields
}

BlockSplitterSimple implements the BlockSplitter interface by using a simple max-size algorithm to determine when to split blocks.

func NewBlockSplitterSimple

func NewBlockSplitterSimple(desiredBlockSize int64,
	blockChangeEmbedMaxSize uint64, codec kbfscodec.Codec) (
	*BlockSplitterSimple, error)

NewBlockSplitterSimple creates a new BlockSplittleSimple and adjusts the max size to try to match the desired size for file blocks, given the overhead of encoding a file block and the round-up padding we do.

func (*BlockSplitterSimple) CheckSplit

func (b *BlockSplitterSimple) CheckSplit(block *FileBlock) int64

CheckSplit implements the BlockSplitter interface for BlockSplitterSimple.

func (*BlockSplitterSimple) CopyUntilSplit

func (b *BlockSplitterSimple) CopyUntilSplit(
	block *FileBlock, lastBlock bool, data []byte, off int64) int64

CopyUntilSplit implements the BlockSplitter interface for BlockSplitterSimple.

func (*BlockSplitterSimple) MaxPtrsPerBlock

func (b *BlockSplitterSimple) MaxPtrsPerBlock() int

MaxPtrsPerBlock implements the BlockSplitter interface for BlockSplitterSimple.

func (*BlockSplitterSimple) SetMaxDirEntriesByBlockSize

func (b *BlockSplitterSimple) SetMaxDirEntriesByBlockSize(
	codec kbfscodec.Codec) error

SetMaxDirEntriesByBlockSize sets the maximum number of directory entries per directory block, based on the maximum block size. If the `KEYBASE_BSPLIT_MAX_DIR_ENTRIES` is set, this function does nothing.

func (*BlockSplitterSimple) ShouldEmbedBlockChanges

func (b *BlockSplitterSimple) ShouldEmbedBlockChanges(
	bc *BlockChanges) bool

ShouldEmbedBlockChanges implements the BlockSplitter interface for BlockSplitterSimple.

func (*BlockSplitterSimple) SplitDirIfNeeded

func (b *BlockSplitterSimple) SplitDirIfNeeded(block *DirBlock) (
	[]*DirBlock, *StringOffset)

SplitDirIfNeeded implements the BlockSplitter interface for BlockSplitterSimple.

type BlockWithPtrs

type BlockWithPtrs interface {
	Block

	// FirstOffset returns the offset of the indirect pointer that
	// points to the first (left-most) block in a block tree.
	FirstOffset() Offset
	// NumIndirectPtrs returns the number of indirect pointers in this
	// block.  The behavior is undefined when called on a non-indirect
	// block.
	NumIndirectPtrs() int
	// IndirectPtr returns the block info and offset for the indirect
	// pointer at index `i`. The behavior is undefined when called on
	// a non-indirect block.
	IndirectPtr(i int) (BlockInfo, Offset)
	// AppendNewIndirectPtr appends a new indirect pointer at the
	// given offset.
	AppendNewIndirectPtr(ptr BlockPointer, off Offset)
	// ClearIndirectPtrSize clears the encoded size of the indirect
	// pointer stored at index `i`.
	ClearIndirectPtrSize(i int)
	// SetIndirectPtrType set the type of the indirect pointer stored
	// at index `i`.
	SetIndirectPtrType(i int, dt BlockDirectType)
	// SetIndirectPtrOff set the offset of the indirect pointer stored
	// at index `i`.
	SetIndirectPtrOff(i int, off Offset)
	// SetIndirectPtrInfo sets the block info of the indirect pointer
	// stored at index `i`.
	SetIndirectPtrInfo(i int, info BlockInfo)
	// SwapIndirectPtrs swaps the indirect ptr at `i` in this block
	// with the one at `otherI` in `other`.
	SwapIndirectPtrs(i int, other BlockWithPtrs, otherI int)
}

BlockWithPtrs defines methods needed for interacting with indirect pointers.

func NewDirBlockWithPtrs

func NewDirBlockWithPtrs(isInd bool) BlockWithPtrs

NewDirBlockWithPtrs creates a new, empty DirBlock.

func NewFileBlockWithPtrs

func NewFileBlockWithPtrs(isInd bool) BlockWithPtrs

NewFileBlockWithPtrs creates a new, empty FileBlock.

type BranchName

type BranchName string

BranchName is the name given to a KBFS branch, for a particular top-level folder. Currently, the notion of a "branch" is client-side only, and can be used to specify which root to use for a top-level folder. (For example, viewing a historical archive could use a different branch name.)

const (
	// MasterBranch represents the mainline branch for a top-level
	// folder.  Set to the empty string so that the default will be
	// the master branch.
	MasterBranch BranchName = ""
)

func MakeRevBranchName

func MakeRevBranchName(rev kbfsmd.Revision) BranchName

MakeRevBranchName returns a branch name specifying an archive branch pinned to the given revision number.

func (BranchName) IsArchived

func (bn BranchName) IsArchived() bool

IsArchived returns true if the branch specifies an archived revision.

func (BranchName) RevisionIfSpecified

func (bn BranchName) RevisionIfSpecified() (kbfsmd.Revision, bool)

RevisionIfSpecified returns a valid revision number and true if `bn` is a revision branch.

type CRAbandonStagedBranchError

type CRAbandonStagedBranchError struct {
	Err error
	Bid kbfsmd.BranchID
}

CRAbandonStagedBranchError indicates that conflict resolution had to abandon a staged branch due to an unresolvable error.

func (CRAbandonStagedBranchError) Error

type CRWrapError

type CRWrapError struct {
	// contains filtered or unexported fields
}

CRWrapError wraps an error that happens during conflict resolution.

func (CRWrapError) Error

func (e CRWrapError) Error() string

Error implements the error interface for CRWrapError.

type Chat

type Chat interface {
	// GetConversationID returns the chat conversation ID associated
	// with the given TLF name, type, chat type and channel name.
	GetConversationID(
		ctx context.Context, tlfName tlf.CanonicalName, tlfType tlf.Type,
		channelName string, chatType chat1.TopicType) (
		chat1.ConversationID, error)

	// SendTextMessage (asynchronously) sends a text chat message to
	// the given conversation and channel.
	SendTextMessage(
		ctx context.Context, tlfName tlf.CanonicalName, tlfType tlf.Type,
		convID chat1.ConversationID, body string) error

	// GetGroupedInbox returns the TLFs with the most-recent chat
	// messages of the given type, up to `maxChats` of them.
	GetGroupedInbox(
		ctx context.Context, chatType chat1.TopicType, maxChats int) (
		[]*TlfHandle, error)

	// GetChannels returns a list of all the channels for a given
	// chat. The entries in `convIDs` and `channelNames` have a 1-to-1
	// correspondence.
	GetChannels(
		ctx context.Context, tlfName tlf.CanonicalName, tlfType tlf.Type,
		chatType chat1.TopicType) (
		convIDs []chat1.ConversationID, channelNames []string, err error)

	// ReadChannel returns a set of text messages from a channel, and
	// a `nextPage` pointer to the following set of messages.  If the
	// given `startPage` is non-nil, it's used to specify the starting
	// point for the set of messages returned.
	ReadChannel(
		ctx context.Context, convID chat1.ConversationID, startPage []byte) (
		messages []string, nextPage []byte, err error)

	// RegisterForMessages registers a callback that will be called
	// for each new messages that reaches convID.
	RegisterForMessages(convID chat1.ConversationID, cb ChatChannelNewMessageCB)

	// ClearCache is called to force this instance to forget
	// everything it might have cached, e.g. when a user logs out.
	ClearCache()
}

Chat specifies a minimal interface for Keybase chatting.

type ChatChannelNewMessageCB

type ChatChannelNewMessageCB func(convID chat1.ConversationID, body string)

ChatChannelNewMessageCB is a callback function that can be called when there's a new message on a given conversation.

type ChatRPC

type ChatRPC struct {
	// contains filtered or unexported fields
}

ChatRPC is an RPC based implementation for chat.

func NewChatRPC

func NewChatRPC(config Config, kbCtx Context) *ChatRPC

NewChatRPC constructs a new RPC based chat implementation.

func (*ChatRPC) ChatAttachmentUploadProgress

func (c *ChatRPC) ChatAttachmentUploadProgress(
	_ context.Context, _ chat1.ChatAttachmentUploadProgressArg) error

ChatAttachmentUploadProgress implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatAttachmentUploadStart

func (c *ChatRPC) ChatAttachmentUploadStart(
	_ context.Context, _ chat1.ChatAttachmentUploadStartArg) error

ChatAttachmentUploadStart implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatIdentifyUpdate

ChatIdentifyUpdate implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatInboxStale

func (c *ChatRPC) ChatInboxStale(_ context.Context, _ keybase1.UID) error

ChatInboxStale implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatInboxSyncStarted

func (c *ChatRPC) ChatInboxSyncStarted(
	_ context.Context, _ keybase1.UID) error

ChatInboxSyncStarted implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatInboxSynced

func (c *ChatRPC) ChatInboxSynced(
	_ context.Context, _ chat1.ChatInboxSyncedArg) error

ChatInboxSynced implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatJoinedConversation

func (c *ChatRPC) ChatJoinedConversation(
	_ context.Context, _ chat1.ChatJoinedConversationArg) error

ChatJoinedConversation implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatKBFSToImpteamUpgrade

func (c *ChatRPC) ChatKBFSToImpteamUpgrade(
	_ context.Context, _ chat1.ChatKBFSToImpteamUpgradeArg) error

ChatKBFSToImpteamUpgrade implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatLeftConversation

func (c *ChatRPC) ChatLeftConversation(
	_ context.Context, _ chat1.ChatLeftConversationArg) error

ChatLeftConversation implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatPaymentInfo

func (c *ChatRPC) ChatPaymentInfo(
	_ context.Context, _ chat1.ChatPaymentInfoArg) error

ChatPaymentInfo implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatPromptUnfurl

func (c *ChatRPC) ChatPromptUnfurl(_ context.Context, _ chat1.ChatPromptUnfurlArg) error

ChatPromptUnfurl implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatRequestInfo

func (c *ChatRPC) ChatRequestInfo(
	_ context.Context, _ chat1.ChatRequestInfoArg) error

ChatRequestInfo implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatResetConversation

func (c *ChatRPC) ChatResetConversation(
	_ context.Context, _ chat1.ChatResetConversationArg) error

ChatResetConversation implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatSetConvRetention

func (c *ChatRPC) ChatSetConvRetention(
	_ context.Context, _ chat1.ChatSetConvRetentionArg) error

ChatSetConvRetention implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatSetConvSettings

func (c *ChatRPC) ChatSetConvSettings(
	_ context.Context, _ chat1.ChatSetConvSettingsArg) error

ChatSetConvSettings implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatSetTeamRetention

func (c *ChatRPC) ChatSetTeamRetention(
	_ context.Context, _ chat1.ChatSetTeamRetentionArg) error

ChatSetTeamRetention implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatSubteamRename

func (c *ChatRPC) ChatSubteamRename(
	_ context.Context, _ chat1.ChatSubteamRenameArg) error

ChatSubteamRename implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatTLFFinalize

func (c *ChatRPC) ChatTLFFinalize(
	_ context.Context, _ chat1.ChatTLFFinalizeArg) error

ChatTLFFinalize implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatTLFResolve

func (c *ChatRPC) ChatTLFResolve(
	_ context.Context, _ chat1.ChatTLFResolveArg) error

ChatTLFResolve implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatThreadsStale

func (c *ChatRPC) ChatThreadsStale(
	_ context.Context, _ chat1.ChatThreadsStaleArg) error

ChatThreadsStale implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ChatTypingUpdate

func (c *ChatRPC) ChatTypingUpdate(
	_ context.Context, _ []chat1.ConvTypingUpdate) error

ChatTypingUpdate implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) ClearCache

func (c *ChatRPC) ClearCache()

ClearCache implements the Chat interface.

func (*ChatRPC) GetChannels

func (c *ChatRPC) GetChannels(
	ctx context.Context, tlfName tlf.CanonicalName, tlfType tlf.Type,
	chatType chat1.TopicType) (
	convIDs []chat1.ConversationID, channelNames []string, err error)

GetChannels implements the Chat interface.

func (*ChatRPC) GetConversationID

func (c *ChatRPC) GetConversationID(
	ctx context.Context, tlfName tlf.CanonicalName, tlfType tlf.Type,
	channelName string, chatType chat1.TopicType) (
	chat1.ConversationID, error)

GetConversationID implements the Chat interface.

func (*ChatRPC) GetGroupedInbox

func (c *ChatRPC) GetGroupedInbox(
	ctx context.Context, chatType chat1.TopicType, maxChats int) (
	results []*TlfHandle, err error)

GetGroupedInbox implements the Chat interface.

func (*ChatRPC) HandlerName

func (c *ChatRPC) HandlerName() string

HandlerName implements the ConnectionHandler interface.

func (*ChatRPC) NewChatActivity

func (c *ChatRPC) NewChatActivity(
	ctx context.Context, arg chat1.NewChatActivityArg) error

NewChatActivity implements the chat1.NotifyChatInterface for ChatRPC.

func (*ChatRPC) OnConnect

func (c *ChatRPC) OnConnect(ctx context.Context, conn *rpc.Connection,
	_ rpc.GenericClient, server *rpc.Server) error

OnConnect implements the ConnectionHandler interface.

func (*ChatRPC) OnConnectError

func (c *ChatRPC) OnConnectError(err error, wait time.Duration)

OnConnectError implements the ConnectionHandler interface.

func (*ChatRPC) OnDisconnected

func (c *ChatRPC) OnDisconnected(_ context.Context,
	status rpc.DisconnectStatus)

OnDisconnected implements the ConnectionHandler interface.

func (*ChatRPC) OnDoCommandError

func (c *ChatRPC) OnDoCommandError(err error, wait time.Duration)

OnDoCommandError implements the ConnectionHandler interface.

func (*ChatRPC) ReadChannel

func (c *ChatRPC) ReadChannel(
	ctx context.Context, convID chat1.ConversationID, startPage []byte) (
	messages []string, nextPage []byte, err error)

ReadChannel implements the Chat interface.

func (*ChatRPC) RegisterForMessages

func (c *ChatRPC) RegisterForMessages(
	convID chat1.ConversationID, cb ChatChannelNewMessageCB)

RegisterForMessages implements the Chat interface.

func (*ChatRPC) SendTextMessage

func (c *ChatRPC) SendTextMessage(
	ctx context.Context, tlfName tlf.CanonicalName, tlfType tlf.Type,
	convID chat1.ConversationID, body string) error

SendTextMessage implements the Chat interface.

func (*ChatRPC) ShouldRetry

func (c *ChatRPC) ShouldRetry(_ string, _ error) bool

ShouldRetry implements the ConnectionHandler interface.

func (*ChatRPC) ShouldRetryOnConnect

func (c *ChatRPC) ShouldRetryOnConnect(err error) bool

ShouldRetryOnConnect implements the ConnectionHandler interface.

type Clock

type Clock interface {
	// Now returns the current time.
	Now() time.Time
}

Clock is an interface for getting the current time

type CoalescingContext

type CoalescingContext struct {
	context.Context
	// contains filtered or unexported fields
}

CoalescingContext allows many contexts to be treated as one. It waits on all its contexts' Context.Done() channels, and when all of them have returned, this CoalescingContext is canceled. At any point, a context can be added to the list, and will subsequently also be part of the wait condition. TODO: add timeout channel in case there is a goroutine leak.

func NewCoalescingContext

func NewCoalescingContext(parent context.Context) (*CoalescingContext, context.CancelFunc)

NewCoalescingContext creates a new CoalescingContext. The context _must_ be canceled to avoid a goroutine leak.

func (*CoalescingContext) AddContext

func (ctx *CoalescingContext) AddContext(other context.Context) error

AddContext adds a context to the set of contexts that we're waiting on.

func (*CoalescingContext) Deadline

func (ctx *CoalescingContext) Deadline() (time.Time, bool)

Deadline overrides the default parent's Deadline().

func (*CoalescingContext) Done

func (ctx *CoalescingContext) Done() <-chan struct{}

Done returns a channel that is closed when the CoalescingContext is canceled.

func (*CoalescingContext) Err

func (ctx *CoalescingContext) Err() error

Err returns context.Canceled if the CoalescingContext has been canceled, and nil otherwise.

type CommonBlock

type CommonBlock struct {
	// IsInd indicates where this block is so big it requires indirect pointers
	IsInd bool `codec:"s"`

	codec.UnknownFieldSetHandler
	// contains filtered or unexported fields
}

CommonBlock holds block data that is common for both subdirectories and files.

func (*CommonBlock) BytesCanBeDirtied

func (cb *CommonBlock) BytesCanBeDirtied() int64

BytesCanBeDirtied implements the Block interface for CommonBlock.

func (*CommonBlock) DataVersion

func (cb *CommonBlock) DataVersion() DataVer

DataVersion returns data version for this block.

func (*CommonBlock) DeepCopy

func (cb *CommonBlock) DeepCopy() CommonBlock

DeepCopy copies a CommonBlock without the lock.

func (*CommonBlock) GetEncodedSize

func (cb *CommonBlock) GetEncodedSize() uint32

GetEncodedSize implements the Block interface for CommonBlock

func (*CommonBlock) IsIndirect

func (cb *CommonBlock) IsIndirect() bool

IsIndirect implements the Block interface for CommonBlock.

func (*CommonBlock) IsTail

func (cb *CommonBlock) IsTail() bool

IsTail implements the Block interface for CommonBlock.

func (*CommonBlock) NewEmptier

func (cb *CommonBlock) NewEmptier() func() Block

NewEmptier implements the Block interface for CommonBlock.

func (*CommonBlock) NewEmpty

func (cb *CommonBlock) NewEmpty() Block

NewEmpty implements the Block interface for CommonBlock.

func (*CommonBlock) OffsetExceedsData

func (cb *CommonBlock) OffsetExceedsData(_, _ Offset) bool

OffsetExceedsData implements the Block interface for CommonBlock.

func (*CommonBlock) Set

func (cb *CommonBlock) Set(other Block)

Set implements the Block interface for CommonBlock.

func (*CommonBlock) SetEncodedSize

func (cb *CommonBlock) SetEncodedSize(size uint32)

SetEncodedSize implements the Block interface for CommonBlock

func (*CommonBlock) ToCommonBlock

func (cb *CommonBlock) ToCommonBlock() *CommonBlock

ToCommonBlock implements the Block interface for CommonBlock.

type Config

type Config interface {
	Tracer
	KBFSOps() KBFSOps
	SetKBFSOps(KBFSOps)
	KBPKI() KBPKI
	SetKBPKI(KBPKI)
	KeyManager() KeyManager
	SetKeyManager(KeyManager)
	Reporter() Reporter
	SetReporter(Reporter)
	MDCache() MDCache
	SetMDCache(MDCache)
	KeyCache() KeyCache
	SetKeyBundleCache(kbfsmd.KeyBundleCache)
	KeyBundleCache() kbfsmd.KeyBundleCache
	SetKeyCache(KeyCache)
	SetBlockCache(BlockCache)
	DirtyBlockCache() DirtyBlockCache
	SetDirtyBlockCache(DirtyBlockCache)
	SetCrypto(Crypto)
	SetChat(Chat)
	SetCodec(kbfscodec.Codec)
	MDOps() MDOps
	SetMDOps(MDOps)
	KeyOps() KeyOps
	SetKeyOps(KeyOps)
	BlockOps() BlockOps
	SetBlockOps(BlockOps)
	MDServer() MDServer
	SetMDServer(MDServer)
	SetBlockServer(BlockServer)
	KeyServer() KeyServer
	SetKeyServer(KeyServer)
	KeybaseService() KeybaseService
	SetKeybaseService(KeybaseService)
	BlockSplitter() BlockSplitter
	SetBlockSplitter(BlockSplitter)
	Notifier() Notifier
	SetNotifier(Notifier)
	SetClock(Clock)
	ConflictRenamer() ConflictRenamer
	SetConflictRenamer(ConflictRenamer)
	UserHistory() *kbfsedits.UserHistory
	SetUserHistory(*kbfsedits.UserHistory)
	MetadataVersion() kbfsmd.MetadataVer
	SetMetadataVersion(kbfsmd.MetadataVer)
	SetBlockCryptVersion(kbfscrypto.EncryptionVer)
	DefaultBlockType() keybase1.BlockType
	SetDefaultBlockType(blockType keybase1.BlockType)
	RekeyQueue() RekeyQueue
	SetRekeyQueue(RekeyQueue)
	// ReqsBufSize indicates the number of read or write operations
	// that can be buffered per folder
	ReqsBufSize() int
	// MaxNameBytes indicates the maximum supported size of a
	// directory entry name in bytes.
	MaxNameBytes() uint32
	// DoBackgroundFlushes says whether we should periodically try to
	// flush dirty files, even without a sync from the user.  Should
	// be true except for during some testing.
	DoBackgroundFlushes() bool
	SetDoBackgroundFlushes(bool)
	// RekeyWithPromptWaitTime indicates how long to wait, after
	// setting the rekey bit, before prompting for a paper key.
	RekeyWithPromptWaitTime() time.Duration
	SetRekeyWithPromptWaitTime(time.Duration)
	// PrefetchStatus returns the prefetch status of a block.
	PrefetchStatus(context.Context, tlf.ID, BlockPointer) PrefetchStatus

	// GracePeriod specifies a grace period for which a delayed cancellation
	// waits before actual cancels the context. This is useful for giving
	// critical portion of a slow remote operation some extra time to finish as
	// an effort to avoid conflicting. Example include an O_EXCL Create call
	// interrupted by ALRM signal actually makes it to the server, while
	// application assumes not since EINTR is returned. A delayed cancellation
	// allows us to distinguish between successful cancel (where remote operation
	// didn't make to server) or failed cancel (where remote operation made to
	// the server). However, the optimal value of this depends on the network
	// conditions. A long grace period for really good network condition would
	// just unnecessarily slow down Ctrl-C.
	//
	// TODO: make this adaptive and self-change over time based on network
	// conditions.
	DelayedCancellationGracePeriod() time.Duration
	SetDelayedCancellationGracePeriod(time.Duration)

	// ResetCaches clears and re-initializes all data and key caches.
	ResetCaches()

	// StorageRoot returns the path to the storage root for this config.
	StorageRoot() string

	// MetricsRegistry may be nil, which should be interpreted as
	// not using metrics at all. (i.e., as if UseNilMetrics were
	// set). This differs from how go-metrics treats nil Registry
	// objects, which is to use the default registry.
	MetricsRegistry() metrics.Registry
	SetMetricsRegistry(metrics.Registry)

	// SetTraceOptions set the options for tracing (via x/net/trace).
	SetTraceOptions(enabled bool)

	// TLFValidDuration is the time TLFs are valid before identification needs to be redone.
	TLFValidDuration() time.Duration
	// SetTLFValidDuration sets TLFValidDuration.
	SetTLFValidDuration(time.Duration)

	// BGFlushDirOpBatchSize returns the directory op batch size for
	// background flushes.
	BGFlushDirOpBatchSize() int
	// SetBGFlushDirOpBatchSize sets the directory op batch size for
	// background flushes.
	SetBGFlushDirOpBatchSize(s int)

	// BGFlushPeriod returns how long to wait for a batch to fill up
	// before syncing a set of changes to the servers.
	BGFlushPeriod() time.Duration
	// SetBGFlushPeriod sets how long to wait for a batch to fill up
	// before syncing a set of changes to the servers.
	SetBGFlushPeriod(p time.Duration)

	// Shutdown is called to free config resources.
	Shutdown(context.Context) error
	// CheckStateOnShutdown tells the caller whether or not it is safe
	// to check the state of the system on shutdown.
	CheckStateOnShutdown() bool

	// GetRekeyFSMLimiter returns the global rekey FSM limiter.
	GetRekeyFSMLimiter() *OngoingWorkLimiter

	// RootNodeWrappers returns the set of root node wrapper functions
	// that will be applied to each newly-created root node.
	RootNodeWrappers() []func(Node) Node
	// AddRootNodeWrapper adds a new wrapper function that will be
	// applied whenever a root Node is created.  This will only apply
	// to TLFs that are first accessed after `AddRootNodeWrapper` is
	// called.
	AddRootNodeWrapper(func(Node) Node)
	// contains filtered or unexported methods
}

Config collects all the singleton instance instantiations needed to run KBFS in one place. The methods below are self-explanatory and do not require comments.

func Init

func Init(
	ctx context.Context, kbCtx Context, params InitParams,
	keybaseServiceCn KeybaseServiceCn, onInterruptFn func(),
	log logger.Logger) (cfg Config, err error)

Init initializes a config and returns it.

onInterruptFn is called whenever an interrupt signal is received (e.g., if the user hits Ctrl-C).

Init should be called at the beginning of main. Shutdown (see below) should then be called at the end of main (usually via defer).

The keybaseServiceCn argument is to specify a custom service and crypto (for non-RPC environments) like mobile. If this is nil, we'll use the default RPC implementation.

func InitWithLogPrefix

func InitWithLogPrefix(
	ctx context.Context, kbCtx Context, params InitParams,
	keybaseServiceCn KeybaseServiceCn, onInterruptFn func(),
	log logger.Logger, logPrefix string) (cfg Config, err error)

InitWithLogPrefix initializes a config and returns it, given a prefix.

onInterruptFn is called whenever an interrupt signal is received (e.g., if the user hits Ctrl-C).

Init should be called at the beginning of main. Shutdown (see below) should then be called at the end of main (usually via defer).

The keybaseServiceCn argument is to specify a custom service and crypto (for non-RPC environments) like mobile. If this is nil, we'll use the default RPC implementation.

type ConfigLocal

type ConfigLocal struct {
	// contains filtered or unexported fields
}

ConfigLocal implements the Config interface using purely local server objects (no KBFS operations used RPCs).

func ConfigAsUser

func ConfigAsUser(config *ConfigLocal,
	loggedInUser kbname.NormalizedUsername) *ConfigLocal

ConfigAsUser clones a test configuration in default init mode, setting another user as the logged in user. Journaling will not be enabled in the returned Config, regardless of the journal status in `config`.

func ConfigAsUserWithMode

func ConfigAsUserWithMode(config *ConfigLocal,
	loggedInUser kbname.NormalizedUsername, mode InitModeType) *ConfigLocal

ConfigAsUserWithMode clones a test configuration in the given mode, setting another user as the logged in user. Journaling will not be enabled in the returned Config, regardless of the journal status in `config`.

func MakeTestConfigOrBust

func MakeTestConfigOrBust(t logger.TestLogBackend,
	users ...kbname.NormalizedUsername) *ConfigLocal

MakeTestConfigOrBust creates and returns a config suitable for unit-testing with the given list of users.

func MakeTestConfigOrBustLoggedIn

func MakeTestConfigOrBustLoggedIn(t logger.TestLogBackend, loggedInIndex int,
	users ...kbname.NormalizedUsername) *ConfigLocal

MakeTestConfigOrBustLoggedIn creates and returns a config suitable for unit-testing with the given list of users. loggedInIndex specifies the index (in the list) of the user being logged in.

func MakeTestConfigOrBustLoggedInWithMode

func MakeTestConfigOrBustLoggedInWithMode(
	t logger.TestLogBackend, loggedInIndex int,
	mode InitModeType, users ...kbname.NormalizedUsername) *ConfigLocal

MakeTestConfigOrBustLoggedInWithMode creates and returns a config suitable for unit-testing with the given mode and list of users. loggedInIndex specifies the index (in the list) of the user being logged in.

func NewConfigLocal

func NewConfigLocal(mode InitMode,
	loggerFn func(module string) logger.Logger,
	storageRoot string, diskCacheMode DiskCacheMode,
	kbCtx Context) *ConfigLocal

NewConfigLocal constructs a new ConfigLocal with some default components that don't depend on a logger. The caller will have to fill in the rest.

TODO: Now that NewConfigLocal takes loggerFn, add more default components.

func (*ConfigLocal) AddRootNodeWrapper

func (c *ConfigLocal) AddRootNodeWrapper(f func(Node) Node)

AddRootNodeWrapper implements the Config interface for ConfigLocal.

func (*ConfigLocal) BGFlushDirOpBatchSize

func (c *ConfigLocal) BGFlushDirOpBatchSize() int

BGFlushDirOpBatchSize implements the Config interface for ConfigLocal.

func (*ConfigLocal) BGFlushPeriod

func (c *ConfigLocal) BGFlushPeriod() time.Duration

BGFlushPeriod implements the Config interface for ConfigLocal.

func (*ConfigLocal) BlockCache

func (c *ConfigLocal) BlockCache() BlockCache

BlockCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) BlockCryptVersion

func (c *ConfigLocal) BlockCryptVersion() kbfscrypto.EncryptionVer

BlockCryptVersion implements the Config interface for ConfigLocal.

func (*ConfigLocal) BlockOps

func (c *ConfigLocal) BlockOps() BlockOps

BlockOps implements the Config interface for ConfigLocal.

func (*ConfigLocal) BlockServer

func (c *ConfigLocal) BlockServer() BlockServer

BlockServer implements the Config interface for ConfigLocal.

func (*ConfigLocal) BlockSplitter

func (c *ConfigLocal) BlockSplitter() BlockSplitter

BlockSplitter implements the Config interface for ConfigLocal.

func (*ConfigLocal) Chat

func (c *ConfigLocal) Chat() Chat

Chat implements the Config interface for ConfigLocal.

func (*ConfigLocal) CheckStateOnShutdown

func (c *ConfigLocal) CheckStateOnShutdown() bool

CheckStateOnShutdown implements the Config interface for ConfigLocal.

func (*ConfigLocal) Clock

func (c *ConfigLocal) Clock() Clock

Clock implements the Config interface for ConfigLocal.

func (*ConfigLocal) Codec

func (c *ConfigLocal) Codec() kbfscodec.Codec

Codec implements the Config interface for ConfigLocal.

func (*ConfigLocal) ConflictRenamer

func (c *ConfigLocal) ConflictRenamer() ConflictRenamer

ConflictRenamer implements the Config interface for ConfigLocal.

func (*ConfigLocal) Crypto

func (c *ConfigLocal) Crypto() Crypto

Crypto implements the Config interface for ConfigLocal.

func (*ConfigLocal) CurrentSessionGetter

func (c *ConfigLocal) CurrentSessionGetter() CurrentSessionGetter

CurrentSessionGetter implements the Config interface for ConfigLocal.

func (*ConfigLocal) DataVersion

func (c *ConfigLocal) DataVersion() DataVer

DataVersion implements the Config interface for ConfigLocal.

func (*ConfigLocal) DefaultBlockType

func (c *ConfigLocal) DefaultBlockType() keybase1.BlockType

DefaultBlockType implements the Config interface for ConfigLocal.

func (*ConfigLocal) DelayedCancellationGracePeriod

func (c *ConfigLocal) DelayedCancellationGracePeriod() time.Duration

DelayedCancellationGracePeriod implements the Config interface for ConfigLocal.

func (*ConfigLocal) DirtyBlockCache

func (c *ConfigLocal) DirtyBlockCache() DirtyBlockCache

DirtyBlockCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) DiskBlockCache

func (c *ConfigLocal) DiskBlockCache() DiskBlockCache

DiskBlockCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) DiskLimiter

func (c *ConfigLocal) DiskLimiter() DiskLimiter

DiskLimiter implements the Config interface for ConfigLocal.

func (*ConfigLocal) DiskMDCache

func (c *ConfigLocal) DiskMDCache() DiskMDCache

DiskMDCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) DiskQuotaCache

func (c *ConfigLocal) DiskQuotaCache() DiskQuotaCache

DiskQuotaCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) DoBackgroundFlushes

func (c *ConfigLocal) DoBackgroundFlushes() bool

DoBackgroundFlushes implements the Config interface for ConfigLocal.

func (*ConfigLocal) EnableDiskLimiter

func (c *ConfigLocal) EnableDiskLimiter(configRoot string) error

EnableDiskLimiter fills in c.ciskLimiter for use in journaling and disk caching. It returns the EventuallyConsistentQuotaUsage object used by the disk limiter.

func (*ConfigLocal) EnableJournaling

func (c *ConfigLocal) EnableJournaling(
	ctx context.Context, journalRoot string,
	bws TLFJournalBackgroundWorkStatus) error

EnableJournaling creates a JournalServer and attaches it to this config. journalRoot must be non-empty. Errors returned are non-fatal.

func (*ConfigLocal) GetAllSyncedTlfs

func (c *ConfigLocal) GetAllSyncedTlfs() []tlf.ID

GetAllSyncedTlfs implements the Config interface for ConfigLocal.

func (*ConfigLocal) GetRekeyFSMLimiter

func (c *ConfigLocal) GetRekeyFSMLimiter() *OngoingWorkLimiter

GetRekeyFSMLimiter implements the Config interface for ConfigLocal.

func (*ConfigLocal) GetTlfSyncState

func (c *ConfigLocal) GetTlfSyncState(tlfID tlf.ID) FolderSyncConfig

GetTlfSyncState implements the isSyncedTlfGetter interface for ConfigLocal.

func (*ConfigLocal) IsSyncedTlf

func (c *ConfigLocal) IsSyncedTlf(tlfID tlf.ID) bool

IsSyncedTlf implements the isSyncedTlfGetter interface for ConfigLocal.

func (*ConfigLocal) IsTestMode

func (c *ConfigLocal) IsTestMode() bool

IsTestMode implements the Config interface for ConfigLocal.

func (*ConfigLocal) KBFSOps

func (c *ConfigLocal) KBFSOps() KBFSOps

KBFSOps implements the Config interface for ConfigLocal.

func (*ConfigLocal) KBPKI

func (c *ConfigLocal) KBPKI() KBPKI

KBPKI implements the Config interface for ConfigLocal.

func (*ConfigLocal) KeyBundleCache

func (c *ConfigLocal) KeyBundleCache() kbfsmd.KeyBundleCache

KeyBundleCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) KeyCache

func (c *ConfigLocal) KeyCache() KeyCache

KeyCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) KeyManager

func (c *ConfigLocal) KeyManager() KeyManager

KeyManager implements the Config interface for ConfigLocal.

func (*ConfigLocal) KeyOps

func (c *ConfigLocal) KeyOps() KeyOps

KeyOps implements the Config interface for ConfigLocal.

func (*ConfigLocal) KeyServer

func (c *ConfigLocal) KeyServer() KeyServer

KeyServer implements the Config interface for ConfigLocal.

func (*ConfigLocal) KeybaseService

func (c *ConfigLocal) KeybaseService() KeybaseService

KeybaseService implements the Config interface for ConfigLocal.

func (*ConfigLocal) MDCache

func (c *ConfigLocal) MDCache() MDCache

MDCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) MDOps

func (c *ConfigLocal) MDOps() MDOps

MDOps implements the Config interface for ConfigLocal.

func (*ConfigLocal) MDServer

func (c *ConfigLocal) MDServer() MDServer

MDServer implements the Config interface for ConfigLocal.

func (*ConfigLocal) MakeBlockMetadataStoreIfNotExists

func (c *ConfigLocal) MakeBlockMetadataStoreIfNotExists() (err error)

MakeBlockMetadataStoreIfNotExists implements the Config interface for ConfigLocal. If error happens, a Noop one is populated.

func (*ConfigLocal) MakeDiskBlockCacheIfNotExists

func (c *ConfigLocal) MakeDiskBlockCacheIfNotExists() error

MakeDiskBlockCacheIfNotExists implements the Config interface for ConfigLocal.

func (*ConfigLocal) MakeDiskMDCacheIfNotExists

func (c *ConfigLocal) MakeDiskMDCacheIfNotExists() error

MakeDiskMDCacheIfNotExists implements the Config interface for ConfigLocal.

func (*ConfigLocal) MakeDiskQuotaCacheIfNotExists

func (c *ConfigLocal) MakeDiskQuotaCacheIfNotExists() error

MakeDiskQuotaCacheIfNotExists implements the Config interface for ConfigLocal.

func (*ConfigLocal) MakeLogger

func (c *ConfigLocal) MakeLogger(module string) logger.Logger

MakeLogger implements the Config interface for ConfigLocal.

func (*ConfigLocal) MaxNameBytes

func (c *ConfigLocal) MaxNameBytes() uint32

MaxNameBytes implements the Config interface for ConfigLocal.

func (*ConfigLocal) MaybeFinishTrace

func (c *ConfigLocal) MaybeFinishTrace(ctx context.Context, err error)

MaybeFinishTrace implements the Config interface for ConfigLocal.

func (*ConfigLocal) MaybeStartTrace

func (c *ConfigLocal) MaybeStartTrace(
	ctx context.Context, family, title string) context.Context

MaybeStartTrace implements the Config interface for ConfigLocal.

func (*ConfigLocal) MetadataVersion

func (c *ConfigLocal) MetadataVersion() kbfsmd.MetadataVer

MetadataVersion implements the Config interface for ConfigLocal.

func (*ConfigLocal) MetricsRegistry

func (c *ConfigLocal) MetricsRegistry() metrics.Registry

MetricsRegistry implements the Config interface for ConfigLocal.

func (*ConfigLocal) Mode

func (c *ConfigLocal) Mode() InitMode

Mode implements the Config interface for ConfigLocal.

func (*ConfigLocal) Notifier

func (c *ConfigLocal) Notifier() Notifier

Notifier implements the Config interface for ConfigLocal.

func (*ConfigLocal) PrefetchStatus

func (c *ConfigLocal) PrefetchStatus(ctx context.Context, tlfID tlf.ID,
	ptr BlockPointer) PrefetchStatus

PrefetchStatus implements the Config interface for ConfigLocal.

func (*ConfigLocal) RekeyQueue

func (c *ConfigLocal) RekeyQueue() RekeyQueue

RekeyQueue implements the Config interface for ConfigLocal.

func (*ConfigLocal) RekeyWithPromptWaitTime

func (c *ConfigLocal) RekeyWithPromptWaitTime() time.Duration

RekeyWithPromptWaitTime implements the Config interface for ConfigLocal.

func (*ConfigLocal) Reporter

func (c *ConfigLocal) Reporter() Reporter

Reporter implements the Config interface for ConfigLocal.

func (*ConfigLocal) ReqsBufSize

func (c *ConfigLocal) ReqsBufSize() int

ReqsBufSize implements the Config interface for ConfigLocal.

func (*ConfigLocal) ResetCaches

func (c *ConfigLocal) ResetCaches()

ResetCaches implements the Config interface for ConfigLocal.

func (*ConfigLocal) RootNodeWrappers

func (c *ConfigLocal) RootNodeWrappers() []func(Node) Node

RootNodeWrappers implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetBGFlushDirOpBatchSize

func (c *ConfigLocal) SetBGFlushDirOpBatchSize(s int)

SetBGFlushDirOpBatchSize implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetBGFlushPeriod

func (c *ConfigLocal) SetBGFlushPeriod(p time.Duration)

SetBGFlushPeriod implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetBlockCache

func (c *ConfigLocal) SetBlockCache(b BlockCache)

SetBlockCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetBlockCryptVersion

func (c *ConfigLocal) SetBlockCryptVersion(ver kbfscrypto.EncryptionVer)

SetBlockCryptVersion implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetBlockOps

func (c *ConfigLocal) SetBlockOps(b BlockOps)

SetBlockOps implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetBlockServer

func (c *ConfigLocal) SetBlockServer(b BlockServer)

SetBlockServer implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetBlockSplitter

func (c *ConfigLocal) SetBlockSplitter(b BlockSplitter)

SetBlockSplitter implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetChat

func (c *ConfigLocal) SetChat(ch Chat)

SetChat implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetClock

func (c *ConfigLocal) SetClock(cl Clock)

SetClock implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetCodec

func (c *ConfigLocal) SetCodec(co kbfscodec.Codec)

SetCodec implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetConflictRenamer

func (c *ConfigLocal) SetConflictRenamer(cr ConflictRenamer)

SetConflictRenamer implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetCrypto

func (c *ConfigLocal) SetCrypto(cr Crypto)

SetCrypto implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetDefaultBlockType

func (c *ConfigLocal) SetDefaultBlockType(blockType keybase1.BlockType)

SetDefaultBlockType implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetDelayedCancellationGracePeriod

func (c *ConfigLocal) SetDelayedCancellationGracePeriod(d time.Duration)

SetDelayedCancellationGracePeriod implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetDirtyBlockCache

func (c *ConfigLocal) SetDirtyBlockCache(d DirtyBlockCache)

SetDirtyBlockCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetDiskBlockCacheFraction

func (c *ConfigLocal) SetDiskBlockCacheFraction(fraction float64)

SetDiskBlockCacheFraction implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetDoBackgroundFlushes

func (c *ConfigLocal) SetDoBackgroundFlushes(doBGFlush bool)

SetDoBackgroundFlushes implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetKBFSOps

func (c *ConfigLocal) SetKBFSOps(k KBFSOps)

SetKBFSOps implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetKBFSService

func (c *ConfigLocal) SetKBFSService(k *KBFSService)

SetKBFSService sets the KBFSService for this ConfigLocal.

func (*ConfigLocal) SetKBPKI

func (c *ConfigLocal) SetKBPKI(k KBPKI)

SetKBPKI implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetKeyBundleCache

func (c *ConfigLocal) SetKeyBundleCache(k kbfsmd.KeyBundleCache)

SetKeyBundleCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetKeyCache

func (c *ConfigLocal) SetKeyCache(k KeyCache)

SetKeyCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetKeyManager

func (c *ConfigLocal) SetKeyManager(k KeyManager)

SetKeyManager implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetKeyOps

func (c *ConfigLocal) SetKeyOps(k KeyOps)

SetKeyOps implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetKeyServer

func (c *ConfigLocal) SetKeyServer(k KeyServer)

SetKeyServer implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetKeybaseService

func (c *ConfigLocal) SetKeybaseService(k KeybaseService)

SetKeybaseService implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetMDCache

func (c *ConfigLocal) SetMDCache(m MDCache)

SetMDCache implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetMDOps

func (c *ConfigLocal) SetMDOps(m MDOps)

SetMDOps implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetMDServer

func (c *ConfigLocal) SetMDServer(m MDServer)

SetMDServer implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetMetadataVersion

func (c *ConfigLocal) SetMetadataVersion(mdVer kbfsmd.MetadataVer)

SetMetadataVersion implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetMetricsRegistry

func (c *ConfigLocal) SetMetricsRegistry(r metrics.Registry)

SetMetricsRegistry implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetNotifier

func (c *ConfigLocal) SetNotifier(n Notifier)

SetNotifier implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetRekeyQueue

func (c *ConfigLocal) SetRekeyQueue(r RekeyQueue)

SetRekeyQueue implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetRekeyWithPromptWaitTime

func (c *ConfigLocal) SetRekeyWithPromptWaitTime(d time.Duration)

SetRekeyWithPromptWaitTime implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetReporter

func (c *ConfigLocal) SetReporter(r Reporter)

SetReporter implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetSyncBlockCacheFraction

func (c *ConfigLocal) SetSyncBlockCacheFraction(fraction float64)

SetSyncBlockCacheFraction implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetTLFValidDuration

func (c *ConfigLocal) SetTLFValidDuration(r time.Duration)

SetTLFValidDuration implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetTlfSyncState

func (c *ConfigLocal) SetTlfSyncState(tlfID tlf.ID, config FolderSyncConfig) (
	<-chan error, error)

SetTlfSyncState implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetTraceOptions

func (c *ConfigLocal) SetTraceOptions(enabled bool)

SetTraceOptions implements the Config interface for ConfigLocal.

func (*ConfigLocal) SetUserHistory

func (c *ConfigLocal) SetUserHistory(uh *kbfsedits.UserHistory)

SetUserHistory implements the Config interface for ConfigLocal.

func (*ConfigLocal) Shutdown

func (c *ConfigLocal) Shutdown(ctx context.Context) error

Shutdown implements the Config interface for ConfigLocal.

func (*ConfigLocal) Signer

func (c *ConfigLocal) Signer() kbfscrypto.Signer

Signer implements the Config interface for ConfigLocal.

func (*ConfigLocal) StorageRoot

func (c *ConfigLocal) StorageRoot() string

StorageRoot implements the Config interface for ConfigLocal.

func (*ConfigLocal) TLFValidDuration

func (c *ConfigLocal) TLFValidDuration() time.Duration

TLFValidDuration implements the Config interface for ConfigLocal.

func (*ConfigLocal) UserHistory

func (c *ConfigLocal) UserHistory() *kbfsedits.UserHistory

UserHistory implements the Config interface for ConfigLocal.

func (*ConfigLocal) XattrStore

func (c *ConfigLocal) XattrStore() XattrStore

XattrStore implements the Config interface for ConfigLocal.

type ConflictRenamer

type ConflictRenamer interface {
	// ConflictRename returns the appropriately modified filename.
	ConflictRename(ctx context.Context, op op, original string) (
		string, error)
}

ConflictRenamer deals with names for conflicting directory entries.

type ConflictResolver

type ConflictResolver struct {
	// contains filtered or unexported fields
}

ConflictResolver is responsible for resolving conflicts in the background.

func NewConflictResolver

func NewConflictResolver(
	config Config, fbo *folderBranchOps) *ConflictResolver

NewConflictResolver constructs a new ConflictResolver (and launches any necessary background goroutines).

func (*ConflictResolver) BeginNewBranch

func (cr *ConflictResolver) BeginNewBranch()

BeginNewBranch resets any internal state to be ready to accept resolutions from a new branch.

func (*ConflictResolver) ForceCancel

func (cr *ConflictResolver) ForceCancel()

ForceCancel cancels any currently-running CR, regardless of what its inputs were.

func (*ConflictResolver) Pause

func (cr *ConflictResolver) Pause()

Pause cancels any ongoing resolutions and prevents any new ones from starting.

func (*ConflictResolver) Resolve

func (cr *ConflictResolver) Resolve(ctx context.Context,
	unmerged kbfsmd.Revision, merged kbfsmd.Revision)

Resolve takes the latest known unmerged and merged revision numbers, and kicks off the resolution process.

func (*ConflictResolver) Restart

func (cr *ConflictResolver) Restart(baseCtx context.Context)

Restart re-enables conflict resolution, with a base context for CR operations. baseCtx must have a cancellation delayer.

func (*ConflictResolver) Shutdown

func (cr *ConflictResolver) Shutdown()

Shutdown cancels any ongoing resolutions and stops any background goroutines.

func (*ConflictResolver) Wait

func (cr *ConflictResolver) Wait(ctx context.Context) error

Wait blocks until the current set of submitted resolutions are complete (though not necessarily successful), or until the given context is canceled.

type Context

type Context env.Context

Context defines the environment for this package

type ContextAlreadyHasCancellationDelayerError

type ContextAlreadyHasCancellationDelayerError struct{}

ContextAlreadyHasCancellationDelayerError is returned when NewContextWithCancellationDelayer is called for the second time on the same ctx, which is not supported yet.

func (ContextAlreadyHasCancellationDelayerError) Error

type CountMeter

type CountMeter struct {
	// contains filtered or unexported fields
}

CountMeter counts ticks with a sliding window into the past.

func NewCountMeter

func NewCountMeter() *CountMeter

NewCountMeter returns a new CountMeter.

func (*CountMeter) Count

func (m *CountMeter) Count() int64

Count returns the overall count.

func (*CountMeter) Mark

func (m *CountMeter) Mark(i int64)

Mark ticks the counters.

func (*CountMeter) Rate1

func (m *CountMeter) Rate1() float64

Rate1 returns the number of ticks in the last 1 minute.

func (*CountMeter) Rate15

func (m *CountMeter) Rate15() float64

Rate15 returns the number of ticks in the last 15 minutes.

func (*CountMeter) Rate5

func (m *CountMeter) Rate5() float64

Rate5 returns the number of ticks in the last 5 minutes.

func (*CountMeter) RateMean

func (m *CountMeter) RateMean() float64

RateMean returns the overall count of ticks.

func (*CountMeter) Shutdown

func (m *CountMeter) Shutdown() <-chan struct{}

Shutdown shuts down this CountMeter.

func (*CountMeter) Snapshot

func (m *CountMeter) Snapshot() metrics.Meter

Snapshot returns the snapshot in time of this CountMeter.

type Crypto

type Crypto interface {

	// Duplicate kbfscrypto.Signer here to work around gomock's
	// limitations.
	Sign(context.Context, []byte) (kbfscrypto.SignatureInfo, error)
	SignForKBFS(context.Context, []byte) (kbfscrypto.SignatureInfo, error)
	SignToString(context.Context, []byte) (string, error)

	// DecryptTLFCryptKeyClientHalf decrypts a
	// kbfscrypto.TLFCryptKeyClientHalf using the current device's
	// private key and the TLF's ephemeral public key.
	DecryptTLFCryptKeyClientHalf(ctx context.Context,
		publicKey kbfscrypto.TLFEphemeralPublicKey,
		encryptedClientHalf kbfscrypto.EncryptedTLFCryptKeyClientHalf) (
		kbfscrypto.TLFCryptKeyClientHalf, error)

	// DecryptTLFCryptKeyClientHalfAny decrypts one of the
	// kbfscrypto.TLFCryptKeyClientHalf using the available
	// private keys and the ephemeral public key.  If promptPaper
	// is true, the service will prompt the user for any unlocked
	// paper keys.
	DecryptTLFCryptKeyClientHalfAny(ctx context.Context,
		keys []EncryptedTLFCryptKeyClientAndEphemeral,
		promptPaper bool) (
		kbfscrypto.TLFCryptKeyClientHalf, int, error)

	// DecryptTeamMerkleLeaf decrypts a team-encrypted Merkle leaf
	// using some team key generation greater than `minKeyGen`, and
	// the provided ephemeral public key.
	DecryptTeamMerkleLeaf(ctx context.Context, teamID keybase1.TeamID,
		publicKey kbfscrypto.TLFEphemeralPublicKey,
		encryptedMerkleLeaf kbfscrypto.EncryptedMerkleLeaf,
		minKeyGen keybase1.PerTeamKeyGeneration) ([]byte, error)

	// Shutdown frees any resources associated with this instance.
	Shutdown()
	// contains filtered or unexported methods
}

Crypto signs, verifies, encrypts, and decrypts stuff.

type CryptoClient

type CryptoClient struct {
	CryptoCommon
	// contains filtered or unexported fields
}

CryptoClient is a keybase1.CryptoInterface based implementation for Crypto.

func (*CryptoClient) DecryptTLFCryptKeyClientHalf

func (c *CryptoClient) DecryptTLFCryptKeyClientHalf(ctx context.Context,
	publicKey kbfscrypto.TLFEphemeralPublicKey,
	encryptedClientHalf kbfscrypto.EncryptedTLFCryptKeyClientHalf) (
	clientHalf kbfscrypto.TLFCryptKeyClientHalf, err error)

DecryptTLFCryptKeyClientHalf implements the Crypto interface for CryptoClient.

func (*CryptoClient) DecryptTLFCryptKeyClientHalfAny

func (c *CryptoClient) DecryptTLFCryptKeyClientHalfAny(ctx context.Context,
	keys []EncryptedTLFCryptKeyClientAndEphemeral, promptPaper bool) (
	clientHalf kbfscrypto.TLFCryptKeyClientHalf, index int, err error)

DecryptTLFCryptKeyClientHalfAny implements the Crypto interface for CryptoClient.

func (*CryptoClient) DecryptTeamMerkleLeaf

func (c *CryptoClient) DecryptTeamMerkleLeaf(
	ctx context.Context, teamID keybase1.TeamID,
	publicKey kbfscrypto.TLFEphemeralPublicKey,
	encryptedMerkleLeaf kbfscrypto.EncryptedMerkleLeaf,
	minKeyGen keybase1.PerTeamKeyGeneration) (decryptedData []byte, err error)

DecryptTeamMerkleLeaf implements the Crypto interface for CryptoClient.

func (*CryptoClient) Shutdown

func (c *CryptoClient) Shutdown()

Shutdown implements the Crypto interface for CryptoClient.

func (*CryptoClient) Sign

func (c *CryptoClient) Sign(ctx context.Context, msg []byte) (
	sigInfo kbfscrypto.SignatureInfo, err error)

Sign implements the Crypto interface for CryptoClient.

func (*CryptoClient) SignForKBFS

func (c *CryptoClient) SignForKBFS(ctx context.Context, msg []byte) (
	sigInfo kbfscrypto.SignatureInfo, err error)

SignForKBFS implements the Crypto interface for CryptoClient.

func (*CryptoClient) SignToString

func (c *CryptoClient) SignToString(ctx context.Context, msg []byte) (
	signature string, err error)

SignToString implements the Crypto interface for CryptoClient.

type CryptoClientRPC

type CryptoClientRPC struct {
	CryptoClient
	// contains filtered or unexported fields
}

CryptoClientRPC is an RPC based implementation for Crypto.

func NewCryptoClientRPC

func NewCryptoClientRPC(config Config, kbCtx Context) *CryptoClientRPC

NewCryptoClientRPC constructs a new RPC based Crypto implementation.

func (CryptoClientRPC) HandlerName

func (CryptoClientRPC) HandlerName() string

HandlerName implements the ConnectionHandler interface.

func (*CryptoClientRPC) OnConnect

func (c *CryptoClientRPC) OnConnect(ctx context.Context, conn *rpc.Connection,
	_ rpc.GenericClient, server *rpc.Server) error

OnConnect implements the ConnectionHandler interface.

func (*CryptoClientRPC) OnConnectError

func (c *CryptoClientRPC) OnConnectError(err error, wait time.Duration)

OnConnectError implements the ConnectionHandler interface.

func (*CryptoClientRPC) OnDisconnected

func (c *CryptoClientRPC) OnDisconnected(_ context.Context,
	status rpc.DisconnectStatus)

OnDisconnected implements the ConnectionHandler interface.

func (*CryptoClientRPC) OnDoCommandError

func (c *CryptoClientRPC) OnDoCommandError(err error, wait time.Duration)

OnDoCommandError implements the ConnectionHandler interface.

func (*CryptoClientRPC) ShouldRetry

func (c *CryptoClientRPC) ShouldRetry(rpcName string, err error) bool

ShouldRetry implements the ConnectionHandler interface.

func (*CryptoClientRPC) ShouldRetryOnConnect

func (c *CryptoClientRPC) ShouldRetryOnConnect(err error) bool

ShouldRetryOnConnect implements the ConnectionHandler interface.

type CryptoCommon

type CryptoCommon struct {
	// contains filtered or unexported fields
}

CryptoCommon contains many of the function implementations need for the Crypto interface, which can be reused by other implementations.

func MakeCryptoCommon

func MakeCryptoCommon(
	codec kbfscodec.Codec,
	blockCryptVersioner blockCryptVersioner) CryptoCommon

MakeCryptoCommon returns a default CryptoCommon object.

func (CryptoCommon) DecryptBlock

func (c CryptoCommon) DecryptBlock(
	encryptedBlock kbfscrypto.EncryptedBlock,
	tlfCryptKey kbfscrypto.TLFCryptKey,
	blockServerHalf kbfscrypto.BlockCryptKeyServerHalf, block Block) error

DecryptBlock implements the Crypto interface for CryptoCommon.

func (CryptoCommon) DecryptPrivateMetadata

func (c CryptoCommon) DecryptPrivateMetadata(
	encryptedPmd kbfscrypto.EncryptedPrivateMetadata, key kbfscrypto.TLFCryptKey) (
	PrivateMetadata, error)

DecryptPrivateMetadata implements the Crypto interface for CryptoCommon.

func (CryptoCommon) EncryptBlock

func (c CryptoCommon) EncryptBlock(
	block Block, tlfCryptKey kbfscrypto.TLFCryptKey,
	blockServerHalf kbfscrypto.BlockCryptKeyServerHalf) (
	plainSize int, encryptedBlock kbfscrypto.EncryptedBlock, err error)

EncryptBlock implements the Crypto interface for CryptoCommon.

func (CryptoCommon) EncryptPrivateMetadata

func (c CryptoCommon) EncryptPrivateMetadata(
	pmd PrivateMetadata, key kbfscrypto.TLFCryptKey) (
	encryptedPmd kbfscrypto.EncryptedPrivateMetadata, err error)

EncryptPrivateMetadata implements the Crypto interface for CryptoCommon.

func (CryptoCommon) MakeBlockRefNonce

func (c CryptoCommon) MakeBlockRefNonce() (nonce kbfsblock.RefNonce, err error)

MakeBlockRefNonce implements the Crypto interface for CryptoCommon.

func (CryptoCommon) MakeRandomBlockCryptKeyServerHalf

func (c CryptoCommon) MakeRandomBlockCryptKeyServerHalf() (
	kbfscrypto.BlockCryptKeyServerHalf, error)

MakeRandomBlockCryptKeyServerHalf implements the Crypto interface for CryptoCommon.

func (CryptoCommon) MakeRandomBranchID

func (c CryptoCommon) MakeRandomBranchID() (kbfsmd.BranchID, error)

MakeRandomBranchID implements the Crypto interface for CryptoCommon.

func (CryptoCommon) MakeRandomTLFEphemeralKeys

MakeRandomTLFEphemeralKeys implements the Crypto interface for CryptoCommon.

func (CryptoCommon) MakeRandomTLFKeys

MakeRandomTLFKeys implements the Crypto interface for CryptoCommon.

func (CryptoCommon) MakeRandomTlfID

func (c CryptoCommon) MakeRandomTlfID(t tlf.Type) (tlf.ID, error)

MakeRandomTlfID implements the Crypto interface for CryptoCommon.

func (CryptoCommon) MakeTemporaryBlockID

func (c CryptoCommon) MakeTemporaryBlockID() (kbfsblock.ID, error)

MakeTemporaryBlockID implements the Crypto interface for CryptoCommon.

type CryptoLocal

type CryptoLocal struct {
	CryptoCommon
	kbfscrypto.SigningKeySigner
	// contains filtered or unexported fields
}

CryptoLocal implements the Crypto interface by using a local signing key and a local crypt private key.

func NewCryptoLocal

func NewCryptoLocal(codec kbfscodec.Codec,
	signingKey kbfscrypto.SigningKey,
	cryptPrivateKey kbfscrypto.CryptPrivateKey,
	blockCryptVersioner blockCryptVersioner) *CryptoLocal

NewCryptoLocal constructs a new CryptoLocal instance with the given signing key.

func (*CryptoLocal) DecryptTLFCryptKeyClientHalf

func (c *CryptoLocal) DecryptTLFCryptKeyClientHalf(ctx context.Context,
	publicKey kbfscrypto.TLFEphemeralPublicKey,
	encryptedClientHalf kbfscrypto.EncryptedTLFCryptKeyClientHalf) (
	kbfscrypto.TLFCryptKeyClientHalf, error)

DecryptTLFCryptKeyClientHalf implements the Crypto interface for CryptoLocal.

func (*CryptoLocal) DecryptTLFCryptKeyClientHalfAny

func (c *CryptoLocal) DecryptTLFCryptKeyClientHalfAny(ctx context.Context,
	keys []EncryptedTLFCryptKeyClientAndEphemeral, _ bool) (
	clientHalf kbfscrypto.TLFCryptKeyClientHalf, index int, err error)

DecryptTLFCryptKeyClientHalfAny implements the Crypto interface for CryptoLocal.

func (*CryptoLocal) DecryptTeamMerkleLeaf

func (c *CryptoLocal) DecryptTeamMerkleLeaf(
	ctx context.Context, teamID keybase1.TeamID,
	publicKey kbfscrypto.TLFEphemeralPublicKey,
	encryptedMerkleLeaf kbfscrypto.EncryptedMerkleLeaf,
	minKeyGen keybase1.PerTeamKeyGeneration) (decryptedData []byte, err error)

DecryptTeamMerkleLeaf implements the Crypto interface for CryptoLocal.

func (*CryptoLocal) Shutdown

func (c *CryptoLocal) Shutdown()

Shutdown implements the Crypto interface for CryptoLocal.

type CtxAllowNameKeyType

type CtxAllowNameKeyType int

CtxAllowNameKeyType is the type for a context allowable name override key.

const (
	// CtxAllowNameKey can be used to set a value in a context, and
	// that value will be treated as an allowable directory entry
	// name, even if it also matches a disallowed prefix.  The value
	// must be of type `string`, or it will panic.
	CtxAllowNameKey CtxAllowNameKeyType = iota
)

type CtxBackgroundSyncKeyType

type CtxBackgroundSyncKeyType int

CtxBackgroundSyncKeyType is the type for a context background sync key.

const (
	// CtxBackgroundSyncKey is set in the context for any change
	// notifications that are triggered from a background sync.
	// Observers can ignore these if they want, since they will have
	// already gotten the relevant notifications via LocalChanges.
	CtxBackgroundSyncKey CtxBackgroundSyncKeyType = iota
)

type CtxCRTagKey

type CtxCRTagKey int

CtxCRTagKey is the type used for unique context tags related to conflict resolution

const (
	// CtxCRIDKey is the type of the tag for unique operation IDs
	// related to conflict resolution
	CtxCRIDKey CtxCRTagKey = iota
)

type CtxCancellationDelayerKeyType

type CtxCancellationDelayerKeyType int

CtxCancellationDelayerKeyType is a type for the context key for using cancellationDelayer

const (
	// CtxCancellationDelayerKey is a context key for using cancellationDelayer
	CtxCancellationDelayerKey CtxCancellationDelayerKeyType = iota
)

type CtxFBMTagKey

type CtxFBMTagKey int

CtxFBMTagKey is the type used for unique context tags within folderBlockManager

const (
	// CtxFBMIDKey is the type of the tag for unique operation IDs
	// within folderBlockManager.
	CtxFBMIDKey CtxFBMTagKey = iota
)

type CtxFBOTagKey

type CtxFBOTagKey int

CtxFBOTagKey is the type used for unique context tags within folderBranchOps

const (
	// CtxFBOIDKey is the type of the tag for unique operation IDs
	// within folderBranchOps.
	CtxFBOIDKey CtxFBOTagKey = iota
)

type CtxJournalTagKey

type CtxJournalTagKey int

CtxJournalTagKey is the type used for unique context tags within background journal work.

const (
	// CtxJournalIDKey is the type of the tag for unique operation IDs
	// within background journal work.
	CtxJournalIDKey CtxJournalTagKey = iota
)

type CtxKeybaseServiceTagKey

type CtxKeybaseServiceTagKey int

CtxKeybaseServiceTagKey is the type used for unique context tags used while servicing incoming keybase requests.

const (
	// CtxKeybaseServiceIDKey is the type of the tag for unique
	// operation IDs used while servicing incoming keybase requests.
	CtxKeybaseServiceIDKey CtxKeybaseServiceTagKey = iota
)

type CtxMDSRTagKey

type CtxMDSRTagKey int

CtxMDSRTagKey is the type used for unique context tags within MDServerRemote

const (
	// CtxMDSRIDKey is the type of the tag for unique operation IDs
	// within MDServerRemote.
	CtxMDSRIDKey CtxMDSRTagKey = iota
)

type CtxNotReplayableError

type CtxNotReplayableError struct{}

CtxNotReplayableError is returned when NewContextWithReplayFrom is called on a ctx with no replay func.

func (CtxNotReplayableError) Error

func (e CtxNotReplayableError) Error() string

type CtxReadWriteKeyType

type CtxReadWriteKeyType int

CtxReadWriteKeyType is the type of the key for overriding read-only nodes.

const (
	// CtxReadWriteKey is a context key to indicate that a read-only
	// node should be treated as read-write.
	CtxReadWriteKey CtxReadWriteKeyType = 1
)

type CtxRekeyTagKey

type CtxRekeyTagKey int

CtxRekeyTagKey is the type used for unique context tags within an enqueued Rekey.

const (
	// CtxRekeyIDKey is the type of the tag for unique operation IDs
	// within an enqueued Rekey.
	CtxRekeyIDKey CtxRekeyTagKey = iota
)

type CtxReplayFunc

type CtxReplayFunc func(ctx context.Context) context.Context

CtxReplayFunc is a function for replaying a series of changes done on a context.

type CtxReplayKeyType

type CtxReplayKeyType int

CtxReplayKeyType is a type for the context key for CtxReplayFunc

const (
	// CtxReplayKey is a context key for CtxReplayFunc
	CtxReplayKey CtxReplayKeyType = iota
)

type CurrentSessionGetter

type CurrentSessionGetter interface {
	// GetCurrentSession gets the current session info.
	GetCurrentSession(ctx context.Context) (SessionInfo, error)
}

CurrentSessionGetter is an interface for objects that can return session info.

type DataVer

type DataVer int

DataVer is the type of a version for marshalled KBFS data structures.

1) DataVer is a per-block attribute, not per-file. This means that, in theory, an indirect block with DataVer n may point to blocks with DataVers less than, equal to, or greater than n. However, for now, it's guaranteed that an indirect block will never point to blocks with greater versions than itself. (See #3 for details.)

2) DataVer is an external attribute of a block, meaning that it's not stored as part of the block, but computed by the creator (or anyone with the latest kbfs client), and stored only in pointers to the block.

2.5) A file (or, in the future a dir) can in theory have any arbitrary tree structure of blocks. However, we only write files such that all paths to leaves have the same depth.

Currently, in addition to 2.5, we have the following constraints on block tree structures: a) Direct blocks are always v1. b) Indirect blocks of depth 2 (meaning one indirect block pointing to all direct blocks) can be v1 (if it has no holes) or v2 (if it has holes). However, all its indirect pointers will have DataVer 1, by a). c) Indirect blocks of depth 3 must be v3 and must have at least one indirect pointer with an indirect DirectType [although if it holds for one, it should hold for all], although its indirect pointers may have any combination of DataVer 1 or 2, by b). d) Indirect blocks of dept k > 3 must be v3 and must have at least one indirect pointer with an indirect DirectType [although if it holds for one, it should hold for all], and all of its indirect pointers must have DataVer 3, by c).

const (
	// FirstValidDataVer is the first value that is considered a
	// valid data version. Note that the nil value is not
	// considered valid.
	FirstValidDataVer DataVer = 1
	// ChildHolesDataVer is the data version for any indirect block
	// containing a set of pointers with holes.
	ChildHolesDataVer DataVer = 2
	// AtLeastTwoLevelsOfChildrenDataVer is the data version for
	// blocks that have multiple levels of indirection below them
	// (i.e., indirect blocks that point to other indirect blocks).
	AtLeastTwoLevelsOfChildrenDataVer DataVer = 3
	// IndirectDirsDataVer is the data version for a directory block
	// that contains indirect pointers.
	IndirectDirsDataVer DataVer = 4
)

func DefaultNewBlockDataVersion

func DefaultNewBlockDataVersion(holes bool) DataVer

DefaultNewBlockDataVersion returns the default data version for new blocks.

type DirBlock

type DirBlock struct {
	CommonBlock
	// if not indirect, a map of path name to directory entry
	Children map[string]DirEntry `codec:"c,omitempty"`
	// if indirect, contains the indirect pointers to the next level of blocks
	IPtrs []IndirectDirPtr `codec:"i,omitempty"`
}

DirBlock is the contents of a directory

func (*DirBlock) AppendNewIndirectPtr

func (db *DirBlock) AppendNewIndirectPtr(ptr BlockPointer, off Offset)

AppendNewIndirectPtr implements the BlockWithPtrs interface for FileBlock.

func (*DirBlock) BytesCanBeDirtied

func (db *DirBlock) BytesCanBeDirtied() int64

BytesCanBeDirtied implements the Block interface for DirBlock.

func (*DirBlock) ClearIndirectPtrSize

func (db *DirBlock) ClearIndirectPtrSize(i int)

ClearIndirectPtrSize implements the BlockWithPtrs interface for DirBlock.

func (*DirBlock) DataVersion

func (db *DirBlock) DataVersion() DataVer

DataVersion returns data version for this block, which is assumed to have been modified locally.

func (*DirBlock) DeepCopy

func (db *DirBlock) DeepCopy() *DirBlock

DeepCopy makes a complete copy of a DirBlock

func (*DirBlock) FirstOffset

func (db *DirBlock) FirstOffset() Offset

FirstOffset implements the Block interface for DirBlock.

func (*DirBlock) IndirectPtr

func (db *DirBlock) IndirectPtr(i int) (BlockInfo, Offset)

IndirectPtr implements the BlockWithPtrs interface for DirBlock.

func (*DirBlock) IsTail

func (db *DirBlock) IsTail() bool

IsTail implements the Block interface for DirBlock.

func (*DirBlock) NewEmptier

func (db *DirBlock) NewEmptier() func() Block

NewEmptier implements the Block interface for DirBlock.

func (*DirBlock) NewEmpty

func (db *DirBlock) NewEmpty() Block

NewEmpty implements the Block interface for DirBlock

func (*DirBlock) NumIndirectPtrs

func (db *DirBlock) NumIndirectPtrs() int

NumIndirectPtrs implements the BlockWithPtrs interface for DirBlock.

func (*DirBlock) OffsetExceedsData

func (db *DirBlock) OffsetExceedsData(startOff, off Offset) bool

OffsetExceedsData implements the Block interface for DirBlock.

func (*DirBlock) Set

func (db *DirBlock) Set(other Block)

Set implements the Block interface for DirBlock

func (*DirBlock) SetIndirectPtrInfo

func (db *DirBlock) SetIndirectPtrInfo(i int, info BlockInfo)

SetIndirectPtrInfo implements the BlockWithPtrs interface for DirBlock.

func (*DirBlock) SetIndirectPtrOff

func (db *DirBlock) SetIndirectPtrOff(i int, off Offset)

SetIndirectPtrOff implements the BlockWithPtrs interface for DirBlock.

func (*DirBlock) SetIndirectPtrType

func (db *DirBlock) SetIndirectPtrType(i int, dt BlockDirectType)

SetIndirectPtrType implements the BlockWithPtrs interface for DirBlock.

func (*DirBlock) SwapIndirectPtrs

func (db *DirBlock) SwapIndirectPtrs(i int, other BlockWithPtrs, otherI int)

SwapIndirectPtrs implements the BlockWithPtrs interface for DirBlock.

func (*DirBlock) ToCommonBlock

func (db *DirBlock) ToCommonBlock() *CommonBlock

ToCommonBlock implements the Block interface for DirBlock.

type DirEntry

type DirEntry struct {
	BlockInfo
	EntryInfo

	codec.UnknownFieldSetHandler
}

DirEntry is all the data info a directory know about its child.

func (*DirEntry) IsInitialized

func (de *DirEntry) IsInitialized() bool

IsInitialized returns true if this DirEntry has been initialized.

type DirNotEmptyError

type DirNotEmptyError struct {
	Name string
}

DirNotEmptyError indicates that the user tried to unlink a subdirectory that was not empty.

func (DirNotEmptyError) Error

func (e DirNotEmptyError) Error() string

Error implements the error interface for DirNotEmptyError

type DirtyBlockCache

type DirtyBlockCache interface {
	DirtyBlockCacheSimple

	// Delete removes the dirty block associated with the given block
	// pointer and branch from the cache.  No error is returned if no
	// block exists for the given ID.
	Delete(tlfID tlf.ID, ptr BlockPointer, branch BranchName) error
	// IsAnyDirty returns whether there are any dirty blocks in the
	// cache. tlfID may be ignored.
	IsAnyDirty(tlfID tlf.ID) bool
	// RequestPermissionToDirty is called whenever a user wants to
	// write data to a file.  The caller provides an estimated number
	// of bytes that will become dirty -- this is difficult to know
	// exactly without pre-fetching all the blocks involved, but in
	// practice we can just use the number of bytes sent in via the
	// Write. It returns a channel that blocks until the cache is
	// ready to receive more dirty data, at which point the channel is
	// closed.  The user must call
	// `UpdateUnsyncedBytes(-estimatedDirtyBytes)` once it has
	// completed its write and called `UpdateUnsyncedBytes` for all
	// the exact dirty block sizes.
	RequestPermissionToDirty(ctx context.Context, tlfID tlf.ID,
		estimatedDirtyBytes int64) (DirtyPermChan, error)
	// UpdateUnsyncedBytes is called by a user, who has already been
	// granted permission to write, with the delta in block sizes that
	// were dirtied as part of the write.  So for example, if a
	// newly-dirtied block of 20 bytes was extended by 5 bytes, they
	// should send 25.  If on the next write (before any syncs), bytes
	// 10-15 of that same block were overwritten, they should send 0
	// over the channel because there were no new bytes.  If an
	// already-dirtied block is truncated, or if previously requested
	// bytes have now been updated more accurately in previous
	// requests, newUnsyncedBytes may be negative.  wasSyncing should
	// be true if `BlockSyncStarted` has already been called for this
	// block.
	UpdateUnsyncedBytes(tlfID tlf.ID, newUnsyncedBytes int64, wasSyncing bool)
	// UpdateSyncingBytes is called when a particular block has
	// started syncing, or with a negative number when a block is no
	// longer syncing due to an error (and BlockSyncFinished will
	// never be called).
	UpdateSyncingBytes(tlfID tlf.ID, size int64)
	// BlockSyncFinished is called when a particular block has
	// finished syncing, though the overall sync might not yet be
	// complete.  This lets the cache know it might be able to grant
	// more permission to writers.
	BlockSyncFinished(tlfID tlf.ID, size int64)
	// SyncFinished is called when a complete sync has completed and
	// its dirty blocks have been removed from the cache.  This lets
	// the cache know it might be able to grant more permission to
	// writers.
	SyncFinished(tlfID tlf.ID, size int64)
	// ShouldForceSync returns true if the sync buffer is full enough
	// to force all callers to sync their data immediately.
	ShouldForceSync(tlfID tlf.ID) bool

	// Shutdown frees any resources associated with this instance.  It
	// returns an error if there are any unsynced blocks.
	Shutdown() error
	// contains filtered or unexported methods
}

DirtyBlockCache gets and puts plaintext dir blocks and file blocks into a cache, which have been modified by the application and not yet committed on the KBFS servers. They are identified by a (potentially random) ID that may not have any relationship with their context, along with a Branch in case the same TLF is being modified via multiple branches. Dirty blocks are never evicted, they must be deleted explicitly.

type DirtyBlockCacheSimple

type DirtyBlockCacheSimple interface {
	// Get gets the block associated with the given block ID.  Returns
	// the dirty block for the given ID, if one exists.
	Get(
		ctx context.Context, tlfID tlf.ID, ptr BlockPointer,
		branch BranchName) (Block, error)
	// Put stores a dirty block currently identified by the
	// given block pointer and branch name.
	Put(
		ctx context.Context, tlfID tlf.ID, ptr BlockPointer, branch BranchName,
		block Block) error
}

DirtyBlockCacheSimple is a bare-bones interface for a dirty block cache.

type DirtyBlockCacheStandard

type DirtyBlockCacheStandard struct {
	// contains filtered or unexported fields
}

DirtyBlockCacheStandard implements the DirtyBlockCache interface by storing blocks in an in-memory cache. Dirty blocks are identified by their block ID, branch name, and reference nonce, since the same block may be forked and modified on different branches and under different references simultaneously.

DirtyBlockCacheStandard controls how fast uses can write into KBFS, and does so with a TCP-like slow-start algorithm that adjusts itself according to how fast bytes are synced to the server. Conceptually, there are two buffers:

syncBuf: The bytes that are currently syncing, or have finished
syncing, back to the servers.  Each TLF has only one sync at a
time, but multiple TLFs may be syncing at the same time.  We also
track how many bytes within this buffer have finished syncing.

waitBuf: The bytes that have not yet begun syncing to the
servers.  Again, this can be for multiple TLFs, and from multiple
files within a TLF.  In the TCP analogy, think of this as the
congestion window (cwnd).

The goal is to make sure that syncBuf can always be transmitted to the server within the file system operation timeout forced on us by the layer that interacts with the file system (19 seconds on OS X and Windows, defaults to 30 seconds for other layers if not already set). In fact, ideally the data would be transmitted in HALF of the file system operation timeout, in case a user Sync operation gets blocked behind a background Sync operation when there is significant data in waitBuf. At the same time, we want it to be as big as possible, because we get the best performance when writing lots of blocks in parallel to the servers. So, we want an algorithm that allows waitBuf to grow, without causing the next sync (or write, or setattr, etc) operation to timeout. For the purposes of this discussion, let's assume there is only one active TLF at a time.

We allow the user to set a min, start, and max size for waitBuf. Whenever a sync starts, bytes are transferred from waitBuf into syncBuf and a timer is started. When a sync completes successfully, the number of bytes synced is added to the allowed size of waitBuf (i.e., "additive increase" == exponential growth). However, if the number of sync'd bytes is smaller than the min waitBuf size, we don't do additive increase (because we haven't really tested the throughput of the server connection in that case).

If the sync takes more than 33% of half the overall operation timeout, the size of waitBuf is reduced by that same percentage (i.e., "multiplicative decrease"), and any outstanding bytes in the sync will not be used in the "additive increase" phase when the sync completes (they are considered "lost" in the TCP analogy, even though they should eventually succeed). The 33% limit was chosen mostly by trial and error, although if you assume that capacity(waitBuf) will double after each sync, then `2*len(syncBuf) == capacity(waitBuf)`, so at any given point there can be about 3*capacity(syncBuf) bytes buffered; so if syncBuf can't be sync'd in a third of the overall timeout, the next waitBuf should be reduced.

Finally, we need to make sure that the Write calls that are filling up waitBuf while a sync is happening don't timeout. But, we also need to fill waitBuf quickly, so that the next sync is ready to go as soon as the first one completes. Here we implement a compromise. Allow waitBuf to fill up instantly until it holds capacity(syncBuf) bytes. After that, allow it to fill up to 2*capacity(syncBuf), but artificially delay each write by adding backpressure, by some fraction of the system operation timeout that matches the fraction of the progress the buffer has made between capacity(syncBuf) and 2*capacity(syncBuf). As soon as the sync completes, any delayed write is unblocked and gets to start filling up the buffers again.

To avoid keeping the buffer capacity large when network conditions suddenly worsen (say after a laptop sleep when it comes back online on a new, worse network), the capacity is reset back to the minimum if resetBufferCapTime passes without any large syncs. TODO: in the future it might make sense to decrease the buffer capacity, rather than resetting it to the minimum?

func NewDirtyBlockCacheStandard

func NewDirtyBlockCacheStandard(clock Clock,
	log logger.Logger, minSyncBufCap int64,
	maxSyncBufCap int64, startSyncBufCap int64) *DirtyBlockCacheStandard

NewDirtyBlockCacheStandard constructs a new BlockCacheStandard instance. The min and max buffer capacities define the possible range of how many bytes we'll try to sync in any one sync, and the start size defines the initial buffer size.

func (*DirtyBlockCacheStandard) BlockSyncFinished

func (d *DirtyBlockCacheStandard) BlockSyncFinished(_ tlf.ID, size int64)

BlockSyncFinished implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) Delete

func (d *DirtyBlockCacheStandard) Delete(_ tlf.ID, ptr BlockPointer,
	branch BranchName) error

Delete implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) Get

Get implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) IsAnyDirty

func (d *DirtyBlockCacheStandard) IsAnyDirty(_ tlf.ID) bool

IsAnyDirty implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) IsDirty

func (d *DirtyBlockCacheStandard) IsDirty(_ tlf.ID, ptr BlockPointer,
	branch BranchName) (isDirty bool)

IsDirty implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) Put

func (d *DirtyBlockCacheStandard) Put(
	_ context.Context, _ tlf.ID, ptr BlockPointer, branch BranchName,
	block Block) error

Put implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) RequestPermissionToDirty

func (d *DirtyBlockCacheStandard) RequestPermissionToDirty(
	ctx context.Context, _ tlf.ID, estimatedDirtyBytes int64) (
	DirtyPermChan, error)

RequestPermissionToDirty implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) ShouldForceSync

func (d *DirtyBlockCacheStandard) ShouldForceSync(_ tlf.ID) bool

ShouldForceSync implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) Shutdown

func (d *DirtyBlockCacheStandard) Shutdown() error

Shutdown implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) SyncFinished

func (d *DirtyBlockCacheStandard) SyncFinished(_ tlf.ID, size int64)

SyncFinished implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) UpdateSyncingBytes

func (d *DirtyBlockCacheStandard) UpdateSyncingBytes(_ tlf.ID, size int64)

UpdateSyncingBytes implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

func (*DirtyBlockCacheStandard) UpdateUnsyncedBytes

func (d *DirtyBlockCacheStandard) UpdateUnsyncedBytes(_ tlf.ID,
	newUnsyncedBytes int64, wasSyncing bool)

UpdateUnsyncedBytes implements the DirtyBlockCache interface for DirtyBlockCacheStandard.

type DirtyPermChan

type DirtyPermChan <-chan struct{}

DirtyPermChan is a channel that gets closed when the holder has permission to write. We are forced to define it as a type due to a bug in mockgen that can't handle return values with a chan struct{}.

type DisallowedPrefixError

type DisallowedPrefixError struct {
	// contains filtered or unexported fields
}

DisallowedPrefixError indicates that the user attempted to create an entry using a name with a disallowed prefix.

func (DisallowedPrefixError) Error

func (e DisallowedPrefixError) Error() string

Error implements the error interface for NoChainFoundError.

type DiskBlockCache

type DiskBlockCache interface {
	// Get gets a block from the disk cache.  If a specific preferred
	// cache type is given, the block and its metadata are moved to
	// that cache if they're not yet in it.
	Get(ctx context.Context, tlfID tlf.ID, blockID kbfsblock.ID,
		preferredCacheType DiskBlockCacheType) (
		buf []byte, serverHalf kbfscrypto.BlockCryptKeyServerHalf,
		prefetchStatus PrefetchStatus, err error)
	// GetPrefetchStatus returns just the prefetchStatus for the block.
	GetPrefetchStatus(
		ctx context.Context, tlfID tlf.ID, blockID kbfsblock.ID,
		cacheType DiskBlockCacheType) (PrefetchStatus, error)
	// Put puts a block to the disk cache. Returns after it has
	// updated the metadata but before it has finished writing the
	// block.  If cacheType is specified, the block is put into that
	// cache; by default, block are put into the working set cache.
	Put(ctx context.Context, tlfID tlf.ID, blockID kbfsblock.ID, buf []byte,
		serverHalf kbfscrypto.BlockCryptKeyServerHalf,
		cacheType DiskBlockCacheType) error
	// Delete deletes some blocks from the disk cache.
	Delete(
		ctx context.Context, blockIDs []kbfsblock.ID,
		cacheType DiskBlockCacheType) (
		numRemoved int, sizeRemoved int64, err error)
	// UpdateMetadata updates metadata for a given block in the disk cache.
	UpdateMetadata(ctx context.Context, blockID kbfsblock.ID,
		prefetchStatus PrefetchStatus) error
	// ClearAllTlfBlocks deletes all the synced blocks corresponding
	// to the given TLF ID from the cache.  It doesn't affect
	// transient blocks for unsynced TLFs.
	ClearAllTlfBlocks(
		ctx context.Context, tlfID tlf.ID, cacheType DiskBlockCacheType) error
	// GetLastUnrefRev returns the last revision that has been marked
	// unref'd for the given TLF.
	GetLastUnrefRev(
		ctx context.Context, tlfID tlf.ID, cacheType DiskBlockCacheType) (
		kbfsmd.Revision, error)
	// PutLastUnrefRev saves the given revision as the last unref'd
	// revision for the given TLF.
	PutLastUnrefRev(
		ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision,
		cacheType DiskBlockCacheType) error
	// Status returns the current status of the disk cache.
	Status(ctx context.Context) map[string]DiskBlockCacheStatus
	// DoesCacheHaveSpace returns whether the given cache has
	// space.
	DoesCacheHaveSpace(
		ctx context.Context, cacheType DiskBlockCacheType) (bool, error)
	// Mark tags a given block in the disk cache with the given tag.
	Mark(
		ctx context.Context, blockID kbfsblock.ID, tag string,
		cacheType DiskBlockCacheType) error
	// DeleteUnmarked deletes all the given TLF's blocks in the disk
	// cache without the given tag.
	DeleteUnmarked(
		ctx context.Context, tlfID tlf.ID, tag string,
		cacheType DiskBlockCacheType) error
	// AddHomeTLF adds a TLF marked as "home" so that the blocks from it are
	// less likely to be evicted, as well as whether this is their public or
	// private TLF, where the public TLF's files are more likely to be evicted
	// than the private one's.
	AddHomeTLF(ctx context.Context, tlfID tlf.ID) error
	// ClearHomeTLFs should be called on logout so that the old user's TLFs
	// are not still marked as home.
	ClearHomeTLFs(ctx context.Context) error
	// Shutdown cleanly shuts down the disk block cache.
	Shutdown(ctx context.Context)
}

DiskBlockCache caches blocks to the disk.

type DiskBlockCacheError

type DiskBlockCacheError struct {
	Msg string
}

DiskBlockCacheError is a generic disk cache error.

func (DiskBlockCacheError) Error

func (e DiskBlockCacheError) Error() string

Error implements the Error interface for DiskBlockCacheError.

func (DiskBlockCacheError) ToStatus

func (e DiskBlockCacheError) ToStatus() (s keybase1.Status)

ToStatus implements the ExportableError interface for DiskBlockCacheError.

type DiskBlockCacheLocal

type DiskBlockCacheLocal struct {
	// contains filtered or unexported fields
}

DiskBlockCacheLocal is the standard implementation for DiskBlockCache.

func (*DiskBlockCacheLocal) AddHomeTLF

func (cache *DiskBlockCacheLocal) AddHomeTLF(ctx context.Context, tlfID tlf.ID) error

AddHomeTLF implements this DiskBlockCache interace for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) ClearAllTlfBlocks

func (cache *DiskBlockCacheLocal) ClearAllTlfBlocks(
	ctx context.Context, tlfID tlf.ID) (err error)

ClearAllTlfBlocks implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) ClearHomeTLFs

func (cache *DiskBlockCacheLocal) ClearHomeTLFs(ctx context.Context) error

ClearHomeTLFs implements this DiskBlockCache interace for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) Delete

func (cache *DiskBlockCacheLocal) Delete(ctx context.Context,
	blockIDs []kbfsblock.ID) (numRemoved int, sizeRemoved int64, err error)

Delete implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) DeleteUnmarked

func (cache *DiskBlockCacheLocal) DeleteUnmarked(
	ctx context.Context, tlfID tlf.ID, tag string) (err error)

DeleteUnmarked deletes all the blocks without the given tag.

func (*DiskBlockCacheLocal) DoesCacheHaveSpace

func (cache *DiskBlockCacheLocal) DoesCacheHaveSpace(
	ctx context.Context) bool

DoesCacheHaveSpace returns true if we have more than 1% of space left in the cache.

func (*DiskBlockCacheLocal) Get

func (cache *DiskBlockCacheLocal) Get(
	ctx context.Context, tlfID tlf.ID, blockID kbfsblock.ID) (buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	prefetchStatus PrefetchStatus, err error)

Get implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) GetLastUnrefRev

func (cache *DiskBlockCacheLocal) GetLastUnrefRev(
	ctx context.Context, tlfID tlf.ID) (kbfsmd.Revision, error)

GetLastUnrefRev implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) GetMetadata

func (cache *DiskBlockCacheLocal) GetMetadata(ctx context.Context,
	blockID kbfsblock.ID) (DiskBlockCacheMetadata, error)

GetMetadata implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) Mark

func (cache *DiskBlockCacheLocal) Mark(
	ctx context.Context, blockID kbfsblock.ID, tag string) error

Mark updates the metadata of the given block with the tag.

func (*DiskBlockCacheLocal) Put

func (cache *DiskBlockCacheLocal) Put(
	ctx context.Context, tlfID tlf.ID, blockID kbfsblock.ID, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf) (err error)

Put implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) PutLastUnrefRev

func (cache *DiskBlockCacheLocal) PutLastUnrefRev(
	ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision) error

PutLastUnrefRev implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) Shutdown

func (cache *DiskBlockCacheLocal) Shutdown(ctx context.Context)

Shutdown implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) Status

Status implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) UpdateMetadata

func (cache *DiskBlockCacheLocal) UpdateMetadata(ctx context.Context,
	blockID kbfsblock.ID, prefetchStatus PrefetchStatus) (err error)

UpdateMetadata implements the DiskBlockCache interface for DiskBlockCacheLocal.

func (*DiskBlockCacheLocal) WaitUntilStarted

func (cache *DiskBlockCacheLocal) WaitUntilStarted() error

WaitUntilStarted waits until this cache has started.

type DiskBlockCacheMetadata

type DiskBlockCacheMetadata struct {
	// the TLF ID for the block
	TlfID tlf.ID
	// the last time the block was used
	LRUTime legacyEncodedTime
	// the size of the block
	BlockSize uint32
	// whether the block has triggered prefetches
	// This used to be called "HasPrefetched" so to maintain compatibility with
	// existing disk caches, we have to name it that in the codec tag.
	TriggeredPrefetch bool `codec:"HasPrefetched"`
	// whether the block's triggered prefetches are complete
	FinishedPrefetch bool
	// the last tag with which the block was marked
	Tag string
}

DiskBlockCacheMetadata packages the metadata needed to make decisions on cache eviction.

func (DiskBlockCacheMetadata) PrefetchStatus

func (dbcm DiskBlockCacheMetadata) PrefetchStatus() PrefetchStatus

type DiskBlockCacheRemote

type DiskBlockCacheRemote struct {
	// contains filtered or unexported fields
}

DiskBlockCacheRemote implements a client to access a remote DiskBlockCacheService. It implements the DiskBlockCache interface.

func NewDiskBlockCacheRemote

func NewDiskBlockCacheRemote(kbCtx Context, config diskBlockCacheRemoteConfig) (
	*DiskBlockCacheRemote, error)

NewDiskBlockCacheRemote creates a new remote disk cache client.

func (*DiskBlockCacheRemote) AddHomeTLF

func (dbcr *DiskBlockCacheRemote) AddHomeTLF(ctx context.Context,
	tlfID tlf.ID) error

AddHomeTLF implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) ClearAllTlfBlocks

func (dbcr *DiskBlockCacheRemote) ClearAllTlfBlocks(
	_ context.Context, _ tlf.ID, _ DiskBlockCacheType) error

ClearAllTlfBlocks implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) ClearHomeTLFs

func (dbcr *DiskBlockCacheRemote) ClearHomeTLFs(ctx context.Context) error

ClearHomeTLFs implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) Delete

func (dbcr *DiskBlockCacheRemote) Delete(
	ctx context.Context, blockIDs []kbfsblock.ID,
	cacheType DiskBlockCacheType) (
	numRemoved int, sizeRemoved int64, err error)

Delete implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) DeleteUnmarked

func (dbcr *DiskBlockCacheRemote) DeleteUnmarked(
	_ context.Context, _ tlf.ID, _ string, _ DiskBlockCacheType) error

DeleteUnmarked implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) DoesCacheHaveSpace

func (dbcr *DiskBlockCacheRemote) DoesCacheHaveSpace(
	_ context.Context, _ DiskBlockCacheType) (bool, error)

DoesCacheHaveSpace implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) Get

func (dbcr *DiskBlockCacheRemote) Get(ctx context.Context, tlfID tlf.ID,
	blockID kbfsblock.ID, _ DiskBlockCacheType) (buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	prefetchStatus PrefetchStatus, err error)

Get implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) GetLastUnrefRev

func (dbcr *DiskBlockCacheRemote) GetLastUnrefRev(
	_ context.Context, _ tlf.ID, _ DiskBlockCacheType) (
	kbfsmd.Revision, error)

GetLastUnrefRev implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) GetPrefetchStatus

func (dbcr *DiskBlockCacheRemote) GetPrefetchStatus(
	ctx context.Context, tlfID tlf.ID, blockID kbfsblock.ID,
	cacheType DiskBlockCacheType) (
	prefetchStatus PrefetchStatus, err error)

GetPefetchStatus implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) Mark

Mark implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) Put

func (dbcr *DiskBlockCacheRemote) Put(ctx context.Context, tlfID tlf.ID,
	blockID kbfsblock.ID, buf []byte,
	serverHalf kbfscrypto.BlockCryptKeyServerHalf,
	_ DiskBlockCacheType) (err error)

Put implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) PutLastUnrefRev

func (dbcr *DiskBlockCacheRemote) PutLastUnrefRev(
	_ context.Context, _ tlf.ID, _ kbfsmd.Revision,
	_ DiskBlockCacheType) error

PutLastUnrefRev implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) Shutdown

func (dbcr *DiskBlockCacheRemote) Shutdown(ctx context.Context)

Shutdown implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) Status

Status implements the DiskBlockCache interface for DiskBlockCacheRemote.

func (*DiskBlockCacheRemote) UpdateMetadata

func (dbcr *DiskBlockCacheRemote) UpdateMetadata(ctx context.Context,
	blockID kbfsblock.ID, prefetchStatus PrefetchStatus) error

UpdateMetadata implements the DiskBlockCache interface for DiskBlockCacheRemote.

type DiskBlockCacheService

type DiskBlockCacheService struct {
	// contains filtered or unexported fields
}

DiskBlockCacheService delegates requests for blocks to this KBFS instance's disk cache.

func NewDiskBlockCacheService

func NewDiskBlockCacheService(config diskBlockCacheServiceConfig) *DiskBlockCacheService

NewDiskBlockCacheService creates a new DiskBlockCacheService.

func (*DiskBlockCacheService) DeleteBlocks

func (cache *DiskBlockCacheService) DeleteBlocks(ctx context.Context,
	blockIDs [][]byte) (kbgitkbfs.DeleteBlocksRes, error)

DeleteBlocks implements the DiskBlockCacheInterface interface for DiskBlockCacheService.

func (*DiskBlockCacheService) GetBlock

GetBlock implements the DiskBlockCacheInterface interface for DiskBlockCacheService.

func (*DiskBlockCacheService) GetPrefetchStatus

func (cache *DiskBlockCacheService) GetPrefetchStatus(
	ctx context.Context, arg kbgitkbfs.GetPrefetchStatusArg) (
	prefetchStatus kbgitkbfs.PrefetchStatus, err error)

GetPrefetchStatus implements the DiskBlockCacheInterface interface for DiskBlockCacheService.

func (*DiskBlockCacheService) PutBlock

func (cache *DiskBlockCacheService) PutBlock(ctx context.Context,
	arg kbgitkbfs.PutBlockArg) error

PutBlock implements the DiskBlockCacheInterface interface for DiskBlockCacheService.

func (*DiskBlockCacheService) UpdateBlockMetadata

func (cache *DiskBlockCacheService) UpdateBlockMetadata(ctx context.Context,
	arg kbgitkbfs.UpdateBlockMetadataArg) error

UpdateBlockMetadata implements the DiskBlockCacheInterface interface for DiskBlockCacheService.

type DiskBlockCacheStartState

type DiskBlockCacheStartState int

DiskBlockCacheStartState represents whether this disk block cache has started or failed.

const (
	// DiskBlockCacheStartStateStarting represents when the cache is starting.
	DiskBlockCacheStartStateStarting DiskBlockCacheStartState = iota
	// DiskBlockCacheStartStateStarted represents when the cache has started.
	DiskBlockCacheStartStateStarted
	// DiskBlockCacheStartStateFailed represents when the cache has failed to
	// start.
	DiskBlockCacheStartStateFailed
)

func (DiskBlockCacheStartState) String

func (s DiskBlockCacheStartState) String() string

String allows DiskBlockCacheStartState to be output as a string.

type DiskBlockCacheStatus

type DiskBlockCacheStatus struct {
	StartState      DiskBlockCacheStartState
	NumBlocks       uint64
	BlockBytes      uint64
	CurrByteLimit   uint64
	LastUnrefCount  uint64
	Hits            MeterStatus
	Misses          MeterStatus
	Puts            MeterStatus
	MetadataUpdates MeterStatus
	NumEvicted      MeterStatus
	SizeEvicted     MeterStatus
	NumDeleted      MeterStatus
	SizeDeleted     MeterStatus

	LocalDiskBytesAvailable uint64
	LocalDiskBytesTotal     uint64
}

DiskBlockCacheStatus represents the status of the disk cache.

type DiskBlockCacheType

type DiskBlockCacheType int

DiskBlockCacheType specifies a type of an on-disk block cache.

const (
	// DiskBlockAnyCache indicates that any disk block cache is fine.
	DiskBlockAnyCache DiskBlockCacheType = iota
	// DiskBlockWorkingSetCache indicates that the working set cache
	// should be used.
	DiskBlockWorkingSetCache
	// DiskBlockSyncCache indicates that the sync cache should be
	// used.
	DiskBlockSyncCache
)

func (DiskBlockCacheType) String

func (dbct DiskBlockCacheType) String() string

type DiskCacheClosedError

type DiskCacheClosedError struct {
	// contains filtered or unexported fields
}

DiskCacheClosedError indicates that the disk cache has been closed, and thus isn't accepting any more operations.

func (DiskCacheClosedError) Error

func (e DiskCacheClosedError) Error() string

Error implements the error interface for DiskCacheClosedError.

type DiskCacheMode

type DiskCacheMode int

DiskCacheMode represents the mode of initialization for the disk cache.

const (
	// DiskCacheModeOff indicates to leave off the disk cache.
	DiskCacheModeOff DiskCacheMode = iota
	// DiskCacheModeLocal indicates to use a local disk cache.
	DiskCacheModeLocal
	// DiskCacheModeRemote indicates to use a remote disk cache.
	DiskCacheModeRemote
)

func (*DiskCacheMode) Set

func (m *DiskCacheMode) Set(s string) error

Set parses a string representing a disk block cache initialization mode, and outputs the mode value corresponding to that string. Defaults to DiskCacheModeOff.

func (DiskCacheMode) String

func (m DiskCacheMode) String() string

String outputs a human-readable description of this DiskBlockCacheMode.

type DiskCacheStartingError

type DiskCacheStartingError struct {
	// contains filtered or unexported fields
}

DiskCacheStartingError indicates that the disk cache has not yet started, so it isn't yet accepting operations.

func (DiskCacheStartingError) Error

func (e DiskCacheStartingError) Error() string

Error implements the error interface for DiskCacheStartingError.

type DiskLimiter

type DiskLimiter interface {
	// contains filtered or unexported methods
}

DiskLimiter is an interface for limiting disk usage.

type DiskMDCache

type DiskMDCache interface {
	// Get gets the latest cached MD for the given TLF from the disk
	// cache. `ver` is the version of the encoded MD, and `timestamp`
	// is the server timestamp for the MD.
	Get(ctx context.Context, tlfID tlf.ID) (
		buf []byte, ver kbfsmd.MetadataVer, timestamp time.Time, err error)
	// Stage asks the disk cache to store the given MD in memory, but
	// not yet write it to disk.  A later call to `Commit` or
	// `Unstage` for `rev` or higher is required to avoid memory leaks.
	Stage(ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision, buf []byte,
		ver kbfsmd.MetadataVer, timestamp time.Time) error
	// Commit writes a previously-staged MD to disk.  Trying to commit
	// a revision that hasn't been staged is a no-op, to allow callers
	// to call Commit without knowing whether Stage was called first
	// (e.g., if the revision came from the cache in the first place).
	// If older revisions (or other copies of this same revision) are
	// staged, they will become unstaged.
	Commit(ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision) error
	// Unstage unstages and forgets about a previously-staged MD.  (If
	// multiple copies of the same revision have been staged, it only
	// unstages the first of them.)
	Unstage(ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision) error
	// Status returns the current status of the disk cache.
	Status(ctx context.Context) DiskMDCacheStatus
	// Shutdown cleanly shuts down the disk MD cache.
	Shutdown(ctx context.Context)
}

DiskMDCache caches encrypted MD objects to the disk.

type DiskMDCacheError

type DiskMDCacheError struct {
	Msg string
}

DiskMDCacheError is a generic disk cache error.

func (DiskMDCacheError) Error

func (e DiskMDCacheError) Error() string

Error implements the Error interface for DiskMDCacheError.

func (DiskMDCacheError) ToStatus

func (e DiskMDCacheError) ToStatus() (s keybase1.Status)

ToStatus implements the ExportableError interface for DiskMDCacheError.

type DiskMDCacheLocal

type DiskMDCacheLocal struct {
	// contains filtered or unexported fields
}

DiskMDCacheLocal is the standard implementation for DiskMDCache.

func (*DiskMDCacheLocal) Commit

func (cache *DiskMDCacheLocal) Commit(
	ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision) error

Commit implements the DiskMDCache interface for DiskMDCacheLocal.

func (*DiskMDCacheLocal) Get

func (cache *DiskMDCacheLocal) Get(
	ctx context.Context, tlfID tlf.ID) (
	buf []byte, ver kbfsmd.MetadataVer, timestamp time.Time, err error)

Get implements the DiskMDCache interface for DiskMDCacheLocal.

func (*DiskMDCacheLocal) Shutdown

func (cache *DiskMDCacheLocal) Shutdown(ctx context.Context)

Shutdown implements the DiskMDCache interface for DiskMDCacheLocal.

func (*DiskMDCacheLocal) Stage

func (cache *DiskMDCacheLocal) Stage(
	ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision, buf []byte,
	ver kbfsmd.MetadataVer, timestamp time.Time) error

Stage implements the DiskMDCache interface for DiskMDCacheLocal.

func (*DiskMDCacheLocal) Status

Status implements the DiskMDCache interface for DiskMDCacheLocal.

func (*DiskMDCacheLocal) Unstage

func (cache *DiskMDCacheLocal) Unstage(
	ctx context.Context, tlfID tlf.ID, rev kbfsmd.Revision) error

Unstage implements the DiskMDCache interface for DiskMDCacheLocal.

func (*DiskMDCacheLocal) WaitUntilStarted

func (cache *DiskMDCacheLocal) WaitUntilStarted() error

WaitUntilStarted waits until this cache has started.

type DiskMDCacheStartState

type DiskMDCacheStartState int

DiskMDCacheStartState represents whether this disk MD cache has started or failed.

const (
	// DiskMDCacheStartStateStarting represents when the cache is starting.
	DiskMDCacheStartStateStarting DiskMDCacheStartState = iota
	// DiskMDCacheStartStateStarted represents when the cache has started.
	DiskMDCacheStartStateStarted
	// DiskMDCacheStartStateFailed represents when the cache has failed to
	// start.
	DiskMDCacheStartStateFailed
)

func (DiskMDCacheStartState) String

func (s DiskMDCacheStartState) String() string

String allows DiskMDCacheStartState to be output as a string.

type DiskMDCacheStatus

type DiskMDCacheStatus struct {
	StartState DiskMDCacheStartState
	NumMDs     uint64
	NumStaged  uint64
	Hits       MeterStatus
	Misses     MeterStatus
	Puts       MeterStatus
}

DiskMDCacheStatus represents the status of the MD cache.

type DiskQuotaCache

type DiskQuotaCache interface {
	// Get gets the latest cached quota for the given ID from the disk
	// cache.
	Get(ctx context.Context, id keybase1.UserOrTeamID) (
		info kbfsblock.QuotaInfo, err error)
	// Put stores the latest cached quota for the given ID to the disk
	// cache.
	Put(ctx context.Context, id keybase1.UserOrTeamID,
		info kbfsblock.QuotaInfo) (err error)
	// Status returns the current status of the disk cache.
	Status(ctx context.Context) DiskQuotaCacheStatus
	// Shutdown cleanly shuts down the disk quota cache.
	Shutdown(ctx context.Context)
}

DiskQuotaCache caches encrypts per-ID quotas to the disk.

type DiskQuotaCacheError

type DiskQuotaCacheError struct {
	Msg string
}

DiskQuotaCacheError is a generic disk cache error.

func (DiskQuotaCacheError) Error

func (e DiskQuotaCacheError) Error() string

Error implements the Error interface for DiskQuotaCacheError.

func (DiskQuotaCacheError) ToStatus

func (e DiskQuotaCacheError) ToStatus() (s keybase1.Status)

ToStatus implements the ExportableError interface for DiskQuotaCacheError.

type DiskQuotaCacheLocal

type DiskQuotaCacheLocal struct {
	// contains filtered or unexported fields
}

DiskQuotaCacheLocal is the standard implementation for DiskQuotaCache.

func (*DiskQuotaCacheLocal) Get

Get implements the DiskQuotaCache interface for DiskQuotaCacheLocal.

func (*DiskQuotaCacheLocal) Put

Put implements the DiskQuotaCache interface for DiskQuotaCacheLocal.

func (*DiskQuotaCacheLocal) Shutdown

func (cache *DiskQuotaCacheLocal) Shutdown(ctx context.Context)

Shutdown implements the DiskQuotaCache interface for DiskQuotaCacheLocal.

func (*DiskQuotaCacheLocal) Status

Status implements the DiskQuotaCache interface for DiskQuotaCacheLocal.

func (*DiskQuotaCacheLocal) WaitUntilStarted

func (cache *DiskQuotaCacheLocal) WaitUntilStarted() error

WaitUntilStarted waits until this cache has started.

type DiskQuotaCacheStartState

type DiskQuotaCacheStartState int

DiskQuotaCacheStartState represents whether this disk Quota cache has started or failed.

const (
	// DiskQuotaCacheStartStateStarting represents when the cache is starting.
	DiskQuotaCacheStartStateStarting DiskQuotaCacheStartState = iota
	// DiskQuotaCacheStartStateStarted represents when the cache has started.
	DiskQuotaCacheStartStateStarted
	// DiskQuotaCacheStartStateFailed represents when the cache has failed to
	// start.
	DiskQuotaCacheStartStateFailed
)

func (DiskQuotaCacheStartState) String

func (s DiskQuotaCacheStartState) String() string

String allows DiskQuotaCacheStartState to be output as a string.

type DiskQuotaCacheStatus

type DiskQuotaCacheStatus struct {
	StartState DiskQuotaCacheStartState
	NumQuotas  uint64
	Hits       MeterStatus
	Misses     MeterStatus
	Puts       MeterStatus
}

DiskQuotaCacheStatus represents the status of the Quota cache.

type ECMRCtxTagKey

type ECMRCtxTagKey struct{}

ECMRCtxTagKey is the type for unique ECMR background operation IDs.

type ECQUCtxTagKey

type ECQUCtxTagKey struct{}

ECQUCtxTagKey is the type for unique ECQU background operation IDs.

type EmptyNameError

type EmptyNameError struct {
	// contains filtered or unexported fields
}

EmptyNameError indicates that the user tried to use an empty name for the given BlockRef.

func (EmptyNameError) Error

func (e EmptyNameError) Error() string

Error implements the error interface for EmptyNameError.

type EncryptedTLFCryptKeyClientAndEphemeral

type EncryptedTLFCryptKeyClientAndEphemeral struct {
	// PublicKey contains the wrapped Key ID of the public key
	PubKey kbfscrypto.CryptPublicKey
	// ClientHalf contains the encrypted client half of the TLF key
	ClientHalf kbfscrypto.EncryptedTLFCryptKeyClientHalf
	// EPubKey contains the ephemeral public key used to encrypt ClientHalf
	EPubKey kbfscrypto.TLFEphemeralPublicKey
}

EncryptedTLFCryptKeyClientAndEphemeral has what's needed to request a client half decryption.

type EntryInfo

type EntryInfo struct {
	Type    EntryType
	Size    uint64
	SymPath string `codec:",omitempty"` // must be within the same root dir
	// Mtime is in unix nanoseconds
	Mtime int64
	// Ctime is in unix nanoseconds
	Ctime int64
	// If this is a team TLF, we want to track the last writer of an
	// entry, since in the block, only the team ID will be tracked.
	TeamWriter keybase1.UID `codec:"tw,omitempty"`
	// Tracks a skiplist of the previous revisions for this entry.
	PrevRevisions PrevRevisions `codec:"pr,omitempty"`
}

EntryInfo is the (non-block-related) info a directory knows about its child.

NOTE: Don't add or modify anything in this struct without considering how old clients will handle them (since this is embedded in DirEntry).

func EntryInfoFromFileInfo

func EntryInfoFromFileInfo(fi os.FileInfo) EntryInfo

EntryInfoFromFileInfo converts an `os.FileInfo` into an `EntryInfo`, to the best of our ability to do so. The caller is responsible for filling in `EntryInfo.SymPath`, if needed.

func (EntryInfo) Eq

func (ei EntryInfo) Eq(other EntryInfo) bool

Eq returns true if `other` is equal to `ei`.

type EntryType

type EntryType int

EntryType is the type of a directory entry.

const (
	// File is a regular file.
	File EntryType = iota
	// Exec is an executable file.
	Exec
	// Dir is a directory.
	Dir
	// Sym is a symbolic link.
	Sym

	// FakeDir can be used to indicate a faked-out entry for a directory,
	// that will be specially processed by folderBranchOps.
	FakeDir EntryType = 0xffff
)

func (EntryType) IsFile

func (et EntryType) IsFile() bool

IsFile returns whether or not this entry points to a file.

func (EntryType) String

func (et EntryType) String() string

String implements the fmt.Stringer interface for EntryType

type ErrBlockMetadataStoreShutdown

type ErrBlockMetadataStoreShutdown struct{}

ErrBlockMetadataStoreShutdown is returned when methods are called on diskBlockMetadataStore when it's already shutdown.

func (ErrBlockMetadataStoreShutdown) Error

Error implements the error interface.

type ErrDiskLimitTimeout

type ErrDiskLimitTimeout struct {
	// contains filtered or unexported fields
}

ErrDiskLimitTimeout is returned when putBlockData exceeds diskLimitTimeout when trying to acquire bytes to put.

func (*ErrDiskLimitTimeout) Error

func (e *ErrDiskLimitTimeout) Error() string

Error implements the error interface for ErrDiskLimitTimeout. It has a pointer receiver because `block_util.go` need to modify it in some cases while preserving any stacks attached to it via the `errors` package.

type ErrorFileAccessError

type ErrorFileAccessError struct {
}

ErrorFileAccessError indicates that the user tried to perform an operation on the ErrorFile that is not allowed.

func (ErrorFileAccessError) Error

func (e ErrorFileAccessError) Error() string

Error implements the error interface for ErrorFileAccessError

type ErrorModeType

type ErrorModeType int

ErrorModeType indicates what type of operation was being attempted when an error was reported.

const (
	// ReadMode indicates that an error happened while trying to read.
	ReadMode ErrorModeType = iota
	// WriteMode indicates that an error happened while trying to write.
	WriteMode
)

type EventuallyConsistentMerkleRoot

type EventuallyConsistentMerkleRoot struct {
	// contains filtered or unexported fields
}

EventuallyConsistentMerkleRoot keeps tracks of the current global Merkle root, in a way user of which can choose to accept stale data to reduce calls to the API server.

func NewEventuallyConsistentMerkleRoot

func NewEventuallyConsistentMerkleRoot(
	config Config, getter merkleRootGetter) *EventuallyConsistentMerkleRoot

NewEventuallyConsistentMerkleRoot creates a new EventuallyConsistentMerkleRoot object.

func (*EventuallyConsistentMerkleRoot) Get

func (ecmr *EventuallyConsistentMerkleRoot) Get(
	ctx context.Context, bgTolerance, blockTolerance time.Duration) (
	timestamp time.Time, root keybase1.MerkleRootV2,
	rootTime time.Time, err error)

Get returns the current merkle root, and the server timestamp of that root. To help avoid having too frequent calls into the API server, caller can provide a positive tolerance, to accept stale LimitBytes and UsageBytes data. If tolerance is 0 or negative, this always makes a blocking RPC to bserver and return latest quota usage.

1) If the age of cached data is more than blockTolerance, a blocking RPC is issued and the function only returns after RPC finishes, with the newest data from RPC. The RPC causes cached data to be refreshed as well. 2) Otherwise, if the age of cached data is more than bgTolerance, a background RPC is spawned to refresh cached data, and the stale data is returned immediately. 3) Otherwise, the cached stale data is returned immediately.

type EventuallyConsistentQuotaUsage

type EventuallyConsistentQuotaUsage struct {
	// contains filtered or unexported fields
}

EventuallyConsistentQuotaUsage keeps tracks of quota usage, in a way user of which can choose to accept stale data to reduce calls into block servers.

func NewEventuallyConsistentQuotaUsage

func NewEventuallyConsistentQuotaUsage(
	config Config, loggerSuffix string) *EventuallyConsistentQuotaUsage

NewEventuallyConsistentQuotaUsage creates a new EventuallyConsistentQuotaUsage object.

func NewEventuallyConsistentTeamQuotaUsage

func NewEventuallyConsistentTeamQuotaUsage(
	config Config, tid keybase1.TeamID,
	loggerSuffix string) *EventuallyConsistentQuotaUsage

NewEventuallyConsistentTeamQuotaUsage creates a new EventuallyConsistentQuotaUsage object.

func (*EventuallyConsistentQuotaUsage) Get

func (q *EventuallyConsistentQuotaUsage) Get(
	ctx context.Context, bgTolerance, blockTolerance time.Duration) (
	timestamp time.Time, usageBytes, archiveBytes, limitBytes int64,
	err error)

Get returns KBFS bytes used and limit for user, for the current default block type. To help avoid having too frequent calls into bserver, caller can provide a positive tolerance, to accept stale LimitBytes and UsageBytes data. If tolerance is 0 or negative, this always makes a blocking RPC to bserver and return latest quota usage.

1) If the age of cached data is more than blockTolerance, a blocking RPC is issued and the function only returns after RPC finishes, with the newest data from RPC. The RPC causes cached data to be refreshed as well. 2) Otherwise, if the age of cached data is more than bgTolerance, a background RPC is spawned to refresh cached data, and the stale data is returned immediately. 3) Otherwise, the cached stale data is returned immediately.

func (*EventuallyConsistentQuotaUsage) GetAllTypes

func (q *EventuallyConsistentQuotaUsage) GetAllTypes(
	ctx context.Context, bgTolerance, blockTolerance time.Duration) (
	timestamp time.Time,
	usageBytes, archiveBytes, limitBytes,
	gitUsageBytes, gitArchiveBytes, gitLimitBytes int64, err error)

GetAllTypes is the same as Get, except it returns usage and limits for all block types.

type Excl

type Excl bool

Excl indicates whether O_EXCL is set on a fuse call

const (
	// NoExcl indicates O_EXCL is not set
	NoExcl Excl = false

	// WithExcl indicates O_EXCL is set
	WithExcl Excl = true
)

func (Excl) String

func (o Excl) String() string

type ExclOnUnmergedError

type ExclOnUnmergedError struct {
}

ExclOnUnmergedError happens when an operation with O_EXCL set when fbo is on an unmerged local revision

func (ExclOnUnmergedError) Error

func (e ExclOnUnmergedError) Error() string

Error implements the error interface for ExclOnUnmergedError.

type ExtendedIdentifyAlreadyExists

type ExtendedIdentifyAlreadyExists struct{}

ExtendedIdentifyAlreadyExists is returned when MakeExtendedIdentify is called on a context already with extendedIdentify.

func (ExtendedIdentifyAlreadyExists) Error

type Favorite

type Favorite struct {
	Name string
	Type tlf.Type
}

Favorite is a top-level favorited folder name.

func NewFavoriteFromFolder

func NewFavoriteFromFolder(folder keybase1.Folder) *Favorite

NewFavoriteFromFolder creates a Favorite from a keybase1.Folder.

func (Favorite) ToKBFolder

func (f Favorite) ToKBFolder(created bool) keybase1.Folder

ToKBFolder creates a keybase1.Folder from a Favorite.

type Favorites

type Favorites struct {
	// contains filtered or unexported fields
}

Favorites manages a user's favorite list.

func NewFavorites

func NewFavorites(config Config) *Favorites

NewFavorites constructs a new Favorites instance.

func (*Favorites) Add

func (f *Favorites) Add(ctx context.Context, fav favToAdd) error

Add adds a favorite to your favorites list.

func (*Favorites) AddAsync

func (f *Favorites) AddAsync(ctx context.Context, fav favToAdd)

AddAsync initiates a request to add this favorite to your favorites list, if one is not already in flight, but it doesn't wait for the result. (It could block while kicking off the request, if lots of different favorite operations are in flight.) The given context is used only for enqueuing the request on an internal queue, not for any resulting I/O.

func (*Favorites) ClearCache

func (f *Favorites) ClearCache(ctx context.Context)

ClearCache clears the cached list of favorites.

func (*Favorites) Delete

func (f *Favorites) Delete(ctx context.Context, fav Favorite) error

Delete deletes a favorite from the favorites list. It is idempotent.

func (*Favorites) Get

func (f *Favorites) Get(ctx context.Context) ([]Favorite, error)

Get returns the logged-in user's list of favorites. It uses the cache.

func (*Favorites) InitForTest

func (f *Favorites) InitForTest()

InitForTest starts the Favorites cache's internal processing loop without loading cached favorites from disk.

func (*Favorites) Initialize

func (f *Favorites) Initialize(ctx context.Context)

Initialize loads the favorites cache from disk and starts listening for requests asynchronously.

func (*Favorites) RefreshCache

func (f *Favorites) RefreshCache(ctx context.Context)

RefreshCache refreshes the cached list of favorites.

func (*Favorites) Shutdown

func (f *Favorites) Shutdown() error

Shutdown shuts down this Favorites instance.

type FavoritesOp

type FavoritesOp int

FavoritesOp defines an operation related to favorites.

const (

	// FavoritesOpAdd means TLF should be added to favorites.
	FavoritesOpAdd FavoritesOp
	// FavoritesOpAddNewlyCreated means TLF should be added to favorites, and it
	// should be considered newly created.
	FavoritesOpAddNewlyCreated
	// FavoritesOpRemove means TLF should be removed from favorites.
	FavoritesOpRemove
	// FavoritesOpNoChange means no changes regarding to favorites should be made.
	FavoritesOpNoChange
)

type FileBlock

type FileBlock struct {
	CommonBlock
	// if not indirect, the full contents of this block
	Contents []byte `codec:"c,omitempty"`
	// if indirect, contains the indirect pointers to the next level of blocks
	IPtrs []IndirectFilePtr `codec:"i,omitempty"`
	// contains filtered or unexported fields
}

FileBlock is the contents of a file

func (*FileBlock) AppendNewIndirectPtr

func (fb *FileBlock) AppendNewIndirectPtr(ptr BlockPointer, off Offset)

AppendNewIndirectPtr implements the BlockWithPtrs interface for FileBlock.

func (*FileBlock) BytesCanBeDirtied

func (fb *FileBlock) BytesCanBeDirtied() int64

BytesCanBeDirtied implements the Block interface for FileBlock.

func (*FileBlock) ClearIndirectPtrSize

func (fb *FileBlock) ClearIndirectPtrSize(i int)

ClearIndirectPtrSize implements the BlockWithPtrs interface for FileBlock.

func (*FileBlock) DataVersion

func (fb *FileBlock) DataVersion() DataVer

DataVersion returns data version for this block, which is assumed to have been modified locally.

func (*FileBlock) DeepCopy

func (fb *FileBlock) DeepCopy() *FileBlock

DeepCopy makes a complete copy of a FileBlock

func (*FileBlock) FirstOffset

func (fb *FileBlock) FirstOffset() Offset

FirstOffset implements the Block interface for FileBlock.

func (*FileBlock) GetHash

func (fb *FileBlock) GetHash() kbfshash.RawDefaultHash

GetHash returns the hash of this FileBlock. If the hash is nil, it first calculates it.

func (*FileBlock) IndirectPtr

func (fb *FileBlock) IndirectPtr(i int) (BlockInfo, Offset)

IndirectPtr implements the BlockWithPtrs interface for FileBlock.

func (*FileBlock) IsTail

func (fb *FileBlock) IsTail() bool

IsTail implements the Block interface for FileBlock.

func (*FileBlock) NewEmptier

func (fb *FileBlock) NewEmptier() func() Block

NewEmptier implements the Block interface for FileBlock.

func (*FileBlock) NewEmpty

func (fb *FileBlock) NewEmpty() Block

NewEmpty implements the Block interface for FileBlock

func (*FileBlock) NumIndirectPtrs

func (fb *FileBlock) NumIndirectPtrs() int

NumIndirectPtrs implements the BlockWithPtrs interface for FileBlock.

func (*FileBlock) OffsetExceedsData

func (fb *FileBlock) OffsetExceedsData(startOff, off Offset) bool

OffsetExceedsData implements the Block interface for FileBlock.

func (*FileBlock) Set

func (fb *FileBlock) Set(other Block)

Set implements the Block interface for FileBlock

func (*FileBlock) SetIndirectPtrInfo

func (fb *FileBlock) SetIndirectPtrInfo(i int, info BlockInfo)

SetIndirectPtrInfo implements the BlockWithPtrs interface for FileBlock.

func (*FileBlock) SetIndirectPtrOff

func (fb *FileBlock) SetIndirectPtrOff(i int, off Offset)

SetIndirectPtrOff implements the BlockWithPtrs interface for FileBlock.

func (*FileBlock) SetIndirectPtrType

func (fb *FileBlock) SetIndirectPtrType(i int, dt BlockDirectType)

SetIndirectPtrType implements the BlockWithPtrs interface for FileBlock.

func (*FileBlock) SwapIndirectPtrs

func (fb *FileBlock) SwapIndirectPtrs(i int, other BlockWithPtrs, otherI int)

SwapIndirectPtrs implements the BlockWithPtrs interface for FileBlock.

func (*FileBlock) ToCommonBlock

func (fb *FileBlock) ToCommonBlock() *CommonBlock

ToCommonBlock implements the Block interface for FileBlock.

type FileTooBigForCRError

type FileTooBigForCRError struct {
	// contains filtered or unexported fields
}

FileTooBigForCRError indicates that a file is too big to fit in memory, and CR can't handle it.

func (FileTooBigForCRError) Error

func (e FileTooBigForCRError) Error() string

Error implements the error interface for FileTooBigForCRError.

type FolderBranch

type FolderBranch struct {
	Tlf    tlf.ID
	Branch BranchName // master branch, by default
}

FolderBranch represents a unique pair of top-level folder and a branch of that folder.

func (FolderBranch) String

func (fb FolderBranch) String() string

type FolderBranchStatus

type FolderBranchStatus struct {
	Staged              bool
	BranchID            string
	HeadWriter          kbname.NormalizedUsername
	DiskUsage           uint64
	RekeyPending        bool
	LatestKeyGeneration kbfsmd.KeyGen
	FolderID            string
	Revision            kbfsmd.Revision
	LastGCRevision      kbfsmd.Revision
	MDVersion           kbfsmd.MetadataVer
	RootBlockID         string
	SyncEnabled         bool
	PrefetchStatus      string
	UsageBytes          int64
	ArchiveBytes        int64
	LimitBytes          int64
	GitUsageBytes       int64
	GitArchiveBytes     int64
	GitLimitBytes       int64

	// DirtyPaths are files that have been written, but not flushed.
	// They do not represent unstaged changes in your local instance.
	DirtyPaths []string

	// If we're in the staged state, these summaries show the
	// diverging operations per-file
	Unmerged []*crChainSummary
	Merged   []*crChainSummary

	Journal *TLFJournalStatus `json:",omitempty"`

	PermanentErr string `json:",omitempty"`
}

FolderBranchStatus is a simple data structure describing the current status of a particular folder-branch. It is suitable for encoding directly as JSON.

type FolderNotResetOnServer

type FolderNotResetOnServer struct {
	// contains filtered or unexported fields
}

FolderNotResetOnServer indicates that a folder can't be reset by the user, because it hasn't yet been reset on the mdserver.

func (FolderNotResetOnServer) Error

func (e FolderNotResetOnServer) Error() string

Error implements the Error interface for FolderNotResetOnServer.

type FolderSyncConfig

type FolderSyncConfig struct {
	Mode  keybase1.FolderSyncMode         `codec:"mode" json:"mode"`
	Paths FolderSyncEncryptedPartialPaths `codec:"paths" json:"paths"`
}

FolderSyncConfig is the on-disk representation for a TLF sync config.

type FolderSyncEncryptedPartialPaths

type FolderSyncEncryptedPartialPaths struct {
	Ptr        BlockPointer
	Buf        []byte
	ServerHalf kbfscrypto.BlockCryptKeyServerHalf
}

FolderSyncEncryptedPartialPaths describes an encrypted block containing the paths of a partial sync config.

type GCOp

type GCOp struct {
	OpCommon

	// LatestRev is the most recent MD revision that was
	// garbage-collected with this operation.
	//
	// The codec name overrides the one for RefBlocks in OpCommon,
	// which GCOp doesn't use.
	LatestRev kbfsmd.Revision `codec:"r"`
}

GCOp is an op that represents garbage-collecting the history of a folder (which may involve unreferencing blocks that previously held operation lists. It may contain unref blocks before it is added to the metadata ops list.

func (*GCOp) SizeExceptUpdates

func (gco *GCOp) SizeExceptUpdates() uint64

SizeExceptUpdates implements op.

func (*GCOp) String

func (gco *GCOp) String() string

func (*GCOp) StringWithRefs

func (gco *GCOp) StringWithRefs(indent string) string

StringWithRefs implements the op interface for GCOp.

type ImmutableBareRootMetadata

type ImmutableBareRootMetadata struct {
	kbfsmd.RootMetadata
	// contains filtered or unexported fields
}

ImmutableBareRootMetadata is a thin wrapper around a BareRootMetadata and a kbfsmd.ExtraMetadata that takes ownership of it and does not ever modify it again. Thus, its MdID can be calculated and stored along with a local timestamp. ImmutableBareRootMetadata objects can be assumed to never alias a (modifiable) BareRootMetadata.

Note that kbfsmd.MakeID() on an ImmutableBareRootMetadata will compute the wrong result, since anonymous fields of interface type are not encoded inline by the codec. Use kbfsmd.MakeID(ibrmd.BareRootMetadata) instead.

TODO: Move this to bare_root_metadata.go if it's used in more places.

func MakeImmutableBareRootMetadata

func MakeImmutableBareRootMetadata(
	rmd kbfsmd.RootMetadata, extra kbfsmd.ExtraMetadata, mdID kbfsmd.ID,
	localTimestamp time.Time) ImmutableBareRootMetadata

MakeImmutableBareRootMetadata makes a new ImmutableBareRootMetadata from the given BareRootMetadata and its corresponding MdID.

func (ImmutableBareRootMetadata) MakeBareTlfHandleWithExtra

func (ibrmd ImmutableBareRootMetadata) MakeBareTlfHandleWithExtra() (
	tlf.Handle, error)

MakeBareTlfHandleWithExtra makes a BareTlfHandle for this ImmutableBareRootMetadata. Should be used only by servers and MDOps.

type ImmutableRootMetadata

type ImmutableRootMetadata struct {
	ReadOnlyRootMetadata
	// contains filtered or unexported fields
}

ImmutableRootMetadata is a thin wrapper around a ReadOnlyRootMetadata that takes ownership of it and does not ever modify it again. Thus, its MdID can be calculated and stored. Unlike ReadOnlyRootMetadata, ImmutableRootMetadata objects can be assumed to never alias a (modifiable) *RootMetadata.

func MakeCopyWithDecryptedPrivateData

func MakeCopyWithDecryptedPrivateData(
	ctx context.Context, config Config,
	irmdToDecrypt, irmdWithKeys ImmutableRootMetadata, uid keybase1.UID) (
	rmdDecrypted ImmutableRootMetadata, err error)

MakeCopyWithDecryptedPrivateData makes a copy of the given IRMD, decrypting it with the given IRMD with keys.

func MakeImmutableRootMetadata

func MakeImmutableRootMetadata(
	rmd *RootMetadata, writerVerifyingKey kbfscrypto.VerifyingKey,
	mdID kbfsmd.ID, localTimestamp time.Time,
	putToServer bool) ImmutableRootMetadata

MakeImmutableRootMetadata makes a new ImmutableRootMetadata from the given RMD and its corresponding MdID.

func (ImmutableRootMetadata) LastModifyingWriterVerifyingKey

func (irmd ImmutableRootMetadata) LastModifyingWriterVerifyingKey() kbfscrypto.VerifyingKey

LastModifyingWriterVerifyingKey returns the VerifyingKey used by the last writer of this MD.

func (ImmutableRootMetadata) LocalTimestamp

func (irmd ImmutableRootMetadata) LocalTimestamp() time.Time

LocalTimestamp returns the timestamp associated with this RootMetadata object.

func (ImmutableRootMetadata) MdID

func (irmd ImmutableRootMetadata) MdID() kbfsmd.ID

MdID returns the pre-computed MdID of the contained RootMetadata object.

type ImpatientDebugDumper

type ImpatientDebugDumper struct {
	// contains filtered or unexported fields
}

ImpatientDebugDumper dumps all running goroutines if an operation takes longer than a preset value. User of this type should call Begin() with a context associated with an operation, and call the returned function when the operation is done. If the operation finishes within the preset duration, nothing is dumped into log. Despite being impatient, it tries not to pollute the log too much by rate limit goroutine dumping based on impatientDebugDumperDumpMinInterval (at most 1 per minute).

func NewImpatientDebugDumper

func NewImpatientDebugDumper(config Config, dumpIn time.Duration) *ImpatientDebugDumper

NewImpatientDebugDumper creates a new *ImpatientDebugDumper, which logs with a logger made by config.MakeLogger("IGD"), and dumps goroutines if an operation takes longer than dumpIn.

func NewImpatientDebugDumperForForcedDumps

func NewImpatientDebugDumperForForcedDumps(config Config) *ImpatientDebugDumper

NewImpatientDebugDumperForForcedDumps creates a new *ImpatientDebugDumper, just as above, though without launching any background goroutines or allowing the user to begin any time-tracked tasks. `ForceDump` is the only way to obtain a dump from a dumper constructed with this function.

func (*ImpatientDebugDumper) Begin

func (d *ImpatientDebugDumper) Begin(ctx context.Context) (done func())

Begin causes d to start tracking time for ctx. The returned function should be called once the associated operation is done, likely in a defer statement.

func (*ImpatientDebugDumper) ForceDump

func (d *ImpatientDebugDumper) ForceDump(ctx context.Context)

ForceDump dumps all debug info to the log, if it hasn't done so recently according to the rate-limiter.

func (*ImpatientDebugDumper) Shutdown

func (d *ImpatientDebugDumper) Shutdown()

Shutdown shuts down d idempotently.

type ImplicitTeamInfo

type ImplicitTeamInfo struct {
	Name  kbname.NormalizedUsername // The "display" name for the i-team.
	TID   keybase1.TeamID
	TlfID tlf.ID
}

ImplicitTeamInfo contains information needed after resolving/identifying an implicit team. TeamInfo is used for anything else.

type IncompatibleHandleError

type IncompatibleHandleError struct {
	// contains filtered or unexported fields
}

IncompatibleHandleError indicates that somethine tried to update the head of a TLF with a RootMetadata with an incompatible handle.

func (IncompatibleHandleError) Error

func (e IncompatibleHandleError) Error() string

type InconsistentEncodedSizeError

type InconsistentEncodedSizeError struct {
	// contains filtered or unexported fields
}

InconsistentEncodedSizeError is raised when a dirty block has a non-zero encoded size.

func (InconsistentEncodedSizeError) Error

Error implements the error interface for InconsistentEncodedSizeError

type IndirectDirPtr

type IndirectDirPtr struct {
	// TODO: Make sure that the block is not dirty when the EncodedSize
	// field is non-zero.
	BlockInfo
	Off StringOffset `codec:"o"`

	codec.UnknownFieldSetHandler
}

IndirectDirPtr pairs an indirect dir block with the start of that block's range of directory entries (inclusive)

type IndirectFilePtr

type IndirectFilePtr struct {
	// When the EncodedSize field is non-zero, the block must not
	// be dirty.
	BlockInfo
	Off Int64Offset `codec:"o"`
	// Marker for files with holes.  This is here for historical
	// reasons; a `FileBlock` should be treated as having a `HasHoles`
	// flag set to true if any of its IPtrs have `Holes` set to true.
	Holes bool `codec:"h,omitempty"`

	codec.UnknownFieldSetHandler
}

IndirectFilePtr pairs an indirect file block with the start of that block's range of bytes (inclusive)

If `Holes` is true, then this pointer is part of a list of pointers that has non-continuous offsets; that is, the offset of ptr `i` plus the length of the corresponding block contents is less than the offset of ptr `i`+1.

type InfiniteChannelWrapper

type InfiniteChannelWrapper struct {
	*channels.InfiniteChannel
	// contains filtered or unexported fields
}

InfiniteChannelWrapper is a wrapper to allow us to select on sending to an infinite channel without fearing a panic when we Close() it.

func NewInfiniteChannelWrapper

func NewInfiniteChannelWrapper() *InfiniteChannelWrapper

NewInfiniteChannelWrapper returns a wrapper around a new infinite channel.

func (*InfiniteChannelWrapper) Close

func (ch *InfiniteChannelWrapper) Close()

Close shuts down this infinite channel.

func (*InfiniteChannelWrapper) In

func (ch *InfiniteChannelWrapper) In() chan<- interface{}

In returns the input channel for this infinite channel.

type InitMode

type InitMode interface {
	// Type returns the InitModeType of this mode.
	Type() InitModeType
	// IsTestMode returns whether we are running a test.
	IsTestMode() bool
	// BlockWorkers returns the number of block workers to run.
	BlockWorkers() int
	// PrefetchWorkers returns the number of prefetch workers to run.
	PrefetchWorkers() int
	// ThrottledPrefetchTime returns the period for each prefetch
	// worker to start a throttled prefetch request.
	ThrottledPrefetchPeriod() time.Duration
	// DefaultBlockRequestAction returns the action to be used by
	// default whenever fetching a block.
	DefaultBlockRequestAction() BlockRequestAction
	// RekeyWorkers returns the number of rekey workers to run.
	RekeyWorkers() int
	// RekeyQueueSize returns the size of the rekey queue.
	RekeyQueueSize() int
	// DirtyBlockCacheEnabled indicates if we should run a dirty block
	// cache.
	DirtyBlockCacheEnabled() bool
	// BackgroundFlushesEnabled indicates if we should periodically be
	// flushing unsynced dirty writes to the server or journal.
	BackgroundFlushesEnabled() bool
	// MetricsEnabled indicates if we should be collecting metrics.
	MetricsEnabled() bool
	// ConflictResolutionEnabled indicated if we should be running
	// the conflict resolution background process.
	ConflictResolutionEnabled() bool
	// BlockManagementEnabled indicates whether we should be running
	// the block archive/delete background process, and whether we
	// should be re-embedding block change blocks in MDs.
	BlockManagementEnabled() bool
	// QuotaReclamationEnabled indicates whether we should be running
	// the quota reclamation background process.
	QuotaReclamationEnabled() bool
	// QuotaReclamationPeriod indicates how often should each TLF
	// should check for quota to reclaim.  If the Duration.Seconds()
	// == 0, quota reclamation should not run automatically.
	QuotaReclamationPeriod() time.Duration
	// QuotaReclamationMinUnrefAge indicates the minimum time a block
	// must have been unreferenced before it can be reclaimed.
	QuotaReclamationMinUnrefAge() time.Duration
	// QuotaReclamationMinHeadAge indicates the minimum age of the
	// most recently merged MD update before we can run reclamation,
	// to avoid conflicting with a currently active writer.
	QuotaReclamationMinHeadAge() time.Duration
	// NodeCacheEnabled indicates whether we should be caching data nodes.
	NodeCacheEnabled() bool
	// TLFUpdatesEnabled indicates whether we should be registering
	// ourselves with the mdserver for TLF updates.
	TLFUpdatesEnabled() bool
	// KBFSServiceEnabled indicates whether we should launch a local
	// service for answering incoming KBFS-related RPCs.
	KBFSServiceEnabled() bool
	// JournalEnabled indicates whether this mode supports a journal.
	JournalEnabled() bool
	// UnmergedTLFsEnabled indicates whether it's possible for a
	// device in this mode to have unmerged TLFs.
	UnmergedTLFsEnabled() bool
	// ServiceKeepaliveEnabled indicates whether we need to send
	// keepalive probes to the Keybase service daemon.
	ServiceKeepaliveEnabled() bool
	// TLFEditHistoryEnabled indicates whether we should be running
	// the background TLF edit history process.
	TLFEditHistoryEnabled() bool
	// SendEditNotificationsEnabled indicates whether we should send
	// edit notifications on FS writes.
	SendEditNotificationsEnabled() bool
	// ClientType indicates the type we should advertise to the
	// Keybase service.
	ClientType() keybase1.ClientType
	// LocalHTTPServerEnabled represents whether we should launch an HTTP
	// server.
	LocalHTTPServerEnabled() bool
	// MaxCleanBlockCacheCapacity is the maximum number of bytes to be taken up
	// by the clean block cache.
	MaxCleanBlockCacheCapacity() uint64
}

InitMode encapsulates mode differences.

func NewInitModeFromType

func NewInitModeFromType(t InitModeType) InitMode

NewInitModeFromType returns an InitMode object corresponding to the given type.

type InitModeType

type InitModeType int

InitModeType indicates how KBFS should configure itself at runtime.

const (
	// InitDefault is the normal mode for when KBFS data will be read
	// and written.
	InitDefault InitModeType = iota
	// InitMinimal is for when KBFS will only be used as a MD lookup
	// layer (e.g., for chat on mobile).
	InitMinimal
	// InitSingleOp is a mode for when KBFS is only needed for a
	// single logical operation; no rekeys or update subscriptions is
	// needed, and some naming restrictions are lifted (e.g., `.kbfs_`
	// filenames are allowed).
	InitSingleOp
	// InitConstrained is a mode where KBFS reads and writes data, but
	// constrains itself to using fewer resources (e.g. on mobile).
	InitConstrained
	// InitMemoryLimited is a mode where KBFS reads and writes data, but
	// constrains its memory use even further.
	InitMemoryLimited
)

func (InitModeType) String

func (im InitModeType) String() string

type InitParams

type InitParams struct {
	// Whether to print debug messages.
	Debug bool

	// If non-empty, the host:port of the block server. If empty,
	// a default value is used depending on the run mode. Can also
	// be "memory" for an in-memory test server or
	// "dir:/path/to/dir" for an on-disk test server.
	BServerAddr string

	// If non-empty the host:port of the metadata server. If
	// empty, a default value is used depending on the run mode.
	// Can also be "memory" for an in-memory test server or
	// "dir:/path/to/dir" for an on-disk test server.
	MDServerAddr string

	// If non-zero, specifies the capacity (in bytes) of the block cache. If
	// zero, the capacity is set using getDefaultBlockCacheCapacity().
	CleanBlockCacheCapacity uint64

	// Fake local user name.
	LocalUser string

	// Where to put favorites. Has an effect only when LocalUser
	// is non-empty, in which case it must be either "memory" or
	// "dir:/path/to/dir".
	LocalFavoriteStorage string

	// TLFValidDuration is the duration that TLFs are valid
	// before marked for lazy revalidation.
	TLFValidDuration time.Duration

	// MetadataVersion is the default version of metadata to use
	// when creating new metadata.
	MetadataVersion kbfsmd.MetadataVer

	// BlockCryptVersion is the encryption version to use when
	// encrypting new blocks.
	BlockCryptVersion kbfscrypto.EncryptionVer

	// LogToFile if true, logs to a default file location.
	LogToFile bool

	// LogFileConfig tells us where to log and rotation config.
	LogFileConfig logger.LogFileConfig

	// TLFJournalBackgroundWorkStatus is the status to use to
	// pass into JournalServer.enableJournaling. Only has an effect when
	// EnableJournal is non-empty.
	TLFJournalBackgroundWorkStatus TLFJournalBackgroundWorkStatus

	// AdditionalProtocolCreators are for adding additional protocols that we
	// should handle for service to call in.
	AdditionalProtocolCreators []AdditionalProtocolCreator

	// EnableJournal enables journaling.
	EnableJournal bool

	// DiskCacheMode specifies which mode to start the disk cache.
	DiskCacheMode DiskCacheMode

	// StorageRoot, if non-empty, points to a local directory to put its local
	// databases for things like the journal or disk cache.
	StorageRoot string

	// BGFlushPeriod indicates how long to wait for a batch to fill up
	// before syncing a set of changes on a TLF to the servers.
	BGFlushPeriod time.Duration

	// BGFlushDirOpBatchSize indicates how many directory operations
	// in a TLF should be batched together in a single background
	// flush.
	BGFlushDirOpBatchSize int

	// Mode describes how KBFS should initialize itself.
	Mode string

	// DiskBlockCacheFraction indicates what fraction of free space on the disk
	// is allowed to be occupied by the KBFS disk block cache.
	DiskBlockCacheFraction float64

	// SyncBlockCacheFraction indicates what fraction of free space on the disk
	// is allowed to be occupied by the KBFS sync block cache for offline use.
	SyncBlockCacheFraction float64
}

InitParams contains the initialization parameters for Init(). It is usually filled in by the flags parser passed into AddFlags().

func AddFlags

func AddFlags(flags *flag.FlagSet, ctx Context) *InitParams

AddFlags adds libkbfs flags to the given FlagSet. Returns an InitParams that will be filled in once the given FlagSet is parsed.

func AddFlagsWithDefaults

func AddFlagsWithDefaults(
	flags *flag.FlagSet, defaultParams InitParams,
	defaultLogPath string) *InitParams

AddFlagsWithDefaults adds libkbfs flags to the given FlagSet, given a set of default flags. Returns an InitParams that will be filled in once the given FlagSet is parsed.

func DefaultInitParams

func DefaultInitParams(ctx Context) InitParams

DefaultInitParams returns default init params

type Int64Offset

type Int64Offset int64

Int64Offset represents the offset of a block within a file.

func (Int64Offset) Equals

func (i Int64Offset) Equals(other Offset) bool

Equals implements the Offset interface for Int64Offset.

func (Int64Offset) Less

func (i Int64Offset) Less(other Offset) bool

Less implements the Offset interface for Int64Offset.

func (Int64Offset) String

func (i Int64Offset) String() string

type InvalidBlockRefError

type InvalidBlockRefError struct {
	// contains filtered or unexported fields
}

InvalidBlockRefError indicates an invalid block reference was encountered.

func (InvalidBlockRefError) Error

func (e InvalidBlockRefError) Error() string

type InvalidDataVersionError

type InvalidDataVersionError struct {
	DataVer DataVer
}

InvalidDataVersionError indicates that an invalid data version was used.

func (InvalidDataVersionError) Error

func (e InvalidDataVersionError) Error() string

Error implements the error interface for InvalidDataVersionError.

type InvalidFavoritesOpError

type InvalidFavoritesOpError struct{}

InvalidFavoritesOpError indicates an unknown FavoritesOp has been provided.

func (InvalidFavoritesOpError) Error

Error implements the error interface for InvalidFavoritesOpError.

type InvalidOpError

type InvalidOpError struct {
	// contains filtered or unexported fields
}

InvalidOpError is returned when an operation is called that isn't supported by the current implementation.

func (InvalidOpError) Error

func (e InvalidOpError) Error() string

type InvalidParentPathError

type InvalidParentPathError struct {
	// contains filtered or unexported fields
}

InvalidParentPathError indicates a path without a valid parent was encountered.

func (InvalidParentPathError) Error

func (e InvalidParentPathError) Error() string

Error implements the error interface for InvalidParentPathError.

type InvalidPathError

type InvalidPathError struct {
	// contains filtered or unexported fields
}

InvalidPathError indicates an invalid path was encountered.

func (InvalidPathError) Error

func (e InvalidPathError) Error() string

Error implements the error interface for InvalidPathError.

type InvalidVersionError

type InvalidVersionError struct {
	// contains filtered or unexported fields
}

InvalidVersionError indicates that we have encountered some new data version we don't understand, and we don't know how to handle it.

func (InvalidVersionError) Error

func (e InvalidVersionError) Error() string

Error implements the error interface for InvalidVersionError.

type JournalServer

type JournalServer struct {
	// contains filtered or unexported fields
}

JournalServer is the server that handles write journals. It interposes itself in front of BlockServer and MDOps. It uses MDOps instead of MDServer because it has to potentially modify the RootMetadata passed in, and by the time it hits MDServer it's already too late. However, this assumes that all MD ops go through MDOps.

The maximum number of characters added to the root dir by a journal server journal is 108: 51 for the TLF journal, and 57 for everything else.

/v1/de...-...(53 characters total)...ff(/tlf journal)

func GetJournalServer

func GetJournalServer(config Config) (*JournalServer, error)

GetJournalServer returns the JournalServer tied to a particular config.

func (*JournalServer) Disable

func (j *JournalServer) Disable(ctx context.Context, tlfID tlf.ID) (
	wasEnabled bool, err error)

Disable turns off the write journal for the given TLF.

func (*JournalServer) DisableAuto

func (j *JournalServer) DisableAuto(ctx context.Context) error

DisableAuto turns off automatic write journal for any newly-accessed TLFs. Existing journaled TLFs need to be disabled manually.

func (*JournalServer) Enable

func (j *JournalServer) Enable(ctx context.Context, tlfID tlf.ID,
	h *TlfHandle, bws TLFJournalBackgroundWorkStatus) (err error)

Enable turns on the write journal for the given TLF. If h is nil, it will be attempted to be fetched from the remote MD server.

func (*JournalServer) EnableAuto

func (j *JournalServer) EnableAuto(ctx context.Context) error

EnableAuto turns on the write journal for all TLFs, even new ones, persistently.

func (*JournalServer) EnableExistingJournals

func (j *JournalServer) EnableExistingJournals(
	ctx context.Context, currentUID keybase1.UID,
	currentVerifyingKey kbfscrypto.VerifyingKey,
	bws TLFJournalBackgroundWorkStatus) (err error)

EnableExistingJournals turns on the write journal for all TLFs for the given (UID, device) tuple (with the device identified by its verifying key) with an existing journal. Any returned error means that the JournalServer remains in the same state as it was before.

Once this is called, this must not be called again until shutdownExistingJournals is called.

func (*JournalServer) FinishSingleOp

func (j *JournalServer) FinishSingleOp(ctx context.Context, tlfID tlf.ID,
	lc *keybase1.LockContext, priority keybase1.MDPriority) (err error)

FinishSingleOp lets the write journal know that the application has finished a single op, and then blocks until the write journal has finished flushing everything.

func (*JournalServer) Flush

func (j *JournalServer) Flush(ctx context.Context, tlfID tlf.ID) (err error)

Flush flushes the write journal for the given TLF.

func (*JournalServer) JournalStatus

func (j *JournalServer) JournalStatus(tlfID tlf.ID) (
	TLFJournalStatus, error)

JournalStatus returns a TLFServerStatus object for the given TLF suitable for diagnostics.

func (*JournalServer) JournalStatusWithPaths

func (j *JournalServer) JournalStatusWithPaths(ctx context.Context,
	tlfID tlf.ID, cpp chainsPathPopulator) (TLFJournalStatus, error)

JournalStatusWithPaths returns a TLFServerStatus object for the given TLF suitable for diagnostics, including paths for all the unflushed entries.

func (*JournalServer) MakeFBOsForExistingJournals

func (j *JournalServer) MakeFBOsForExistingJournals(
	ctx context.Context) *sync.WaitGroup

MakeFBOsForExistingJournals creates folderBranchOps objects for all existing, non-empty journals. This is useful to initialize the unflushed edit history, for example. It returns a wait group that the caller can use to determine when all the FBOs have been initialized. If the caller is not going to wait on the group, it should provoide a context that won't be canceled before the wait group is finished.

func (*JournalServer) PauseBackgroundWork

func (j *JournalServer) PauseBackgroundWork(ctx context.Context, tlfID tlf.ID)

PauseBackgroundWork pauses the background work goroutine, if it's not already paused.

func (*JournalServer) ResumeBackgroundWork

func (j *JournalServer) ResumeBackgroundWork(ctx context.Context, tlfID tlf.ID)

ResumeBackgroundWork resumes the background work goroutine, if it's not already resumed.

func (*JournalServer) Status

func (j *JournalServer) Status(
	ctx context.Context) (JournalServerStatus, []tlf.ID)

Status returns a JournalServerStatus object suitable for diagnostics. It also returns a list of TLF IDs which have journals enabled.

func (*JournalServer) Wait

func (j *JournalServer) Wait(ctx context.Context, tlfID tlf.ID) (err error)

Wait blocks until the write journal has finished flushing everything. It is essentially the same as Flush() when the journal is enabled and unpaused, except that it is safe to cancel the context without leaving the journal in a partially-flushed state. It does not wait for any conflicts or squashes resulting from flushing the data currently in the journal.

func (*JournalServer) WaitForCompleteFlush

func (j *JournalServer) WaitForCompleteFlush(
	ctx context.Context, tlfID tlf.ID) (err error)

WaitForCompleteFlush blocks until the write journal has finished flushing everything. Unlike `Wait()`, it also waits for any conflicts or squashes detected during each flush attempt.

type JournalServerStatus

type JournalServerStatus struct {
	RootDir             string
	Version             int
	CurrentUID          keybase1.UID
	CurrentVerifyingKey kbfscrypto.VerifyingKey
	EnableAuto          bool
	EnableAutoSetByUser bool
	JournalCount        int
	// The byte counters below are signed because
	// os.FileInfo.Size() is signed. The file counter is signed
	// for consistency.
	StoredBytes       int64
	StoredFiles       int64
	UnflushedBytes    int64
	UnflushedPaths    []string
	EndEstimate       *time.Time
	DiskLimiterStatus interface{}
}

JournalServerStatus represents the overall status of the JournalServer for display in diagnostics. It is suitable for encoding directly as JSON.

type KBFSErrorUnwrapper

type KBFSErrorUnwrapper struct {
}

KBFSErrorUnwrapper unwraps errors from the KBFS service.

func (KBFSErrorUnwrapper) MakeArg

func (eu KBFSErrorUnwrapper) MakeArg() interface{}

MakeArg implements rpc.ErrorUnwrapper.

func (KBFSErrorUnwrapper) UnwrapError

func (eu KBFSErrorUnwrapper) UnwrapError(arg interface{}) (appError error,
	dispatchError error)

UnwrapError implements rpc.ErrorUnwrapper.

type KBFSOps

type KBFSOps interface {
	// GetFavorites returns the logged-in user's list of favorite
	// top-level folders.  This is a remote-access operation.
	GetFavorites(ctx context.Context) ([]Favorite, error)
	// RefreshCachedFavorites tells the instances to forget any cached
	// favorites list and fetch a new list from the server.  The
	// effects are asychronous; if there's an error refreshing the
	// favorites, the cached favorites will become empty.
	RefreshCachedFavorites(ctx context.Context)
	// ClearCachedFavorites tells the instances to forget any cached
	// favorites list, e.g. when a user logs out.
	ClearCachedFavorites(ctx context.Context)
	// AddFavorite adds the favorite to both the server and
	// the local cache.
	AddFavorite(ctx context.Context, fav Favorite) error
	// DeleteFavorite deletes the favorite from both the server and
	// the local cache.  Idempotent, so it succeeds even if the folder
	// isn't favorited.
	DeleteFavorite(ctx context.Context, fav Favorite) error
	// RefreshEditHistory asks the FBO for the given favorite to reload its
	// edit history.
	RefreshEditHistory(fav Favorite)

	// GetTLFCryptKeys gets crypt key of all generations as well as
	// TLF ID for tlfHandle. The returned keys (the keys slice) are ordered by
	// generation, starting with the key for FirstValidKeyGen.
	GetTLFCryptKeys(ctx context.Context, tlfHandle *TlfHandle) (
		keys []kbfscrypto.TLFCryptKey, id tlf.ID, err error)

	// GetTLFID gets the TLF ID for tlfHandle.
	GetTLFID(ctx context.Context, tlfHandle *TlfHandle) (tlf.ID, error)

	// GetTLFHandle returns the TLF handle for a given node.
	GetTLFHandle(ctx context.Context, node Node) (*TlfHandle, error)

	// GetOrCreateRootNode returns the root node and root entry
	// info associated with the given TLF handle and branch, if
	// the logged-in user has read permissions to the top-level
	// folder. It creates the folder if one doesn't exist yet (and
	// branch == MasterBranch), and the logged-in user has write
	// permissions to the top-level folder.  This is a
	// remote-access operation.
	GetOrCreateRootNode(
		ctx context.Context, h *TlfHandle, branch BranchName) (
		node Node, ei EntryInfo, err error)
	// GetRootNode is like GetOrCreateRootNode but if the root node
	// does not exist it will return a nil Node and not create it.
	GetRootNode(
		ctx context.Context, h *TlfHandle, branch BranchName) (
		node Node, ei EntryInfo, err error)
	// GetDirChildren returns a map of children in the directory,
	// mapped to their EntryInfo, if the logged-in user has read
	// permission for the top-level folder.  This is a remote-access
	// operation.
	GetDirChildren(ctx context.Context, dir Node) (map[string]EntryInfo, error)
	// Lookup returns the Node and entry info associated with a
	// given name in a directory, if the logged-in user has read
	// permissions to the top-level folder.  The returned Node is nil
	// if the name is a symlink.  This is a remote-access operation.
	Lookup(ctx context.Context, dir Node, name string) (Node, EntryInfo, error)
	// Stat returns the entry info associated with a
	// given Node, if the logged-in user has read permissions to the
	// top-level folder.  This is a remote-access operation.
	Stat(ctx context.Context, node Node) (EntryInfo, error)
	// CreateDir creates a new subdirectory under the given node, if
	// the logged-in user has write permission to the top-level
	// folder.  Returns the new Node for the created subdirectory, and
	// its new entry info.  This is a remote-sync operation.
	CreateDir(ctx context.Context, dir Node, name string) (
		Node, EntryInfo, error)
	// CreateFile creates a new file under the given node, if the
	// logged-in user has write permission to the top-level folder.
	// Returns the new Node for the created file, and its new
	// entry info. excl (when implemented) specifies whether this is an exclusive
	// create.  Semantically setting excl to WithExcl is like O_CREAT|O_EXCL in a
	// Unix open() call.
	//
	// This is a remote-sync operation.
	CreateFile(ctx context.Context, dir Node, name string, isExec bool, excl Excl) (
		Node, EntryInfo, error)
	// CreateLink creates a new symlink under the given node, if the
	// logged-in user has write permission to the top-level folder.
	// Returns the new entry info for the created symlink.  This
	// is a remote-sync operation.
	CreateLink(ctx context.Context, dir Node, fromName string, toPath string) (
		EntryInfo, error)
	// RemoveDir removes the subdirectory represented by the given
	// node, if the logged-in user has write permission to the
	// top-level folder.  Will return an error if the subdirectory is
	// not empty.  This is a remote-sync operation.
	RemoveDir(ctx context.Context, dir Node, dirName string) error
	// RemoveEntry removes the directory entry represented by the
	// given node, if the logged-in user has write permission to the
	// top-level folder.  This is a remote-sync operation.
	RemoveEntry(ctx context.Context, dir Node, name string) error
	// Rename performs an atomic rename operation with a given
	// top-level folder if the logged-in user has write permission to
	// that folder, and will return an error if nodes from different
	// folders are passed in.  Also returns an error if the new name
	// already has an entry corresponding to an existing directory
	// (only non-dir types may be renamed over).  This is a
	// remote-sync operation.
	Rename(ctx context.Context, oldParent Node, oldName string, newParent Node,
		newName string) error
	// Read fills in the given buffer with data from the file at the
	// given node starting at the given offset, if the logged-in user
	// has read permission to the top-level folder.  The read data
	// reflects any outstanding writes and truncates to that file that
	// have been written through this KBFSOps object, even if those
	// writes have not yet been sync'd.  There is no guarantee that
	// Read returns all of the requested data; it will return the
	// number of bytes that it wrote to the dest buffer.  Reads on an
	// unlinked file may or may not succeed, depending on whether or
	// not the data has been cached locally.  If (0, nil) is returned,
	// that means EOF has been reached. This is a remote-access
	// operation.
	Read(ctx context.Context, file Node, dest []byte, off int64) (int64, error)
	// Write modifies the file at the given node, by writing the given
	// buffer at the given offset within the file, if the logged-in
	// user has write permission to the top-level folder.  It
	// overwrites any data already there, and extends the file size as
	// necessary to accomodate the new data.  It guarantees to write
	// the entire buffer in one operation.  Writes on an unlinked file
	// may or may not succeed as no-ops, depending on whether or not
	// the necessary blocks have been locally cached.  This is a
	// remote-access operation.
	Write(ctx context.Context, file Node, data []byte, off int64) error
	// Truncate modifies the file at the given node, by either
	// shrinking or extending its size to match the given size, if the
	// logged-in user has write permission to the top-level folder.
	// If extending the file, it pads the new data with 0s.  Truncates
	// on an unlinked file may or may not succeed as no-ops, depending
	// on whether or not the necessary blocks have been locally
	// cached.  This is a remote-access operation.
	Truncate(ctx context.Context, file Node, size uint64) error
	// SetEx turns on or off the executable bit on the file
	// represented by a given node, if the logged-in user has write
	// permissions to the top-level folder.  This is a remote-sync
	// operation.
	SetEx(ctx context.Context, file Node, ex bool) error
	// SetMtime sets the modification time on the file represented by
	// a given node, if the logged-in user has write permissions to
	// the top-level folder.  If mtime is nil, it is a noop.  This is
	// a remote-sync operation.
	SetMtime(ctx context.Context, file Node, mtime *time.Time) error
	// SyncAll flushes all outstanding writes and truncates for any
	// dirty files to the KBFS servers within the given folder, if the
	// logged-in user has write permissions to the top-level folder.
	// If done through a file system interface, this may include
	// modifications done via multiple file handles.  This is a
	// remote-sync operation.
	SyncAll(ctx context.Context, folderBranch FolderBranch) error
	// FolderStatus returns the status of a particular folder/branch, along
	// with a channel that will be closed when the status has been
	// updated (to eliminate the need for polling this method).
	FolderStatus(ctx context.Context, folderBranch FolderBranch) (
		FolderBranchStatus, <-chan StatusUpdate, error)
	// Status returns the status of KBFS, along with a channel that will be
	// closed when the status has been updated (to eliminate the need for
	// polling this method). Note that this channel only applies to
	// connection status changes.
	//
	// KBFSStatus can be non-empty even if there is an error.
	Status(ctx context.Context) (
		KBFSStatus, <-chan StatusUpdate, error)
	// UnstageForTesting clears out this device's staged state, if
	// any, and fast-forwards to the current head of this
	// folder-branch.
	UnstageForTesting(ctx context.Context, folderBranch FolderBranch) error
	// RequestRekey requests to rekey this folder. Note that this asynchronously
	// requests a rekey, so canceling ctx doesn't cancel the rekey.
	RequestRekey(ctx context.Context, id tlf.ID)
	// SyncFromServer blocks until the local client has contacted the
	// server and guaranteed that all known updates for the given
	// top-level folder have been applied locally (and notifications
	// sent out to any observers).  It returns an error if this
	// folder-branch is currently unmerged or dirty locally. If
	// lockBeforeGet is non-nil, it blocks on idempotently taking the
	// lock from server at the time it gets any metadata.
	SyncFromServer(ctx context.Context,
		folderBranch FolderBranch, lockBeforeGet *keybase1.LockID) error
	// GetUpdateHistory returns a complete history of all the merged
	// updates of the given folder, in a data structure that's
	// suitable for encoding directly into JSON.  This is an expensive
	// operation, and should only be used for ocassional debugging.
	// Note that the history does not include any unmerged changes or
	// outstanding writes from the local device.
	GetUpdateHistory(ctx context.Context, folderBranch FolderBranch) (
		history TLFUpdateHistory, err error)
	// GetEditHistory returns the edit history of the TLF, clustered
	// by writer.
	GetEditHistory(ctx context.Context, folderBranch FolderBranch) (
		tlfHistory keybase1.FSFolderEditHistory, err error)

	// GetNodeMetadata gets metadata associated with a Node.
	GetNodeMetadata(ctx context.Context, node Node) (NodeMetadata, error)

	// Shutdown is called to clean up any resources associated with
	// this KBFSOps instance.
	Shutdown(ctx context.Context) error
	// PushConnectionStatusChange updates the status of a service for
	// human readable connection status tracking.
	PushConnectionStatusChange(service string, newStatus error)
	// PushStatusChange causes Status listeners to be notified via closing
	// the status channel.
	PushStatusChange()
	// ClearPrivateFolderMD clears any cached private folder metadata,
	// e.g. on a logout.
	ClearPrivateFolderMD(ctx context.Context)
	// ForceFastForward forwards the nodes of all folders that have
	// been previously cleared with `ClearPrivateFolderMD` to their
	// newest version.  It works asynchronously, so no error is
	// returned.
	ForceFastForward(ctx context.Context)
	// InvalidateNodeAndChildren sends invalidation messages for the
	// given node and all of its children that are currently in the
	// NodeCache.  It's useful if the caller has outside knowledge of
	// data changes to that node or its children that didn't come
	// through the usual MD update channels (e.g., autogit nodes need
	// invalidation when the corresponding git repo is updated).
	InvalidateNodeAndChildren(ctx context.Context, node Node) error
	// TeamNameChanged indicates that a team has changed its name, and
	// we should clean up any outstanding handle info associated with
	// the team ID.
	TeamNameChanged(ctx context.Context, tid keybase1.TeamID)
	// TeamAbandoned indicates that a team has been abandoned, and
	// shouldn't be referred to by its previous name anymore.
	TeamAbandoned(ctx context.Context, tid keybase1.TeamID)
	// MigrateToImplicitTeam migrates the given folder from a private-
	// or public-keyed folder, to a team-keyed folder.  If it's
	// already a private/public team-keyed folder, nil is returned.
	MigrateToImplicitTeam(ctx context.Context, id tlf.ID) error
	// KickoffAllOutstandingRekeys kicks off all outstanding rekeys. It does
	// nothing to folders that have not scheduled a rekey. This should be
	// called when we receive an event of "paper key cached" from service.
	KickoffAllOutstandingRekeys() error
	// NewNotificationChannel is called to notify any existing TLF
	// matching `handle` that a new kbfs-edits channel is available.
	NewNotificationChannel(
		ctx context.Context, handle *TlfHandle, convID chat1.ConversationID,
		channelName string)
	// Reset completely resets the given folder.  Should only be
	// called after explicit user confirmation.  After the call,
	// `handle` has the new TLF ID.
	Reset(ctx context.Context, handle *TlfHandle) error

	// GetSyncConfig returns the sync state configuration for the
	// given TLF.
	GetSyncConfig(ctx context.Context, tlfID tlf.ID) (
		keybase1.FolderSyncConfig, error)
	// SetSyncConfig sets the sync state configuration for the given
	// TLF to either fully enabled, fully disabled, or partially
	// syncing selected paths.  If syncing is disabled, it returns a
	// channel that is closed when all of the TLF's blocks have been
	// removed from the sync cache.  For a partially-synced folder,
	// the config must contain no absolute paths, no duplicate paths,
	// and no relative paths that go out of the TLF.
	SetSyncConfig(
		ctx context.Context, tlfID tlf.ID, config keybase1.FolderSyncConfig) (
		<-chan error, error)
}

KBFSOps handles all file system operations. Expands all indirect pointers. Operations that modify the server data change all the block IDs along the path, and so must return a path with the new BlockIds so the caller can update their references.

KBFSOps implementations must guarantee goroutine-safety of calls on a per-top-level-folder basis.

There are two types of operations that could block:

  • remote-sync operations, that need to synchronously update the MD for the corresponding top-level folder. When these operations return successfully, they will have guaranteed to have successfully written the modification to the KBFS servers.
  • remote-access operations, that don't sync any modifications to KBFS servers, but may block on reading data from the servers.

KBFSOps implementations are supposed to give git-like consistency semantics for modification operations; they will be visible to other clients immediately after the remote-sync operations succeed, if and only if there was no other intervening modification to the same folder. If not, the change will be sync'd to the server in a special per-device "unmerged" area before the operation succeeds. In this case, the modification will not be visible to other clients until the KBFS code on this device performs automatic conflict resolution in the background.

All methods take a Context (see https://blog.golang.org/context), and if that context is cancelled during the operation, KBFSOps will abort any blocking calls and return ctx.Err(). Any notifications resulting from an operation will also include this ctx (or a Context derived from it), allowing the caller to determine whether the notification is a result of their own action or an external action.

type KBFSOpsStandard

type KBFSOpsStandard struct {
	// contains filtered or unexported fields
}

KBFSOpsStandard implements the KBFSOps interface, and is go-routine safe by forwarding requests to individual per-folder-branch handlers that are go-routine-safe.

func NewKBFSOpsStandard

func NewKBFSOpsStandard(appStateUpdater env.AppStateUpdater, config Config) *KBFSOpsStandard

NewKBFSOpsStandard constructs a new KBFSOpsStandard object.

func (*KBFSOpsStandard) AddFavorite

func (fs *KBFSOpsStandard) AddFavorite(ctx context.Context,
	fav Favorite) error

AddFavorite implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) ClearCachedFavorites

func (fs *KBFSOpsStandard) ClearCachedFavorites(ctx context.Context)

ClearCachedFavorites implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) ClearPrivateFolderMD

func (fs *KBFSOpsStandard) ClearPrivateFolderMD(ctx context.Context)

ClearPrivateFolderMD implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) CreateDir

func (fs *KBFSOpsStandard) CreateDir(
	ctx context.Context, dir Node, name string) (Node, EntryInfo, error)

CreateDir implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) CreateFile

func (fs *KBFSOpsStandard) CreateFile(
	ctx context.Context, dir Node, name string, isExec bool, excl Excl) (
	Node, EntryInfo, error)

CreateFile implements the KBFSOps interface for KBFSOpsStandard

func (fs *KBFSOpsStandard) CreateLink(
	ctx context.Context, dir Node, fromName string, toPath string) (
	EntryInfo, error)

CreateLink implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) DeleteFavorite

func (fs *KBFSOpsStandard) DeleteFavorite(ctx context.Context,
	fav Favorite) error

DeleteFavorite implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) FolderStatus

func (fs *KBFSOpsStandard) FolderStatus(
	ctx context.Context, folderBranch FolderBranch) (
	FolderBranchStatus, <-chan StatusUpdate, error)

FolderStatus implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) ForceFastForward

func (fs *KBFSOpsStandard) ForceFastForward(ctx context.Context)

ForceFastForward implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) GetDirChildren

func (fs *KBFSOpsStandard) GetDirChildren(ctx context.Context, dir Node) (
	map[string]EntryInfo, error)

GetDirChildren implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) GetEditHistory

func (fs *KBFSOpsStandard) GetEditHistory(
	ctx context.Context, folderBranch FolderBranch) (
	tlfHistory keybase1.FSFolderEditHistory, err error)

GetEditHistory implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) GetFavorites

func (fs *KBFSOpsStandard) GetFavorites(ctx context.Context) (
	[]Favorite, error)

GetFavorites implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) GetNodeMetadata

func (fs *KBFSOpsStandard) GetNodeMetadata(ctx context.Context, node Node) (
	NodeMetadata, error)

GetNodeMetadata implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) GetOrCreateRootNode

func (fs *KBFSOpsStandard) GetOrCreateRootNode(
	ctx context.Context, h *TlfHandle, branch BranchName) (
	node Node, ei EntryInfo, err error)

GetOrCreateRootNode implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) GetRootNode

func (fs *KBFSOpsStandard) GetRootNode(
	ctx context.Context, h *TlfHandle, branch BranchName) (
	node Node, ei EntryInfo, err error)

GetRootNode implements the KBFSOps interface for KBFSOpsStandard. Returns a nil Node and nil error if the tlf does not exist but there is no error present.

func (*KBFSOpsStandard) GetSyncConfig

func (fs *KBFSOpsStandard) GetSyncConfig(
	ctx context.Context, tlfID tlf.ID) (keybase1.FolderSyncConfig, error)

GetSyncConfig implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) GetTLFCryptKeys

func (fs *KBFSOpsStandard) GetTLFCryptKeys(
	ctx context.Context, tlfHandle *TlfHandle) (
	keys []kbfscrypto.TLFCryptKey, id tlf.ID, err error)

GetTLFCryptKeys implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) GetTLFHandle

func (fs *KBFSOpsStandard) GetTLFHandle(ctx context.Context, node Node) (
	*TlfHandle, error)

GetTLFHandle implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) GetTLFID

func (fs *KBFSOpsStandard) GetTLFID(ctx context.Context,
	tlfHandle *TlfHandle) (id tlf.ID, err error)

GetTLFID implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) GetUpdateHistory

func (fs *KBFSOpsStandard) GetUpdateHistory(ctx context.Context,
	folderBranch FolderBranch) (history TLFUpdateHistory, err error)

GetUpdateHistory implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) InvalidateNodeAndChildren

func (fs *KBFSOpsStandard) InvalidateNodeAndChildren(
	ctx context.Context, node Node) error

InvalidateNodeAndChildren implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) KickoffAllOutstandingRekeys

func (fs *KBFSOpsStandard) KickoffAllOutstandingRekeys() error

KickoffAllOutstandingRekeys implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) Lookup

func (fs *KBFSOpsStandard) Lookup(ctx context.Context, dir Node, name string) (
	Node, EntryInfo, error)

Lookup implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) MigrateToImplicitTeam

func (fs *KBFSOpsStandard) MigrateToImplicitTeam(
	ctx context.Context, id tlf.ID) error

MigrateToImplicitTeam implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) NewNotificationChannel

func (fs *KBFSOpsStandard) NewNotificationChannel(
	ctx context.Context, handle *TlfHandle, convID chat1.ConversationID,
	channelName string)

NewNotificationChannel implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) PushConnectionStatusChange

func (fs *KBFSOpsStandard) PushConnectionStatusChange(
	service string, newStatus error)

PushConnectionStatusChange pushes human readable connection status changes.

func (*KBFSOpsStandard) PushStatusChange

func (fs *KBFSOpsStandard) PushStatusChange()

PushStatusChange forces a new status be fetched by status listeners.

func (*KBFSOpsStandard) Read

func (fs *KBFSOpsStandard) Read(
	ctx context.Context, file Node, dest []byte, off int64) (
	numRead int64, err error)

Read implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) RefreshCachedFavorites

func (fs *KBFSOpsStandard) RefreshCachedFavorites(ctx context.Context)

RefreshCachedFavorites implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) RefreshEditHistory

func (fs *KBFSOpsStandard) RefreshEditHistory(fav Favorite)

RefreshEditHistory implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) RegisterForChanges

func (fs *KBFSOpsStandard) RegisterForChanges(
	folderBranches []FolderBranch, obs Observer) error

RegisterForChanges implements the Notifer interface for KBFSOpsStandard

func (*KBFSOpsStandard) RemoveDir

func (fs *KBFSOpsStandard) RemoveDir(
	ctx context.Context, dir Node, name string) error

RemoveDir implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) RemoveEntry

func (fs *KBFSOpsStandard) RemoveEntry(
	ctx context.Context, dir Node, name string) error

RemoveEntry implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) Rename

func (fs *KBFSOpsStandard) Rename(
	ctx context.Context, oldParent Node, oldName string, newParent Node,
	newName string) error

Rename implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) RequestRekey

func (fs *KBFSOpsStandard) RequestRekey(ctx context.Context, id tlf.ID)

RequestRekey implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) Reset

func (fs *KBFSOpsStandard) Reset(
	ctx context.Context, handle *TlfHandle) error

Reset implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) SetEx

func (fs *KBFSOpsStandard) SetEx(
	ctx context.Context, file Node, ex bool) error

SetEx implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) SetMtime

func (fs *KBFSOpsStandard) SetMtime(
	ctx context.Context, file Node, mtime *time.Time) error

SetMtime implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) SetSyncConfig

func (fs *KBFSOpsStandard) SetSyncConfig(
	ctx context.Context, tlfID tlf.ID,
	config keybase1.FolderSyncConfig) (<-chan error, error)

SetSyncConfig implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) Shutdown

func (fs *KBFSOpsStandard) Shutdown(ctx context.Context) error

Shutdown safely shuts down any background goroutines that may have been launched by KBFSOpsStandard.

func (*KBFSOpsStandard) Stat

func (fs *KBFSOpsStandard) Stat(ctx context.Context, node Node) (
	EntryInfo, error)

Stat implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) Status

func (fs *KBFSOpsStandard) Status(ctx context.Context) (
	KBFSStatus, <-chan StatusUpdate, error)

Status implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) SyncAll

func (fs *KBFSOpsStandard) SyncAll(
	ctx context.Context, folderBranch FolderBranch) error

SyncAll implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) SyncFromServer

func (fs *KBFSOpsStandard) SyncFromServer(ctx context.Context,
	folderBranch FolderBranch, lockBeforeGet *keybase1.LockID) error

SyncFromServer implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) TeamAbandoned

func (fs *KBFSOpsStandard) TeamAbandoned(
	ctx context.Context, tid keybase1.TeamID)

TeamAbandoned implements the KBFSOps interface for KBFSOpsStandard.

func (*KBFSOpsStandard) TeamNameChanged

func (fs *KBFSOpsStandard) TeamNameChanged(
	ctx context.Context, tid keybase1.TeamID)

TeamNameChanged implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) Truncate

func (fs *KBFSOpsStandard) Truncate(
	ctx context.Context, file Node, size uint64) error

Truncate implements the KBFSOps interface for KBFSOpsStandard

func (*KBFSOpsStandard) UnregisterFromChanges

func (fs *KBFSOpsStandard) UnregisterFromChanges(
	folderBranches []FolderBranch, obs Observer) error

UnregisterFromChanges implements the Notifer interface for KBFSOpsStandard

func (*KBFSOpsStandard) UnstageForTesting

func (fs *KBFSOpsStandard) UnstageForTesting(
	ctx context.Context, folderBranch FolderBranch) error

UnstageForTesting implements the KBFSOps interface for KBFSOpsStandard TODO: remove once we have automatic conflict resolution

func (*KBFSOpsStandard) Write

func (fs *KBFSOpsStandard) Write(
	ctx context.Context, file Node, data []byte, off int64) error

Write implements the KBFSOps interface for KBFSOpsStandard

type KBFSService

type KBFSService struct {
	// contains filtered or unexported fields
}

KBFSService represents a running KBFS service.

func NewKBFSService

func NewKBFSService(kbCtx Context, config kbfsServiceConfig) (
	*KBFSService, error)

NewKBFSService creates a new KBFSService.

func (*KBFSService) Run

func (k *KBFSService) Run(l net.Listener)

Run starts listening on the passed-in listener.

func (*KBFSService) Shutdown

func (k *KBFSService) Shutdown()

Shutdown shuts down this KBFSService.

type KBFSStatus

type KBFSStatus struct {
	CurrentUser          string
	IsConnected          bool
	UsageBytes           int64
	ArchiveBytes         int64
	LimitBytes           int64
	GitUsageBytes        int64
	GitArchiveBytes      int64
	GitLimitBytes        int64
	FailingServices      map[string]error
	JournalServer        *JournalServerStatus            `json:",omitempty"`
	DiskBlockCacheStatus map[string]DiskBlockCacheStatus `json:",omitempty"`
	DiskMDCacheStatus    DiskMDCacheStatus               `json:",omitempty"`
	DiskQuotaCacheStatus DiskQuotaCacheStatus            `json:",omitempty"`
}

KBFSStatus represents the content of the top-level status file. It is suitable for encoding directly as JSON. TODO: implement magical status update like FolderBranchStatus

type KBPKI

type KBPKI interface {
	CurrentSessionGetter

	// HasVerifyingKey returns nil if the given user has the given
	// VerifyingKey, and an error otherwise.  If the revoked key was
	// valid according to the untrusted server timestamps, a special
	// error type `RevokedDeviceVerificationError` is returned, which
	// includes information the caller can use to verify the key using
	// the merkle tree.
	HasVerifyingKey(ctx context.Context, uid keybase1.UID,
		verifyingKey kbfscrypto.VerifyingKey,
		atServerTime time.Time) error

	// GetCryptPublicKeys gets all of a user's crypt public keys (including
	// paper keys).
	GetCryptPublicKeys(ctx context.Context, uid keybase1.UID) (
		[]kbfscrypto.CryptPublicKey, error)

	// FavoriteAdd adds folder to the list of the logged in user's
	// favorite folders.  It is idempotent.
	FavoriteAdd(ctx context.Context, folder keybase1.Folder) error

	// FavoriteDelete deletes folder from the list of the logged in user's
	// favorite folders.  It is idempotent.
	FavoriteDelete(ctx context.Context, folder keybase1.Folder) error

	// FavoriteList returns the list of all favorite folders for
	// the logged in user.
	FavoriteList(ctx context.Context) ([]keybase1.Folder, error)

	// CreateTeamTLF associates the given TLF ID with the team ID in
	// the team's sigchain.  If the team already has a TLF ID
	// associated with it, this overwrites it.
	CreateTeamTLF(
		ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) error

	// Notify sends a filesystem notification.
	Notify(ctx context.Context, notification *keybase1.FSNotification) error

	// NotifyPathUpdated sends a path updated notification.
	NotifyPathUpdated(ctx context.Context, path string) error
	// contains filtered or unexported methods
}

KBPKI interacts with the Keybase daemon to fetch user info.

type KBPKIClient

type KBPKIClient struct {
	// contains filtered or unexported fields
}

KBPKIClient uses a KeybaseService.

func NewKBPKIClient

func NewKBPKIClient(
	serviceOwner keybaseServiceOwner, log logger.Logger) *KBPKIClient

NewKBPKIClient returns a new KBPKIClient with the given service.

func (*KBPKIClient) CreateTeamTLF

func (k *KBPKIClient) CreateTeamTLF(
	ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) error

CreateTeamTLF implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) FavoriteAdd

func (k *KBPKIClient) FavoriteAdd(ctx context.Context, folder keybase1.Folder) error

FavoriteAdd implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) FavoriteDelete

func (k *KBPKIClient) FavoriteDelete(ctx context.Context, folder keybase1.Folder) error

FavoriteDelete implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) FavoriteList

func (k *KBPKIClient) FavoriteList(ctx context.Context) ([]keybase1.Folder, error)

FavoriteList implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) GetCryptPublicKeys

func (k *KBPKIClient) GetCryptPublicKeys(ctx context.Context,
	uid keybase1.UID) (keys []kbfscrypto.CryptPublicKey, err error)

GetCryptPublicKeys implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) GetCurrentMerkleRoot

func (k *KBPKIClient) GetCurrentMerkleRoot(ctx context.Context) (
	keybase1.MerkleRootV2, time.Time, error)

GetCurrentMerkleRoot implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) GetCurrentSession

func (k *KBPKIClient) GetCurrentSession(ctx context.Context) (
	SessionInfo, error)

GetCurrentSession implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) GetNormalizedUsername

func (k *KBPKIClient) GetNormalizedUsername(
	ctx context.Context, id keybase1.UserOrTeamID) (
	kbname.NormalizedUsername, error)

GetNormalizedUsername implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) GetTeamRootID

func (k *KBPKIClient) GetTeamRootID(ctx context.Context, tid keybase1.TeamID) (
	keybase1.TeamID, error)

GetTeamRootID implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) GetTeamTLFCryptKeys

func (k *KBPKIClient) GetTeamTLFCryptKeys(
	ctx context.Context, tid keybase1.TeamID, desiredKeyGen kbfsmd.KeyGen) (
	map[kbfsmd.KeyGen]kbfscrypto.TLFCryptKey, kbfsmd.KeyGen, error)

GetTeamTLFCryptKeys implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) HasVerifyingKey

func (k *KBPKIClient) HasVerifyingKey(ctx context.Context, uid keybase1.UID,
	verifyingKey kbfscrypto.VerifyingKey, atServerTime time.Time) error

HasVerifyingKey implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) Identify

func (k *KBPKIClient) Identify(ctx context.Context, assertion, reason string) (
	kbname.NormalizedUsername, keybase1.UserOrTeamID, error)

Identify implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) IdentifyImplicitTeam

func (k *KBPKIClient) IdentifyImplicitTeam(
	ctx context.Context, assertions, suffix string, tlfType tlf.Type,
	reason string) (ImplicitTeamInfo, error)

IdentifyImplicitTeam identifies (and creates if necessary) the given implicit team.

func (*KBPKIClient) IsTeamReader

func (k *KBPKIClient) IsTeamReader(
	ctx context.Context, tid keybase1.TeamID, uid keybase1.UID) (bool, error)

IsTeamReader implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) IsTeamWriter

func (k *KBPKIClient) IsTeamWriter(
	ctx context.Context, tid keybase1.TeamID, uid keybase1.UID,
	verifyingKey kbfscrypto.VerifyingKey) (bool, error)

IsTeamWriter implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) NoLongerTeamWriter

func (k *KBPKIClient) NoLongerTeamWriter(
	ctx context.Context, tid keybase1.TeamID, tlfType tlf.Type,
	uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey) (
	keybase1.MerkleRootV2, error)

NoLongerTeamWriter implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) NormalizeSocialAssertion

func (k *KBPKIClient) NormalizeSocialAssertion(
	ctx context.Context, assertion string) (keybase1.SocialAssertion, error)

NormalizeSocialAssertion implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) Notify

func (k *KBPKIClient) Notify(ctx context.Context, notification *keybase1.FSNotification) error

Notify implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) NotifyPathUpdated

func (k *KBPKIClient) NotifyPathUpdated(
	ctx context.Context, path string) error

NotifyPathUpdated implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) PutGitMetadata

func (k *KBPKIClient) PutGitMetadata(
	ctx context.Context, folder keybase1.Folder, repoID keybase1.RepoID,
	metadata keybase1.GitLocalMetadata) error

PutGitMetadata implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) Resolve

Resolve implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) ResolveImplicitTeam

func (k *KBPKIClient) ResolveImplicitTeam(
	ctx context.Context, assertions, suffix string, tlfType tlf.Type) (
	ImplicitTeamInfo, error)

ResolveImplicitTeam implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) ResolveImplicitTeamByID

func (k *KBPKIClient) ResolveImplicitTeamByID(
	ctx context.Context, teamID keybase1.TeamID, tlfType tlf.Type) (
	ImplicitTeamInfo, error)

ResolveImplicitTeamByID implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) ResolveTeamTLFID

func (k *KBPKIClient) ResolveTeamTLFID(
	ctx context.Context, teamID keybase1.TeamID) (tlf.ID, error)

ResolveTeamTLFID implements the KBPKI interface for KBPKIClient.

func (*KBPKIClient) VerifyMerkleRoot

func (k *KBPKIClient) VerifyMerkleRoot(
	ctx context.Context, root keybase1.MerkleRootV2,
	kbfsRoot keybase1.KBFSRoot) error

VerifyMerkleRoot implements the KBPKI interface for KBPKIClient.

type KeyBundleCacheMeasured

type KeyBundleCacheMeasured struct {
	// contains filtered or unexported fields
}

KeyBundleCacheMeasured delegates to another KeyBundleCache instance but also keeps track of stats.

func NewKeyBundleCacheMeasured

func NewKeyBundleCacheMeasured(delegate kbfsmd.KeyBundleCache, r metrics.Registry) KeyBundleCacheMeasured

NewKeyBundleCacheMeasured creates and returns a new KeyBundleCacheMeasured instance with the given delegate and registry.

func (KeyBundleCacheMeasured) GetTLFReaderKeyBundle

func (b KeyBundleCacheMeasured) GetTLFReaderKeyBundle(
	bundleID kbfsmd.TLFReaderKeyBundleID) (rkb *kbfsmd.TLFReaderKeyBundleV3, err error)

GetTLFReaderKeyBundle implements the KeyBundleCache interface for KeyBundleCacheMeasured.

func (KeyBundleCacheMeasured) GetTLFWriterKeyBundle

func (b KeyBundleCacheMeasured) GetTLFWriterKeyBundle(
	bundleID kbfsmd.TLFWriterKeyBundleID) (wkb *kbfsmd.TLFWriterKeyBundleV3, err error)

GetTLFWriterKeyBundle implements the KeyBundleCache interface for KeyBundleCacheMeasured.

func (KeyBundleCacheMeasured) PutTLFReaderKeyBundle

func (b KeyBundleCacheMeasured) PutTLFReaderKeyBundle(
	bundleID kbfsmd.TLFReaderKeyBundleID, rkb kbfsmd.TLFReaderKeyBundleV3)

PutTLFReaderKeyBundle implements the KeyBundleCache interface for KeyBundleCacheMeasured.

func (KeyBundleCacheMeasured) PutTLFWriterKeyBundle

func (b KeyBundleCacheMeasured) PutTLFWriterKeyBundle(
	bundleID kbfsmd.TLFWriterKeyBundleID, wkb kbfsmd.TLFWriterKeyBundleV3)

PutTLFWriterKeyBundle implements the KeyBundleCache interface for KeyBundleCacheMeasured.

type KeyCache

type KeyCache interface {
	// GetTLFCryptKey gets the crypt key for the given TLF.
	GetTLFCryptKey(tlf.ID, kbfsmd.KeyGen) (kbfscrypto.TLFCryptKey, error)
	// PutTLFCryptKey stores the crypt key for the given TLF.
	PutTLFCryptKey(tlf.ID, kbfsmd.KeyGen, kbfscrypto.TLFCryptKey) error
}

KeyCache handles caching for both TLFCryptKeys and BlockCryptKeys.

type KeyCacheHitError

type KeyCacheHitError struct {
	// contains filtered or unexported fields
}

KeyCacheHitError indicates that a key matching the given TLF ID and key generation was found in cache but the object type was unknown.

func (KeyCacheHitError) Error

func (e KeyCacheHitError) Error() string

Error implements the error interface for KeyCacheHitError.

type KeyCacheMeasured

type KeyCacheMeasured struct {
	// contains filtered or unexported fields
}

KeyCacheMeasured delegates to another KeyCache instance but also keeps track of stats.

func NewKeyCacheMeasured

func NewKeyCacheMeasured(delegate KeyCache, r metrics.Registry) KeyCacheMeasured

NewKeyCacheMeasured creates and returns a new KeyCacheMeasured instance with the given delegate and registry.

func (KeyCacheMeasured) GetTLFCryptKey

func (b KeyCacheMeasured) GetTLFCryptKey(
	tlfID tlf.ID, keyGen kbfsmd.KeyGen) (key kbfscrypto.TLFCryptKey, err error)

GetTLFCryptKey implements the KeyCache interface for KeyCacheMeasured.

func (KeyCacheMeasured) PutTLFCryptKey

func (b KeyCacheMeasured) PutTLFCryptKey(
	tlfID tlf.ID, keyGen kbfsmd.KeyGen, key kbfscrypto.TLFCryptKey) (err error)

PutTLFCryptKey implements the KeyCache interface for KeyCacheMeasured.

type KeyCacheMissError

type KeyCacheMissError struct {
	// contains filtered or unexported fields
}

KeyCacheMissError indicates that a key matching the given TLF ID and key generation wasn't found in cache.

func (KeyCacheMissError) Error

func (e KeyCacheMissError) Error() string

Error implements the error interface for KeyCacheMissError.

type KeyCacheStandard

type KeyCacheStandard struct {
	// contains filtered or unexported fields
}

KeyCacheStandard is an LRU-based implementation of the KeyCache interface.

func NewKeyCacheStandard

func NewKeyCacheStandard(capacity int) *KeyCacheStandard

NewKeyCacheStandard constructs a new KeyCacheStandard with the given cache capacity.

func (*KeyCacheStandard) GetTLFCryptKey

func (k *KeyCacheStandard) GetTLFCryptKey(tlf tlf.ID, keyGen kbfsmd.KeyGen) (
	kbfscrypto.TLFCryptKey, error)

GetTLFCryptKey implements the KeyCache interface for KeyCacheStandard.

func (*KeyCacheStandard) PutTLFCryptKey

func (k *KeyCacheStandard) PutTLFCryptKey(
	tlf tlf.ID, keyGen kbfsmd.KeyGen, key kbfscrypto.TLFCryptKey) error

PutTLFCryptKey implements the KeyCache interface for KeyCacheStandard.

type KeyHalfMismatchError

type KeyHalfMismatchError struct {
	Expected kbfscrypto.TLFCryptKeyServerHalfID
	Actual   kbfscrypto.TLFCryptKeyServerHalfID
}

KeyHalfMismatchError is returned when the key server doesn't return the expected key half.

func (KeyHalfMismatchError) Error

func (e KeyHalfMismatchError) Error() string

Error implements the error interface for KeyHalfMismatchError.

type KeyManager

type KeyManager interface {

	// GetTLFCryptKeyOfAllGenerations gets the crypt keys of all generations
	// for current devices. keys contains crypt keys from all generations, in
	// order, starting from FirstValidKeyGen.
	GetTLFCryptKeyOfAllGenerations(ctx context.Context, kmd KeyMetadata) (
		keys []kbfscrypto.TLFCryptKey, err error)

	// Rekey checks the given MD object, if it is a private TLF,
	// against the current set of device keys for all valid
	// readers and writers.  If there are any new devices, it
	// updates all existing key generations to include the new
	// devices.  If there are devices that have been removed, it
	// creates a new epoch of keys for the TLF.  If there was an
	// error, or the RootMetadata wasn't changed, it returns false.
	// Otherwise, it returns true. If a new key generation is
	// added the second return value points to this new key. This
	// is to allow for caching of the TLF crypt key only after a
	// successful merged write of the metadata. Otherwise we could
	// prematurely pollute the key cache.
	//
	// If the given MD object is a public TLF, it simply updates
	// the TLF's handle with any newly-resolved writers.
	//
	// If promptPaper is set, prompts for any unlocked paper keys.
	// promptPaper shouldn't be set if md is for a public TLF.
	Rekey(ctx context.Context, md *RootMetadata, promptPaper bool) (
		bool, *kbfscrypto.TLFCryptKey, error)
	// contains filtered or unexported methods
}

KeyManager fetches and constructs the keys needed for KBFS file operations.

type KeyManagerStandard

type KeyManagerStandard struct {
	// contains filtered or unexported fields
}

KeyManagerStandard implements the KeyManager interface by fetching keys from KeyOps and KBPKI, and computing the complete keys necessary to run KBFS.

func NewKeyManagerStandard

func NewKeyManagerStandard(config Config) *KeyManagerStandard

NewKeyManagerStandard returns a new KeyManagerStandard

func (*KeyManagerStandard) GetTLFCryptKeyForBlockDecryption

func (km *KeyManagerStandard) GetTLFCryptKeyForBlockDecryption(
	ctx context.Context, kmd KeyMetadata, blockPtr BlockPointer) (
	tlfCryptKey kbfscrypto.TLFCryptKey, err error)

GetTLFCryptKeyForBlockDecryption implements the KeyManager interface for KeyManagerStandard.

func (*KeyManagerStandard) GetTLFCryptKeyForEncryption

func (km *KeyManagerStandard) GetTLFCryptKeyForEncryption(ctx context.Context,
	kmd KeyMetadata) (tlfCryptKey kbfscrypto.TLFCryptKey, err error)

GetTLFCryptKeyForEncryption implements the KeyManager interface for KeyManagerStandard.

func (*KeyManagerStandard) GetTLFCryptKeyForMDDecryption

func (km *KeyManagerStandard) GetTLFCryptKeyForMDDecryption(
	ctx context.Context, kmdToDecrypt, kmdWithKeys KeyMetadata) (
	tlfCryptKey kbfscrypto.TLFCryptKey, err error)

GetTLFCryptKeyForMDDecryption implements the KeyManager interface for KeyManagerStandard.

func (*KeyManagerStandard) GetTLFCryptKeyOfAllGenerations

func (km *KeyManagerStandard) GetTLFCryptKeyOfAllGenerations(
	ctx context.Context, kmd KeyMetadata) (
	keys []kbfscrypto.TLFCryptKey, err error)

GetTLFCryptKeyOfAllGenerations implements the KeyManager interface for KeyManagerStandard.

func (*KeyManagerStandard) Rekey

func (km *KeyManagerStandard) Rekey(ctx context.Context, md *RootMetadata, promptPaper bool) (
	mdChanged bool, cryptKey *kbfscrypto.TLFCryptKey, err error)

Rekey implements the KeyManager interface for KeyManagerStandard.

TODO: Make this less terrible. See KBFS-1799.

type KeyMetadata

type KeyMetadata interface {
	// TlfID returns the ID of the TLF for which this object holds
	// key info.
	TlfID() tlf.ID

	// TypeForKeying returns the keying type for this MD.
	TypeForKeying() tlf.KeyingType

	// LatestKeyGeneration returns the most recent key generation
	// with key data in this object, or PublicKeyGen if this TLF
	// is public.
	LatestKeyGeneration() kbfsmd.KeyGen

	// GetTlfHandle returns the handle for the TLF. It must not
	// return nil.
	//
	// TODO: Remove the need for this function in this interface,
	// so that kbfsmd.RootMetadata can implement this interface
	// fully.
	GetTlfHandle() *TlfHandle

	// IsWriter checks that the given user is a valid writer of the TLF
	// right now.
	IsWriter(
		ctx context.Context, checker kbfsmd.TeamMembershipChecker,
		uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey) (
		bool, error)

	// HasKeyForUser returns whether or not the given user has
	// keys for at least one device. Returns an error if the TLF
	// is public.
	HasKeyForUser(user keybase1.UID) (bool, error)

	// GetTLFCryptKeyParams returns all the necessary info to
	// construct the TLF crypt key for the given key generation,
	// user, and device (identified by its crypt public key), or
	// false if not found. This returns an error if the TLF is
	// public.
	GetTLFCryptKeyParams(
		keyGen kbfsmd.KeyGen, user keybase1.UID,
		key kbfscrypto.CryptPublicKey) (
		kbfscrypto.TLFEphemeralPublicKey,
		kbfscrypto.EncryptedTLFCryptKeyClientHalf,
		kbfscrypto.TLFCryptKeyServerHalfID, bool, error)

	// StoresHistoricTLFCryptKeys returns whether or not history keys are
	// symmetrically encrypted; if not, they're encrypted per-device.
	StoresHistoricTLFCryptKeys() bool

	// GetHistoricTLFCryptKey attempts to symmetrically decrypt the key at the given
	// generation using the current generation's TLFCryptKey.
	GetHistoricTLFCryptKey(codec kbfscodec.Codec, keyGen kbfsmd.KeyGen,
		currentKey kbfscrypto.TLFCryptKey) (
		kbfscrypto.TLFCryptKey, error)
}

KeyMetadata is an interface for something that holds key information. This is usually implemented by RootMetadata.

type KeyMetadataWithRootDirEntry

type KeyMetadataWithRootDirEntry interface {
	KeyMetadata

	// GetRootDirEntry returns the root directory entry for the
	// associated MD.
	GetRootDirEntry() DirEntry
}

KeyMetadataWithRootDirEntry is like KeyMetadata, but can also return the root dir entry for the associated MD update.

type KeyOps

type KeyOps interface {
	// GetTLFCryptKeyServerHalf gets a server-side key half for a
	// device given the key half ID.
	GetTLFCryptKeyServerHalf(ctx context.Context,
		serverHalfID kbfscrypto.TLFCryptKeyServerHalfID,
		cryptPublicKey kbfscrypto.CryptPublicKey) (
		kbfscrypto.TLFCryptKeyServerHalf, error)

	// PutTLFCryptKeyServerHalves stores a server-side key halves for a
	// set of users and devices.
	PutTLFCryptKeyServerHalves(ctx context.Context,
		keyServerHalves kbfsmd.UserDeviceKeyServerHalves) error

	// DeleteTLFCryptKeyServerHalf deletes a server-side key half for a
	// device given the key half ID.
	DeleteTLFCryptKeyServerHalf(ctx context.Context,
		uid keybase1.UID, key kbfscrypto.CryptPublicKey,
		serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) error
}

KeyOps fetches server-side key halves from the key server.

type KeyOpsStandard

type KeyOpsStandard struct {
	// contains filtered or unexported fields
}

KeyOpsStandard implements the KeyOps interface and relays get/put requests for server-side key halves from/to the key server.

func (*KeyOpsStandard) DeleteTLFCryptKeyServerHalf

func (k *KeyOpsStandard) DeleteTLFCryptKeyServerHalf(ctx context.Context,
	uid keybase1.UID, key kbfscrypto.CryptPublicKey,
	serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) error

DeleteTLFCryptKeyServerHalf is an implementation of the KeyOps interface.

func (*KeyOpsStandard) GetTLFCryptKeyServerHalf

GetTLFCryptKeyServerHalf is an implementation of the KeyOps interface.

func (*KeyOpsStandard) PutTLFCryptKeyServerHalves

func (k *KeyOpsStandard) PutTLFCryptKeyServerHalves(ctx context.Context,
	keyServerHalves kbfsmd.UserDeviceKeyServerHalves) error

PutTLFCryptKeyServerHalves is an implementation of the KeyOps interface.

type KeyServer

type KeyServer interface {
	// GetTLFCryptKeyServerHalf gets a server-side key half for a
	// device given the key half ID.
	GetTLFCryptKeyServerHalf(ctx context.Context,
		serverHalfID kbfscrypto.TLFCryptKeyServerHalfID,
		cryptPublicKey kbfscrypto.CryptPublicKey) (
		kbfscrypto.TLFCryptKeyServerHalf, error)

	// PutTLFCryptKeyServerHalves stores a server-side key halves for a
	// set of users and devices.
	PutTLFCryptKeyServerHalves(ctx context.Context,
		keyServerHalves kbfsmd.UserDeviceKeyServerHalves) error

	// DeleteTLFCryptKeyServerHalf deletes a server-side key half for a
	// device given the key half ID.
	DeleteTLFCryptKeyServerHalf(ctx context.Context,
		uid keybase1.UID, key kbfscrypto.CryptPublicKey,
		serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) error

	// Shutdown is called to free any KeyServer resources.
	Shutdown()
}

KeyServer fetches/writes server-side key halves from/to the key server.

type KeyServerLocal

type KeyServerLocal struct {
	// contains filtered or unexported fields
}

KeyServerLocal puts/gets key server halves in/from a local leveldb instance.

func NewKeyServerDir

func NewKeyServerDir(config Config, dirPath string) (*KeyServerLocal, error)

NewKeyServerDir constructs a new KeyServerLocal that stores its data in the given directory.

func NewKeyServerMemory

func NewKeyServerMemory(config Config) (*KeyServerLocal, error)

NewKeyServerMemory returns a KeyServerLocal with an in-memory leveldb instance.

func NewKeyServerTempDir

func NewKeyServerTempDir(config Config) (*KeyServerLocal, error)

NewKeyServerTempDir constructs a new KeyServerLocal that stores its data in a temp directory which is cleaned up on shutdown.

func (*KeyServerLocal) DeleteTLFCryptKeyServerHalf

func (ks *KeyServerLocal) DeleteTLFCryptKeyServerHalf(ctx context.Context,
	_ keybase1.UID, _ kbfscrypto.CryptPublicKey,
	serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) error

DeleteTLFCryptKeyServerHalf implements the KeyOps interface for KeyServerLocal.

func (*KeyServerLocal) GetTLFCryptKeyServerHalf

func (ks *KeyServerLocal) GetTLFCryptKeyServerHalf(ctx context.Context,
	serverHalfID kbfscrypto.TLFCryptKeyServerHalfID, key kbfscrypto.CryptPublicKey) (
	serverHalf kbfscrypto.TLFCryptKeyServerHalf, err error)

GetTLFCryptKeyServerHalf implements the KeyServer interface for KeyServerLocal.

func (*KeyServerLocal) PutTLFCryptKeyServerHalves

func (ks *KeyServerLocal) PutTLFCryptKeyServerHalves(ctx context.Context,
	keyServerHalves kbfsmd.UserDeviceKeyServerHalves) error

PutTLFCryptKeyServerHalves implements the KeyOps interface for KeyServerLocal.

func (*KeyServerLocal) Shutdown

func (ks *KeyServerLocal) Shutdown()

Shutdown implements the KeyServer interface for KeyServerLocal.

type KeyServerMeasured

type KeyServerMeasured struct {
	// contains filtered or unexported fields
}

KeyServerMeasured delegates to another KeyServer instance but also keeps track of stats.

func NewKeyServerMeasured

func NewKeyServerMeasured(delegate KeyServer, r metrics.Registry) KeyServerMeasured

NewKeyServerMeasured creates and returns a new KeyServerMeasured instance with the given delegate and registry.

func (KeyServerMeasured) DeleteTLFCryptKeyServerHalf

func (b KeyServerMeasured) DeleteTLFCryptKeyServerHalf(ctx context.Context,
	uid keybase1.UID, key kbfscrypto.CryptPublicKey,
	serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) (err error)

DeleteTLFCryptKeyServerHalf implements the KeyServer interface for KeyServerMeasured.

func (KeyServerMeasured) GetTLFCryptKeyServerHalf

func (b KeyServerMeasured) GetTLFCryptKeyServerHalf(ctx context.Context,
	serverHalfID kbfscrypto.TLFCryptKeyServerHalfID, key kbfscrypto.CryptPublicKey) (
	serverHalf kbfscrypto.TLFCryptKeyServerHalf, err error)

GetTLFCryptKeyServerHalf implements the KeyServer interface for KeyServerMeasured.

func (KeyServerMeasured) PutTLFCryptKeyServerHalves

func (b KeyServerMeasured) PutTLFCryptKeyServerHalves(ctx context.Context,
	keyServerHalves kbfsmd.UserDeviceKeyServerHalves) (err error)

PutTLFCryptKeyServerHalves implements the KeyServer interface for KeyServerMeasured.

func (KeyServerMeasured) Shutdown

func (b KeyServerMeasured) Shutdown()

Shutdown implements the KeyServer interface for KeyServerMeasured.

type KeybaseDaemonLocal

type KeybaseDaemonLocal struct {
	// contains filtered or unexported fields
}

KeybaseDaemonLocal implements KeybaseDaemon using an in-memory user and session store, and a given favorite store.

func NewKeybaseDaemonDisk

func NewKeybaseDaemonDisk(currentUID keybase1.UID, users []LocalUser,
	teams []TeamInfo, favDBFile string, codec kbfscodec.Codec) (
	*KeybaseDaemonLocal, error)

NewKeybaseDaemonDisk constructs a KeybaseDaemonLocal object given a set of possible users, and one user that should be "logged in". Any storage (e.g. the favorites) persists to disk.

func NewKeybaseDaemonMemory

func NewKeybaseDaemonMemory(currentUID keybase1.UID,
	users []LocalUser, teams []TeamInfo,
	codec kbfscodec.Codec) *KeybaseDaemonLocal

NewKeybaseDaemonMemory constructs a KeybaseDaemonLocal object given a set of possible users, and one user that should be "logged in". Any storage (e.g. the favorites) is kept in memory only.

func (*KeybaseDaemonLocal) CreateTeamTLF

func (k *KeybaseDaemonLocal) CreateTeamTLF(
	ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) (err error)

CreateTeamTLF implements the KBPKI interface for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) CurrentSession

func (k *KeybaseDaemonLocal) CurrentSession(ctx context.Context, sessionID int) (
	SessionInfo, error)

CurrentSession implements KeybaseDaemon for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) DecryptFavorites

func (k *KeybaseDaemonLocal) DecryptFavorites(ctx context.Context,
	dataToDecrypt []byte) ([]byte, error)

DecryptFavorites implements KeybaseService for KeybaseDaemonLocal

func (*KeybaseDaemonLocal) EncryptFavorites

func (k *KeybaseDaemonLocal) EncryptFavorites(ctx context.Context,
	dataToEncrypt []byte) ([]byte, error)

EncryptFavorites implements KeybaseService for KeybaseDaemonLocal

func (*KeybaseDaemonLocal) EstablishMountDir

func (k *KeybaseDaemonLocal) EstablishMountDir(ctx context.Context) (string, error)

EstablishMountDir implements the KeybaseDaemon interface for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) FavoriteAdd

func (k *KeybaseDaemonLocal) FavoriteAdd(
	ctx context.Context, folder keybase1.Folder) error

FavoriteAdd implements KeybaseDaemon for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) FavoriteDelete

func (k *KeybaseDaemonLocal) FavoriteDelete(
	ctx context.Context, folder keybase1.Folder) error

FavoriteDelete implements KeybaseDaemon for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) FavoriteList

func (k *KeybaseDaemonLocal) FavoriteList(
	ctx context.Context, sessionID int) ([]keybase1.Folder, error)

FavoriteList implements KeybaseDaemon for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) FlushUserFromLocalCache

func (k *KeybaseDaemonLocal) FlushUserFromLocalCache(ctx context.Context,
	uid keybase1.UID)

FlushUserFromLocalCache implements the KeybaseDaemon interface for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) GetCurrentMerkleRoot

func (k *KeybaseDaemonLocal) GetCurrentMerkleRoot(ctx context.Context) (
	keybase1.MerkleRootV2, time.Time, error)

GetCurrentMerkleRoot implements the KeybaseService interface for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) GetTeamSettings

func (k *KeybaseDaemonLocal) GetTeamSettings(
	ctx context.Context, teamID keybase1.TeamID) (
	settings keybase1.KBFSTeamSettings, err error)

GetTeamSettings implements the KeybaseService interface for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) Identify

Identify implements KeybaseDaemon for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) LoadTeamPlusKeys

LoadTeamPlusKeys implements KeybaseDaemon for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) LoadUserPlusKeys

func (k *KeybaseDaemonLocal) LoadUserPlusKeys(ctx context.Context,
	uid keybase1.UID, _ keybase1.KID) (UserInfo, error)

LoadUserPlusKeys implements KeybaseDaemon for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) NormalizeSocialAssertion

func (k *KeybaseDaemonLocal) NormalizeSocialAssertion(
	ctx context.Context, assertion string) (keybase1.SocialAssertion, error)

NormalizeSocialAssertion implements the KeybaseService interface for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) Notify

func (k *KeybaseDaemonLocal) Notify(ctx context.Context, notification *keybase1.FSNotification) error

Notify implements KeybaseDaemon for KeybaseDeamonLocal.

func (*KeybaseDaemonLocal) NotifyPathUpdated

func (k *KeybaseDaemonLocal) NotifyPathUpdated(
	ctx context.Context, _ string) error

NotifyPathUpdated implements KeybaseDaemon for KeybaseDeamonLocal.

func (*KeybaseDaemonLocal) NotifySyncStatus

func (k *KeybaseDaemonLocal) NotifySyncStatus(ctx context.Context,
	_ *keybase1.FSPathSyncStatus) error

NotifySyncStatus implements KeybaseDaemon for KeybaseDeamonLocal.

func (*KeybaseDaemonLocal) PutGitMetadata

func (k *KeybaseDaemonLocal) PutGitMetadata(
	ctx context.Context, folder keybase1.Folder, repoID keybase1.RepoID,
	metadata keybase1.GitLocalMetadata) error

PutGitMetadata implements the KeybaseService interface for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) Resolve

Resolve implements KeybaseDaemon for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) ResolveIdentifyImplicitTeam

func (k *KeybaseDaemonLocal) ResolveIdentifyImplicitTeam(
	ctx context.Context, assertions, suffix string, tlfType tlf.Type,
	doIdentifies bool, reason string) (ImplicitTeamInfo, error)

ResolveIdentifyImplicitTeam implements the KeybaseService interface for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) ResolveImplicitTeamByID

func (k *KeybaseDaemonLocal) ResolveImplicitTeamByID(
	ctx context.Context, teamID keybase1.TeamID) (name string, err error)

ResolveImplicitTeamByID implements the KeybaseService interface for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) Shutdown

func (k *KeybaseDaemonLocal) Shutdown()

Shutdown implements KeybaseDaemon for KeybaseDaemonLocal.

func (*KeybaseDaemonLocal) VerifyMerkleRoot

VerifyMerkleRoot implements the KBPKI interface for KeybaseDaemonLocal.

type KeybaseDaemonRPC

type KeybaseDaemonRPC struct {
	*KeybaseServiceBase
	// contains filtered or unexported fields
}

KeybaseDaemonRPC implements the KeybaseService interface using RPC calls.

func NewKeybaseDaemonRPC

func NewKeybaseDaemonRPC(config Config, kbCtx Context, log logger.Logger,
	debug bool, additionalProtocols []rpc.Protocol) *KeybaseDaemonRPC

NewKeybaseDaemonRPC makes a new KeybaseDaemonRPC that makes RPC calls using the socket of the given Keybase context.

func (*KeybaseDaemonRPC) AddProtocols

func (k *KeybaseDaemonRPC) AddProtocols(protocols []rpc.Protocol)

AddProtocols adds protocols that are registered on server connect

func (*KeybaseDaemonRPC) AvatarUpdated

func (k *KeybaseDaemonRPC) AvatarUpdated(ctx context.Context,
	arg keybase1.AvatarUpdatedArg) error

AvatarUpdated implements keybase1.NotifyTeamInterface for KeybaseServiceBase.

func (*KeybaseDaemonRPC) FavoritesChanged

func (k *KeybaseDaemonRPC) FavoritesChanged(ctx context.Context,
	uid keybase1.UID) error

FavoritesChanged implements keybase1.NotifyFavoritesClient

func (*KeybaseDaemonRPC) HandlerName

func (*KeybaseDaemonRPC) HandlerName() string

HandlerName implements the ConnectionHandler interface.

func (*KeybaseDaemonRPC) NewlyAddedToTeam

func (k *KeybaseDaemonRPC) NewlyAddedToTeam(context.Context, keybase1.TeamID) error

NewlyAddedToTeam implements keybase1.NotifyTeamInterface for KeybaseServiceBase.

func (*KeybaseDaemonRPC) OnConnect

func (k *KeybaseDaemonRPC) OnConnect(ctx context.Context,
	conn *rpc.Connection, rawClient rpc.GenericClient,
	server *rpc.Server) (err error)

OnConnect implements the ConnectionHandler interface.

func (*KeybaseDaemonRPC) OnConnectError

func (k *KeybaseDaemonRPC) OnConnectError(err error, wait time.Duration)

OnConnectError implements the ConnectionHandler interface.

func (*KeybaseDaemonRPC) OnDisconnected

func (k *KeybaseDaemonRPC) OnDisconnected(_ context.Context,
	status rpc.DisconnectStatus)

OnDisconnected implements the ConnectionHandler interface.

func (*KeybaseDaemonRPC) OnDoCommandError

func (k *KeybaseDaemonRPC) OnDoCommandError(err error, wait time.Duration)

OnDoCommandError implements the ConnectionHandler interface.

func (*KeybaseDaemonRPC) ShouldRetry

func (k *KeybaseDaemonRPC) ShouldRetry(rpcName string, err error) bool

ShouldRetry implements the ConnectionHandler interface.

func (*KeybaseDaemonRPC) ShouldRetryOnConnect

func (k *KeybaseDaemonRPC) ShouldRetryOnConnect(err error) bool

ShouldRetryOnConnect implements the ConnectionHandler interface.

func (*KeybaseDaemonRPC) Shutdown

func (k *KeybaseDaemonRPC) Shutdown()

Shutdown implements the KeybaseService interface for KeybaseDaemonRPC.

func (*KeybaseDaemonRPC) TeamAbandoned

func (k *KeybaseDaemonRPC) TeamAbandoned(
	ctx context.Context, tid keybase1.TeamID) error

TeamAbandoned implements keybase1.NotifyTeamInterface for KeybaseServiceBase.

func (*KeybaseDaemonRPC) TeamExit

TeamExit implements keybase1.NotifyTeamInterface for KeybaseServiceBase.

type KeybaseService

type KeybaseService interface {

	// Resolve, given an assertion, resolves it to a username/UID
	// pair. The username <-> UID mapping is trusted and
	// immutable, so it can be cached. If the assertion is just
	// the username or a UID assertion, then the resolution can
	// also be trusted. If the returned pair is equal to that of
	// the current session, then it can also be
	// trusted. Otherwise, Identify() needs to be called on the
	// assertion before the assertion -> (username, UID) mapping
	// can be trusted.
	Resolve(ctx context.Context, assertion string) (
		kbname.NormalizedUsername, keybase1.UserOrTeamID, error)

	// Identify, given an assertion, returns a UserInfo struct
	// with the user that matches that assertion, or an error
	// otherwise. The reason string is displayed on any tracker
	// popups spawned.
	Identify(ctx context.Context, assertion, reason string) (
		kbname.NormalizedUsername, keybase1.UserOrTeamID, error)

	// NormalizeSocialAssertion creates a SocialAssertion from its input and
	// normalizes it.  The service name will be lowercased.  If the service is
	// case-insensitive, then the username will also be lowercased.  Colon
	// assertions (twitter:user) will be transformed to the user@twitter
	// format.  Only registered services are allowed.
	NormalizeSocialAssertion(
		ctx context.Context, assertion string) (keybase1.SocialAssertion, error)

	// ResolveIdentifyImplicitTeam resolves, and optionally
	// identifies, an implicit team.  If the implicit team doesn't yet
	// exist, and doIdentifies is true, one is created.
	ResolveIdentifyImplicitTeam(
		ctx context.Context, assertions, suffix string, tlfType tlf.Type,
		doIdentifies bool, reason string) (ImplicitTeamInfo, error)

	// ResolveImplicitTeamByID resolves an implicit team to a team
	// name, given a team ID.
	ResolveImplicitTeamByID(
		ctx context.Context, teamID keybase1.TeamID) (string, error)

	// CreateTeamTLF associates the given TLF ID with the team ID in
	// the team's sigchain.  If the team already has a TLF ID
	// associated with it, this overwrites it.
	CreateTeamTLF(
		ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) error

	// GetTeamSettings returns the KBFS settings for the given team.
	GetTeamSettings(ctx context.Context, teamID keybase1.TeamID) (
		keybase1.KBFSTeamSettings, error)

	// LoadUserPlusKeys returns a UserInfo struct for a
	// user with the specified UID.
	// If you have the UID for a user and don't require Identify to
	// validate an assertion or the identity of a user, use this to
	// get UserInfo structs as it is much cheaper than Identify.
	//
	// pollForKID, if non empty, causes `PollForKID` field to be populated, which
	// causes the service to poll for the given KID. This is useful during
	// provisioning where the provisioner needs to get the MD revision that the
	// provisionee has set the rekey bit on.
	LoadUserPlusKeys(ctx context.Context,
		uid keybase1.UID, pollForKID keybase1.KID) (UserInfo, error)

	// LoadTeamPlusKeys returns a TeamInfo struct for a team with the
	// specified TeamID.  The caller can specify `desiredKeyGen` to
	// force a server check if that particular key gen isn't yet
	// known; it may be set to UnspecifiedKeyGen if no server check is
	// required.  The caller can specify `desiredUID` and
	// `desiredRole` to force a server check if that particular UID
	// isn't a member of the team yet according to local caches; it
	// may be set to "" if no server check is required.
	LoadTeamPlusKeys(ctx context.Context, tid keybase1.TeamID,
		tlfType tlf.Type, desiredKeyGen kbfsmd.KeyGen,
		desiredUser keybase1.UserVersion, desiredKey kbfscrypto.VerifyingKey,
		desiredRole keybase1.TeamRole) (TeamInfo, error)

	// CurrentSession returns a SessionInfo struct with all the
	// information for the current session, or an error otherwise.
	CurrentSession(ctx context.Context, sessionID int) (SessionInfo, error)

	// FavoriteAdd adds the given folder to the list of favorites.
	FavoriteAdd(ctx context.Context, folder keybase1.Folder) error

	// FavoriteAdd removes the given folder from the list of
	// favorites.
	FavoriteDelete(ctx context.Context, folder keybase1.Folder) error

	// FavoriteList returns the current list of favorites.
	FavoriteList(ctx context.Context, sessionID int) ([]keybase1.Folder, error)

	// EncryptFavorites encrypts cached favorites to store on disk.
	EncryptFavorites(ctx context.Context, dataToEncrypt []byte) ([]byte, error)

	// DecryptFavorites decrypts cached favorites stored on disk.
	DecryptFavorites(ctx context.Context, dataToDecrypt []byte) ([]byte, error)

	// Notify sends a filesystem notification.
	Notify(ctx context.Context, notification *keybase1.FSNotification) error

	// NotifyPathUpdated sends a path updated notification.
	NotifyPathUpdated(ctx context.Context, path string) error

	// NotifySyncStatus sends a sync status notification.
	NotifySyncStatus(ctx context.Context,
		status *keybase1.FSPathSyncStatus) error

	// FlushUserFromLocalCache instructs this layer to clear any
	// KBFS-side, locally-cached information about the given user.
	// This does NOT involve communication with the daemon, this is
	// just to force future calls loading this user to fall through to
	// the daemon itself, rather than being served from the cache.
	FlushUserFromLocalCache(ctx context.Context, uid keybase1.UID)

	// EstablishMountDir asks the service for the current mount path
	// and sets it if not established.
	EstablishMountDir(ctx context.Context) (string, error)

	// Shutdown frees any resources associated with this
	// instance. No other methods may be called after this is
	// called.
	Shutdown()
	// contains filtered or unexported methods
}

KeybaseService is an interface for communicating with the keybase service.

type KeybaseServiceBase

type KeybaseServiceBase struct {
	// contains filtered or unexported fields
}

KeybaseServiceBase implements most of KeybaseService from protocol defined clients.

func NewKeybaseServiceBase

func NewKeybaseServiceBase(config Config, kbCtx Context, log logger.Logger) *KeybaseServiceBase

NewKeybaseServiceBase makes a new KeybaseService.

func (*KeybaseServiceBase) CheckReachability

func (k *KeybaseServiceBase) CheckReachability(ctx context.Context) (res keybase1.Reachability, err error)

CheckReachability implements keybase1.ReachabilityInterface.

func (*KeybaseServiceBase) ClientOutOfDate

func (k *KeybaseServiceBase) ClientOutOfDate(ctx context.Context,
	arg keybase1.ClientOutOfDateArg) error

ClientOutOfDate implements keybase1.NotifySessionInterface.

func (*KeybaseServiceBase) CreateTeamTLF

func (k *KeybaseServiceBase) CreateTeamTLF(
	ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) (err error)

CreateTeamTLF implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) CurrentSession

func (k *KeybaseServiceBase) CurrentSession(ctx context.Context, sessionID int) (
	SessionInfo, error)

CurrentSession implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) DecryptFavorites

func (k *KeybaseServiceBase) DecryptFavorites(ctx context.Context, dataToEncrypt []byte) (res []byte, err error)

DecryptFavorites decrypts cached favorites stored on disk.

func (*KeybaseServiceBase) EncryptFavorites

func (k *KeybaseServiceBase) EncryptFavorites(ctx context.Context, dataToEncrypt []byte) (res []byte, err error)

EncryptFavorites encrypts cached favorites to store on disk.

func (*KeybaseServiceBase) EstablishMountDir

func (k *KeybaseServiceBase) EstablishMountDir(ctx context.Context) (
	string, error)

EstablishMountDir asks the service for the current mount path

func (*KeybaseServiceBase) FSEditListRequest

func (k *KeybaseServiceBase) FSEditListRequest(ctx context.Context,
	req keybase1.FSEditListRequest) (err error)

FSEditListRequest implements keybase1.NotifyFSRequestInterface for KeybaseServiceBase.

func (*KeybaseServiceBase) FSSyncStatusRequest

func (k *KeybaseServiceBase) FSSyncStatusRequest(ctx context.Context,
	req keybase1.FSSyncStatusRequest) (err error)

FSSyncStatusRequest implements keybase1.NotifyFSRequestInterface for KeybaseServiceBase.

func (*KeybaseServiceBase) FavoriteAdd

func (k *KeybaseServiceBase) FavoriteAdd(ctx context.Context, folder keybase1.Folder) error

FavoriteAdd implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) FavoriteDelete

func (k *KeybaseServiceBase) FavoriteDelete(ctx context.Context, folder keybase1.Folder) error

FavoriteDelete implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) FavoriteList

func (k *KeybaseServiceBase) FavoriteList(ctx context.Context, sessionID int) ([]keybase1.Folder, error)

FavoriteList implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) FillClients

func (k *KeybaseServiceBase) FillClients(
	identifyClient keybase1.IdentifyInterface,
	userClient keybase1.UserInterface, teamsClient keybase1.TeamsInterface,
	merkleClient keybase1.MerkleInterface,
	sessionClient keybase1.SessionInterface,
	favoriteClient keybase1.FavoriteInterface,
	kbfsClient keybase1.KbfsInterface,
	kbfsMountClient keybase1.KbfsMountInterface,
	gitClient keybase1.GitInterface)

FillClients sets the client protocol implementations needed for a KeybaseService.

func (*KeybaseServiceBase) FinalizeMigration

func (k *KeybaseServiceBase) FinalizeMigration(ctx context.Context,
	folder keybase1.Folder) (err error)

FinalizeMigration implements keybase1.ImplicitTeamMigrationInterface for KeybaseServiceBase.

func (*KeybaseServiceBase) FlushUserFromLocalCache

func (k *KeybaseServiceBase) FlushUserFromLocalCache(ctx context.Context,
	uid keybase1.UID)

FlushUserFromLocalCache implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) GetCurrentMerkleRoot

func (k *KeybaseServiceBase) GetCurrentMerkleRoot(ctx context.Context) (
	keybase1.MerkleRootV2, time.Time, error)

GetCurrentMerkleRoot implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) GetPublicCanonicalTLFNameAndID

func (k *KeybaseServiceBase) GetPublicCanonicalTLFNameAndID(
	ctx context.Context, query keybase1.TLFQuery) (
	res keybase1.CanonicalTLFNameAndIDWithBreaks, err error)

GetPublicCanonicalTLFNameAndID implements the TlfKeysInterface interface for KeybaseServiceBase.

func (*KeybaseServiceBase) GetTLFCryptKeys

func (k *KeybaseServiceBase) GetTLFCryptKeys(ctx context.Context,
	query keybase1.TLFQuery) (res keybase1.GetTLFCryptKeysRes, err error)

GetTLFCryptKeys implements the TlfKeysInterface interface for KeybaseServiceBase.

func (*KeybaseServiceBase) GetTeamSettings

func (k *KeybaseServiceBase) GetTeamSettings(
	ctx context.Context, teamID keybase1.TeamID) (
	keybase1.KBFSTeamSettings, error)

GetTeamSettings implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) Identify

func (k *KeybaseServiceBase) Identify(ctx context.Context, assertion, reason string) (
	kbname.NormalizedUsername, keybase1.UserOrTeamID, error)

Identify implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) KeyfamilyChanged

func (k *KeybaseServiceBase) KeyfamilyChanged(ctx context.Context,
	uid keybase1.UID) error

KeyfamilyChanged implements keybase1.NotifyKeyfamilyInterface.

func (*KeybaseServiceBase) LoadTeamPlusKeys

func (k *KeybaseServiceBase) LoadTeamPlusKeys(
	ctx context.Context, tid keybase1.TeamID, tlfType tlf.Type,
	desiredKeyGen kbfsmd.KeyGen, desiredUser keybase1.UserVersion,
	desiredKey kbfscrypto.VerifyingKey, desiredRole keybase1.TeamRole) (
	TeamInfo, error)

LoadTeamPlusKeys implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) LoadUserPlusKeys

func (k *KeybaseServiceBase) LoadUserPlusKeys(ctx context.Context,
	uid keybase1.UID, pollForKID keybase1.KID) (UserInfo, error)

LoadUserPlusKeys implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) LoggedIn

func (k *KeybaseServiceBase) LoggedIn(ctx context.Context, name string) error

LoggedIn implements keybase1.NotifySessionInterface.

func (*KeybaseServiceBase) LoggedOut

func (k *KeybaseServiceBase) LoggedOut(ctx context.Context) error

LoggedOut implements keybase1.NotifySessionInterface.

func (*KeybaseServiceBase) NormalizeSocialAssertion

func (k *KeybaseServiceBase) NormalizeSocialAssertion(
	ctx context.Context, assertion string) (keybase1.SocialAssertion, error)

NormalizeSocialAssertion implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) Notify

func (k *KeybaseServiceBase) Notify(ctx context.Context, notification *keybase1.FSNotification) error

Notify implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) NotifyPathUpdated

func (k *KeybaseServiceBase) NotifyPathUpdated(
	ctx context.Context, path string) error

NotifyPathUpdated implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) NotifySyncStatus

func (k *KeybaseServiceBase) NotifySyncStatus(ctx context.Context,
	status *keybase1.FSPathSyncStatus) error

NotifySyncStatus implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) PaperKeyCached

func (k *KeybaseServiceBase) PaperKeyCached(ctx context.Context,
	arg keybase1.PaperKeyCachedArg) error

PaperKeyCached implements keybase1.NotifyPaperKeyInterface.

func (*KeybaseServiceBase) PutGitMetadata

func (k *KeybaseServiceBase) PutGitMetadata(
	ctx context.Context, folder keybase1.Folder, repoID keybase1.RepoID,
	metadata keybase1.GitLocalMetadata) error

PutGitMetadata implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) ReachabilityChanged

func (k *KeybaseServiceBase) ReachabilityChanged(ctx context.Context,
	reachability keybase1.Reachability) error

ReachabilityChanged implements keybase1.ReachabiltyInterface.

func (*KeybaseServiceBase) Resolve

Resolve implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) ResolveIdentifyImplicitTeam

func (k *KeybaseServiceBase) ResolveIdentifyImplicitTeam(
	ctx context.Context, assertions, suffix string, tlfType tlf.Type,
	doIdentifies bool, reason string) (ImplicitTeamInfo, error)

ResolveIdentifyImplicitTeam implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) ResolveImplicitTeamByID

func (k *KeybaseServiceBase) ResolveImplicitTeamByID(
	ctx context.Context, teamID keybase1.TeamID) (name string, err error)

ResolveImplicitTeamByID implements the KeybaseService interface for KeybaseServiceBase.

func (*KeybaseServiceBase) StartMigration

func (k *KeybaseServiceBase) StartMigration(ctx context.Context,
	folder keybase1.Folder) (err error)

StartMigration implements keybase1.ImplicitTeamMigrationInterface for KeybaseServiceBase.

func (*KeybaseServiceBase) StartReachability

func (k *KeybaseServiceBase) StartReachability(ctx context.Context) (res keybase1.Reachability, err error)

StartReachability implements keybase1.ReachabilityInterface.

func (*KeybaseServiceBase) TeamChangedByID

func (k *KeybaseServiceBase) TeamChangedByID(ctx context.Context,
	arg keybase1.TeamChangedByIDArg) error

TeamChangedByID implements keybase1.NotifyTeamInterface for KeybaseServiceBase.

func (*KeybaseServiceBase) TeamChangedByName

func (k *KeybaseServiceBase) TeamChangedByName(ctx context.Context,
	arg keybase1.TeamChangedByNameArg) error

TeamChangedByName implements keybase1.NotifyTeamInterface for KeybaseServiceBase.

func (*KeybaseServiceBase) TeamDeleted

func (k *KeybaseServiceBase) TeamDeleted(ctx context.Context,
	teamID keybase1.TeamID) error

TeamDeleted implements keybase1.NotifyTeamInterface for KeybaseServiceBase.

func (*KeybaseServiceBase) VerifyMerkleRoot

func (k *KeybaseServiceBase) VerifyMerkleRoot(
	ctx context.Context, root keybase1.MerkleRootV2,
	kbfsRoot keybase1.KBFSRoot) error

VerifyMerkleRoot implements the KBPKI interface for KeybaseServiceBase.

type KeybaseServiceCn

type KeybaseServiceCn interface {
	NewKeybaseService(
		config Config, params InitParams, ctx Context, log logger.Logger) (
		KeybaseService, error)
	NewCrypto(
		config Config, params InitParams, ctx Context, log logger.Logger) (
		Crypto, error)
	NewChat(
		config Config, params InitParams, ctx Context, log logger.Logger) (
		Chat, error)
}

KeybaseServiceCn defines methods needed to construct KeybaseService and Crypto implementations.

type KeybaseServiceMeasured

type KeybaseServiceMeasured struct {
	// contains filtered or unexported fields
}

KeybaseServiceMeasured delegates to another KeybaseService instance but also keeps track of stats.

func NewKeybaseServiceMeasured

func NewKeybaseServiceMeasured(delegate KeybaseService, r metrics.Registry) KeybaseServiceMeasured

NewKeybaseServiceMeasured creates and returns a new KeybaseServiceMeasured instance with the given delegate and registry.

func (KeybaseServiceMeasured) CreateTeamTLF

func (k KeybaseServiceMeasured) CreateTeamTLF(
	ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) (err error)

CreateTeamTLF implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) CurrentSession

func (k KeybaseServiceMeasured) CurrentSession(ctx context.Context, sessionID int) (
	sessionInfo SessionInfo, err error)

CurrentSession implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) DecryptFavorites

func (k KeybaseServiceMeasured) DecryptFavorites(ctx context.Context,
	dataIn []byte) (dataOut []byte, err error)

DecryptFavorites implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) EncryptFavorites

func (k KeybaseServiceMeasured) EncryptFavorites(ctx context.Context,
	dataIn []byte) (dataOut []byte, err error)

EncryptFavorites implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) EstablishMountDir

func (k KeybaseServiceMeasured) EstablishMountDir(ctx context.Context) (string, error)

EstablishMountDir implements the KeybaseDaemon interface for KeybaseDaemonLocal.

func (KeybaseServiceMeasured) FavoriteAdd

func (k KeybaseServiceMeasured) FavoriteAdd(ctx context.Context, folder keybase1.Folder) (err error)

FavoriteAdd implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) FavoriteDelete

func (k KeybaseServiceMeasured) FavoriteDelete(ctx context.Context, folder keybase1.Folder) (err error)

FavoriteDelete implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) FavoriteList

func (k KeybaseServiceMeasured) FavoriteList(ctx context.Context, sessionID int) (
	favorites []keybase1.Folder, err error)

FavoriteList implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) FlushUserFromLocalCache

func (k KeybaseServiceMeasured) FlushUserFromLocalCache(
	ctx context.Context, uid keybase1.UID)

FlushUserFromLocalCache implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) GetCurrentMerkleRoot

func (k KeybaseServiceMeasured) GetCurrentMerkleRoot(ctx context.Context) (
	root keybase1.MerkleRootV2, updateTime time.Time, err error)

GetCurrentMerkleRoot implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) GetTeamSettings

func (k KeybaseServiceMeasured) GetTeamSettings(
	ctx context.Context, teamID keybase1.TeamID) (
	settings keybase1.KBFSTeamSettings, err error)

GetTeamSettings implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) Identify

func (k KeybaseServiceMeasured) Identify(ctx context.Context, assertion, reason string) (
	name kbname.NormalizedUsername, id keybase1.UserOrTeamID, err error)

Identify implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) LoadTeamPlusKeys

func (k KeybaseServiceMeasured) LoadTeamPlusKeys(ctx context.Context,
	tid keybase1.TeamID, tlfType tlf.Type, desiredKeyGen kbfsmd.KeyGen,
	desiredUser keybase1.UserVersion, desiredKey kbfscrypto.VerifyingKey,
	desiredRole keybase1.TeamRole) (teamInfo TeamInfo, err error)

LoadTeamPlusKeys implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) LoadUserPlusKeys

func (k KeybaseServiceMeasured) LoadUserPlusKeys(ctx context.Context,
	uid keybase1.UID, pollForKID keybase1.KID) (userInfo UserInfo, err error)

LoadUserPlusKeys implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) NormalizeSocialAssertion

func (k KeybaseServiceMeasured) NormalizeSocialAssertion(
	ctx context.Context, assertion string) (res keybase1.SocialAssertion, err error)

NormalizeSocialAssertion implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) Notify

func (k KeybaseServiceMeasured) Notify(ctx context.Context, notification *keybase1.FSNotification) (err error)

Notify implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) NotifyPathUpdated

func (k KeybaseServiceMeasured) NotifyPathUpdated(
	ctx context.Context, path string) (err error)

NotifyPathUpdated implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) NotifySyncStatus

func (k KeybaseServiceMeasured) NotifySyncStatus(ctx context.Context,
	status *keybase1.FSPathSyncStatus) (err error)

NotifySyncStatus implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) PutGitMetadata

func (k KeybaseServiceMeasured) PutGitMetadata(
	ctx context.Context, folder keybase1.Folder, repoID keybase1.RepoID,
	metadata keybase1.GitLocalMetadata) (err error)

PutGitMetadata implements the KeybaseDaemon interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) Resolve

func (k KeybaseServiceMeasured) Resolve(ctx context.Context, assertion string) (
	name kbname.NormalizedUsername, uid keybase1.UserOrTeamID, err error)

Resolve implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) ResolveIdentifyImplicitTeam

func (k KeybaseServiceMeasured) ResolveIdentifyImplicitTeam(
	ctx context.Context, assertions, suffix string, tlfType tlf.Type,
	doIdentifies bool, reason string) (info ImplicitTeamInfo, err error)

ResolveIdentifyImplicitTeam implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) ResolveImplicitTeamByID

func (k KeybaseServiceMeasured) ResolveImplicitTeamByID(
	ctx context.Context, teamID keybase1.TeamID) (name string, err error)

ResolveImplicitTeamByID implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) Shutdown

func (k KeybaseServiceMeasured) Shutdown()

Shutdown implements the KeybaseService interface for KeybaseServiceMeasured.

func (KeybaseServiceMeasured) VerifyMerkleRoot

func (k KeybaseServiceMeasured) VerifyMerkleRoot(
	ctx context.Context, root keybase1.MerkleRootV2,
	kbfsRoot keybase1.KBFSRoot) (err error)

VerifyMerkleRoot implements the KBPKI interface for KeybaseServiceMeasured.

type LocalUser

type LocalUser struct {
	UserInfo
	Asserts []string
	// Index into UserInfo.CryptPublicKeys.
	CurrentCryptPublicKeyIndex int
	// Index into UserInfo.VerifyingKeys.
	CurrentVerifyingKeyIndex int
	// Unverified keys.
	UnverifiedKeys []keybase1.PublicKey
}

LocalUser represents a fake KBFS user, useful for testing.

func MakeLocalUsers

func MakeLocalUsers(users []kbname.NormalizedUsername) []LocalUser

MakeLocalUsers is a helper function to generate a list of LocalUsers suitable to use with KeybaseDaemonLocal.

func (*LocalUser) GetCurrentCryptPublicKey

func (lu *LocalUser) GetCurrentCryptPublicKey() kbfscrypto.CryptPublicKey

GetCurrentCryptPublicKey returns this LocalUser's public encryption key.

func (*LocalUser) GetCurrentVerifyingKey

func (lu *LocalUser) GetCurrentVerifyingKey() kbfscrypto.VerifyingKey

GetCurrentVerifyingKey returns this LocalUser's public signing key.

func (*LocalUser) GetPublicKeys

func (lu *LocalUser) GetPublicKeys() []keybase1.PublicKey

GetPublicKeys returns all of this LocalUser's public encryption keys.

type MDCache

type MDCache interface {
	// Get gets the metadata object associated with the given TLF ID,
	// revision number, and branch ID (kbfsmd.NullBranchID for merged MD).
	Get(tlf tlf.ID, rev kbfsmd.Revision, bid kbfsmd.BranchID) (ImmutableRootMetadata, error)
	// Put stores the metadata object, only if an MD matching that TLF
	// ID, revision number, and branch ID isn't already cached.  If
	// there is already a matching item in the cache, we require that
	// caller manages the cache explicitly by deleting or replacing it
	// explicitly.  This should be used when putting existing MDs
	// being fetched from the server.
	Put(md ImmutableRootMetadata) error
	// Delete removes the given metadata object from the cache if it exists.
	Delete(tlf tlf.ID, rev kbfsmd.Revision, bid kbfsmd.BranchID)
	// Replace replaces the entry matching the md under the old branch
	// ID with the new one.  If the old entry doesn't exist, this is
	// equivalent to a Put, except that it overrides anything else
	// that's already in the cache.  This should be used when putting
	// new MDs created locally.
	Replace(newRmd ImmutableRootMetadata, oldBID kbfsmd.BranchID) error
	// MarkPutToServer sets `PutToServer` to true for the specified
	// MD, if it already exists in the cache.
	MarkPutToServer(tlf tlf.ID, rev kbfsmd.Revision, bid kbfsmd.BranchID)
	// GetIDForHandle retrieves a cached, trusted TLF ID for the given
	// handle, if one exists.
	GetIDForHandle(handle *TlfHandle) (tlf.ID, error)
	// PutIDForHandle caches a trusted TLF ID for the given handle.
	PutIDForHandle(handle *TlfHandle, id tlf.ID) error
	// ChangeHandleForID moves an ID to be under a new handle, if the
	// ID is cached already.
	ChangeHandleForID(oldHandle *TlfHandle, newHandle *TlfHandle)
	// GetNextMD returns a cached view of the next MD following the
	// given global Merkle root.
	GetNextMD(tlfID tlf.ID, rootSeqno keybase1.Seqno) (
		nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
		nextRootSeqno keybase1.Seqno, err error)
	// PutNextMD caches a view of the next MD following the given
	// global Merkle root.
	PutNextMD(tlfID tlf.ID, rootSeqno keybase1.Seqno,
		nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
		nextRootSeqno keybase1.Seqno) error
}

MDCache gets and puts plaintext top-level metadata into the cache.

type MDCacheStandard

type MDCacheStandard struct {
	// contains filtered or unexported fields
}

MDCacheStandard implements a simple LRU cache for per-folder metadata objects.

func NewMDCacheStandard

func NewMDCacheStandard(capacity int) *MDCacheStandard

NewMDCacheStandard constructs a new MDCacheStandard using the given cache capacity.

func (*MDCacheStandard) ChangeHandleForID

func (md *MDCacheStandard) ChangeHandleForID(
	oldHandle *TlfHandle, newHandle *TlfHandle)

ChangeHandleForID implements the MDCache interface for MDCacheStandard.

func (*MDCacheStandard) Delete

func (md *MDCacheStandard) Delete(tlf tlf.ID, rev kbfsmd.Revision,
	bid kbfsmd.BranchID)

Delete implements the MDCache interface for MDCacheStandard.

func (*MDCacheStandard) Get

Get implements the MDCache interface for MDCacheStandard.

func (*MDCacheStandard) GetIDForHandle

func (md *MDCacheStandard) GetIDForHandle(handle *TlfHandle) (tlf.ID, error)

GetIDForHandle implements the MDCache interface for MDCacheStandard.

func (*MDCacheStandard) GetNextMD

func (md *MDCacheStandard) GetNextMD(tlfID tlf.ID, rootSeqno keybase1.Seqno) (
	nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
	nextRootSeqno keybase1.Seqno, err error)

GetNextMD implements the MDCache interface for MDCacheStandard.

func (*MDCacheStandard) MarkPutToServer

func (md *MDCacheStandard) MarkPutToServer(
	tlf tlf.ID, rev kbfsmd.Revision, bid kbfsmd.BranchID)

MarkPutToServer implements the MDCache interface for MDCacheStandard.

func (*MDCacheStandard) Put

Put implements the MDCache interface for MDCacheStandard.

func (*MDCacheStandard) PutIDForHandle

func (md *MDCacheStandard) PutIDForHandle(handle *TlfHandle, id tlf.ID) error

PutIDForHandle implements the MDCache interface for MDCacheStandard.

func (*MDCacheStandard) PutNextMD

func (md *MDCacheStandard) PutNextMD(
	tlfID tlf.ID, rootSeqno keybase1.Seqno, nextKbfsRoot *kbfsmd.MerkleRoot,
	nextMerkleNodes [][]byte, nextRootSeqno keybase1.Seqno) error

PutNextMD implements the MDCache interface for MDCacheStandard.

func (*MDCacheStandard) Replace

func (md *MDCacheStandard) Replace(newRmd ImmutableRootMetadata,
	oldBID kbfsmd.BranchID) error

Replace implements the MDCache interface for MDCacheStandard.

type MDJournalConflictError

type MDJournalConflictError struct{}

MDJournalConflictError is an error that is returned when a put detects a rewritten journal.

func (MDJournalConflictError) Error

func (e MDJournalConflictError) Error() string

type MDMismatchError

type MDMismatchError struct {
	Revision kbfsmd.Revision
	Dir      string
	TlfID    tlf.ID
	Err      error
}

MDMismatchError indicates an inconsistent or unverifiable MD object for the given top-level folder.

func (MDMismatchError) Error

func (e MDMismatchError) Error() string

Error implements the error interface for MDMismatchError

type MDOps

type MDOps interface {

	// GetForTLF returns the current metadata object
	// corresponding to the given top-level folder, if the logged-in
	// user has read permission on the folder.
	//
	// If lockBeforeGet is not nil, it causes mdserver to take the lock on the
	// lock ID before the get.
	GetForTLF(ctx context.Context, id tlf.ID, lockBeforeGet *keybase1.LockID) (
		ImmutableRootMetadata, error)

	// GetForTLFByTime returns the newest merged MD update with a
	// server timestamp less than or equal to `serverTime`.
	GetForTLFByTime(ctx context.Context, id tlf.ID, serverTime time.Time) (
		ImmutableRootMetadata, error)

	// GetUnmergedForTLF is the same as the above but for unmerged
	// metadata.
	GetUnmergedForTLF(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID) (
		ImmutableRootMetadata, error)

	// GetRange returns a range of metadata objects corresponding to
	// the passed revision numbers (inclusive).
	//
	// If lockBeforeGet is not nil, it causes mdserver to take the lock on the
	// lock ID before the get.
	GetRange(ctx context.Context, id tlf.ID, start, stop kbfsmd.Revision,
		lockID *keybase1.LockID) ([]ImmutableRootMetadata, error)

	// GetUnmergedRange is the same as the above but for unmerged
	// metadata history (inclusive).
	GetUnmergedRange(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID,
		start, stop kbfsmd.Revision) ([]ImmutableRootMetadata, error)

	// Put stores the metadata object for the given top-level folder.
	// This also adds the resulting ImmutableRootMetadata object to
	// the mdcache, if the Put is successful.  Note that constructing
	// the ImmutableRootMetadata requires knowing the verifying key,
	// which might not be the same as the local user's verifying key
	// if the MD has been copied from a previous update.
	//
	// If lockContext is not nil, it causes the mdserver to check a lockID at
	// the time of the put, and optionally (if specified in lockContext)
	// releases the lock on the lock ID if the put is successful. Releasing the
	// lock in mdserver is idempotent. Note that journalMDOps doesn't support
	// lockContext for now. If journaling is enabled, use FinishSinbleOp to
	// require locks.
	//
	// The priority parameter specifies the priority of this particular MD put
	// operation. When conflict happens, mdserver tries to prioritize writes
	// with higher priorities. Caller should use pre-defined (or define new)
	// constants in keybase1 package, such as keybase1.MDPriorityNormal. Note
	// that journalMDOps doesn't support any priority other than
	// MDPriorityNormal for now. If journaling is enabled, use FinishSinbleOp
	// to override priority.
	Put(ctx context.Context, rmd *RootMetadata,
		verifyingKey kbfscrypto.VerifyingKey,
		lockContext *keybase1.LockContext, priority keybase1.MDPriority) (
		ImmutableRootMetadata, error)

	// PutUnmerged is the same as the above but for unmerged metadata
	// history.  This also adds the resulting ImmutableRootMetadata
	// object to the mdcache, if the PutUnmerged is successful.  Note
	// that constructing the ImmutableRootMetadata requires knowing
	// the verifying key, which might not be the same as the local
	// user's verifying key if the MD has been copied from a previous
	// update.
	PutUnmerged(ctx context.Context, rmd *RootMetadata,
		verifyingKey kbfscrypto.VerifyingKey) (ImmutableRootMetadata, error)

	// PruneBranch prunes all unmerged history for the given TLF
	// branch.
	PruneBranch(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID) error

	// ResolveBranch prunes all unmerged history for the given TLF
	// branch, and also deletes any blocks in `blocksToDelete` that
	// are still in the local journal.  In addition, it appends the
	// given MD to the journal.  This also adds the resulting
	// ImmutableRootMetadata object to the mdcache, if the
	// ResolveBranch is successful.  Note that constructing the
	// ImmutableRootMetadata requires knowing the verifying key, which
	// might not be the same as the local user's verifying key if the
	// MD has been copied from a previous update.
	ResolveBranch(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID,
		blocksToDelete []kbfsblock.ID, rmd *RootMetadata,
		verifyingKey kbfscrypto.VerifyingKey) (ImmutableRootMetadata, error)

	// GetLatestHandleForTLF returns the server's idea of the latest
	// handle for the TLF, which may not yet be reflected in the MD if
	// the TLF hasn't been rekeyed since it entered into a conflicting
	// state.
	GetLatestHandleForTLF(ctx context.Context, id tlf.ID) (tlf.Handle, error)
	// contains filtered or unexported methods
}

MDOps gets and puts root metadata to an MDServer. On a get, it verifies the metadata is signed by the metadata's signing key.

type MDOpsStandard

type MDOpsStandard struct {
	// contains filtered or unexported fields
}

MDOpsStandard provides plaintext RootMetadata objects to upper layers, and processes RootMetadataSigned objects (encrypted and signed) suitable for passing to/from the MDServer backend.

func NewMDOpsStandard

func NewMDOpsStandard(config Config) *MDOpsStandard

NewMDOpsStandard returns a new MDOpsStandard

func (*MDOpsStandard) GetForTLF

func (md *MDOpsStandard) GetForTLF(
	ctx context.Context, id tlf.ID, lockBeforeGet *keybase1.LockID) (
	ImmutableRootMetadata, error)

GetForTLF implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) GetForTLFByTime

func (md *MDOpsStandard) GetForTLFByTime(
	ctx context.Context, id tlf.ID, serverTime time.Time) (
	irmd ImmutableRootMetadata, err error)

GetForTLFByTime implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) GetIDForHandle

func (md *MDOpsStandard) GetIDForHandle(
	ctx context.Context, handle *TlfHandle) (id tlf.ID, err error)

GetIDForHandle implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) GetLatestHandleForTLF

func (md *MDOpsStandard) GetLatestHandleForTLF(ctx context.Context, id tlf.ID) (
	tlf.Handle, error)

GetLatestHandleForTLF implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) GetRange

func (md *MDOpsStandard) GetRange(ctx context.Context, id tlf.ID,
	start, stop kbfsmd.Revision, lockBeforeGet *keybase1.LockID) (
	[]ImmutableRootMetadata, error)

GetRange implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) GetUnmergedForTLF

func (md *MDOpsStandard) GetUnmergedForTLF(
	ctx context.Context, id tlf.ID, bid kbfsmd.BranchID) (
	ImmutableRootMetadata, error)

GetUnmergedForTLF implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) GetUnmergedRange

func (md *MDOpsStandard) GetUnmergedRange(ctx context.Context, id tlf.ID,
	bid kbfsmd.BranchID, start, stop kbfsmd.Revision) (
	[]ImmutableRootMetadata, error)

GetUnmergedRange implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) PruneBranch

func (md *MDOpsStandard) PruneBranch(
	ctx context.Context, id tlf.ID, bid kbfsmd.BranchID) error

PruneBranch implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) Put

Put implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) PutUnmerged

func (md *MDOpsStandard) PutUnmerged(
	ctx context.Context, rmd *RootMetadata,
	verifyingKey kbfscrypto.VerifyingKey) (ImmutableRootMetadata, error)

PutUnmerged implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) ResolveBranch

func (md *MDOpsStandard) ResolveBranch(
	ctx context.Context, id tlf.ID, bid kbfsmd.BranchID, _ []kbfsblock.ID,
	rmd *RootMetadata, verifyingKey kbfscrypto.VerifyingKey) (
	ImmutableRootMetadata, error)

ResolveBranch implements the MDOps interface for MDOpsStandard.

func (*MDOpsStandard) ValidateLatestHandleNotFinal

func (md *MDOpsStandard) ValidateLatestHandleNotFinal(
	ctx context.Context, h *TlfHandle) (bool, error)

ValidateLatestHandleNotFinal implements the MDOps interface for MDOpsStandard.

type MDServer

type MDServer interface {

	// GetForHandle returns the current (signed/encrypted) metadata
	// object corresponding to the given top-level folder's handle, if
	// the logged-in user has read permission on the folder.  It
	// creates the folder if one doesn't exist yet, and the logged-in
	// user has permission to do so.
	//
	// If lockBeforeGet is not nil, it takes a lock on the lock ID before
	// trying to get anything. If taking the lock fails, an error is returned.
	// Note that taking a lock from the mdserver is idempotent.
	//
	// If there is no returned error, then the returned ID must
	// always be non-null. A nil *RootMetadataSigned may be
	// returned, but if it is non-nil, then its ID must match the
	// returned ID.
	GetForHandle(ctx context.Context, handle tlf.Handle,
		mStatus kbfsmd.MergeStatus, lockBeforeGet *keybase1.LockID) (
		tlf.ID, *RootMetadataSigned, error)

	// GetForTLF returns the current (signed/encrypted) metadata object
	// corresponding to the given top-level folder, if the logged-in
	// user has read permission on the folder.
	//
	// If lockBeforeGet is not nil, it takes a lock on the lock ID before
	// trying to get anything. If taking the lock fails, an error is returned.
	// Note that taking a lock from the mdserver is idempotent.
	GetForTLF(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID, mStatus kbfsmd.MergeStatus,
		lockBeforeGet *keybase1.LockID) (*RootMetadataSigned, error)

	// GetForTLFByTime returns the earliest merged MD update with a
	// server timestamp equal or greater to `serverTime`.
	GetForTLFByTime(ctx context.Context, id tlf.ID, serverTime time.Time) (
		*RootMetadataSigned, error)

	// GetRange returns a range of (signed/encrypted) metadata objects
	// corresponding to the passed revision numbers (inclusive).
	//
	// If lockBeforeGet is not nil, it takes a lock on the lock ID before
	// trying to get anything. If taking the lock fails, an error is returned.
	// Note that taking a lock from the mdserver is idempotent.
	GetRange(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID, mStatus kbfsmd.MergeStatus,
		start, stop kbfsmd.Revision, lockBeforeGet *keybase1.LockID) (
		[]*RootMetadataSigned, error)

	// Put stores the (signed/encrypted) metadata object for the given
	// top-level folder. Note: If the unmerged bit is set in the metadata
	// block's flags bitmask it will be appended to the unmerged per-device
	// history.
	//
	// If lockContext is not nil, it causes the mdserver to check a lockID at
	// the time of the put, and optionally (if specified in lockContext)
	// releases the lock on the lock ID if the put is successful. Releasing the
	// lock in mdserver is idempotent.
	Put(ctx context.Context, rmds *RootMetadataSigned, extra kbfsmd.ExtraMetadata,
		lockContext *keybase1.LockContext, priority keybase1.MDPriority) error

	// Lock ensures lockID for tlfID is taken by this session, i.e.,
	// idempotently take the lock. If the lock is already taken by *another*
	// session, mdserver returns a throttle error, causing RPC layer at client
	// to retry. So caller of this method should observe a behavior similar to
	// blocking call, which upon successful return, makes sure the lock is
	// taken on the server. Note that the lock expires after certain time, so
	// it's important to make writes contingent to the lock by requiring the
	// lockID in Put.
	Lock(ctx context.Context, tlfID tlf.ID, lockID keybase1.LockID) error

	// Release Lock ensures lockID for tlfID is not taken by this session, i.e.,
	// idempotently release the lock. If the lock is already released or
	// expired, this is a no-op.
	ReleaseLock(ctx context.Context, tlfID tlf.ID, lockID keybase1.LockID) error

	// StartImplicitTeamMigration tells mdserver to put a implicit team
	// migration lock on id, which prevents any rekey MD writes from going
	// in. Normal classic MD updates can still happen after implicit team
	// migration has started, until a iTeam-style MD is written.
	StartImplicitTeamMigration(ctx context.Context, id tlf.ID) (err error)

	// PruneBranch prunes all unmerged history for the given TLF branch.
	PruneBranch(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID) error

	// RegisterForUpdate tells the MD server to inform the caller when
	// there is a merged update with a revision number greater than
	// currHead, which did NOT originate from this same MD server
	// session.  This method returns a chan which can receive only a
	// single error before it's closed.  If the received err is nil,
	// then there is updated MD ready to fetch which didn't originate
	// locally; if it is non-nil, then the previous registration
	// cannot send the next notification (e.g., the connection to the
	// MD server may have failed). In either case, the caller must
	// re-register to get a new chan that can receive future update
	// notifications.
	RegisterForUpdate(ctx context.Context, id tlf.ID,
		currHead kbfsmd.Revision) (<-chan error, error)

	// CancelRegistration lets the local MDServer instance know that
	// we are no longer interested in updates for the specified
	// folder.  It does not necessarily forward this cancellation to
	// remote servers.
	CancelRegistration(ctx context.Context, id tlf.ID)

	// CheckForRekeys initiates the rekey checking process on the
	// server.  The server is allowed to delay this request, and so it
	// returns a channel for returning the error. Actual rekey
	// requests are expected to come in asynchronously.
	CheckForRekeys(ctx context.Context) <-chan error

	// TruncateLock attempts to take the history truncation lock for
	// this folder, for a TTL defined by the server.  Returns true if
	// the lock was successfully taken.
	TruncateLock(ctx context.Context, id tlf.ID) (bool, error)
	// TruncateUnlock attempts to release the history truncation lock
	// for this folder.  Returns true if the lock was successfully
	// released.
	TruncateUnlock(ctx context.Context, id tlf.ID) (bool, error)

	// DisableRekeyUpdatesForTesting disables processing rekey updates
	// received from the mdserver while testing.
	DisableRekeyUpdatesForTesting()

	// Shutdown is called to shutdown an MDServer connection.
	Shutdown()

	// IsConnected returns whether the MDServer is connected.
	IsConnected() bool

	// GetLatestHandleForTLF returns the server's idea of the latest handle for the TLF,
	// which may not yet be reflected in the MD if the TLF hasn't been rekeyed since it
	// entered into a conflicting state.  For the highest level of confidence, the caller
	// should verify the mapping with a Merkle tree lookup.
	GetLatestHandleForTLF(ctx context.Context, id tlf.ID) (tlf.Handle, error)

	// OffsetFromServerTime is the current estimate for how off our
	// local clock is from the mdserver clock.  Add this to any
	// mdserver-provided timestamps to get the "local" time of the
	// corresponding event.  If the returned bool is false, then we
	// don't have a current estimate for the offset.
	OffsetFromServerTime() (time.Duration, bool)

	// GetKeyBundles looks up the key bundles for the given key
	// bundle IDs. tlfID must be non-zero but either or both wkbID
	// and rkbID can be zero, in which case nil will be returned
	// for the respective bundle. If a bundle cannot be found, an
	// error is returned and nils are returned for both bundles.
	GetKeyBundles(ctx context.Context, tlfID tlf.ID,
		wkbID kbfsmd.TLFWriterKeyBundleID, rkbID kbfsmd.TLFReaderKeyBundleID) (
		*kbfsmd.TLFWriterKeyBundleV3, *kbfsmd.TLFReaderKeyBundleV3, error)

	// CheckReachability is called when the Keybase service sends a notification
	// that network connectivity has changed.
	CheckReachability(ctx context.Context)

	// FastForwardBackoff fast forwards any existing backoff timer for
	// reconnects. If MD server is connected at the time this is called, it's
	// essentially a no-op.
	FastForwardBackoff()

	// FindNextMD finds the serialized (and possibly encrypted) root
	// metadata object from the leaf node of the second KBFS merkle
	// tree to be produced after a given Keybase global merkle tree
	// sequence number `rootSeqno` (and all merkle nodes between it
	// and the root, and the root itself).  It also returns the global
	// merkle tree sequence number of the root that first included the
	// returned metadata object.
	FindNextMD(ctx context.Context, tlfID tlf.ID, rootSeqno keybase1.Seqno) (
		nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
		nextRootSeqno keybase1.Seqno, err error)

	// GetMerkleRootLatest returns the latest KBFS merkle root for the
	// given tree ID.
	GetMerkleRootLatest(ctx context.Context, treeID keybase1.MerkleTreeID) (
		root *kbfsmd.MerkleRoot, err error)
	// contains filtered or unexported methods
}

MDServer gets and puts metadata for each top-level directory. The instantiation should be able to fetch session/user details via KBPKI. On a put, the server is responsible for 1) ensuring the user has appropriate permissions for whatever modifications were made; 2) ensuring that LastModifyingWriter and LastModifyingUser are updated appropriately; and 3) detecting conflicting writes based on the previous root block ID (i.e., when it supports strict consistency). On a get, it verifies the logged-in user has read permissions.

TODO: Add interface for searching by time

type MDServerDisconnected

type MDServerDisconnected struct {
}

MDServerDisconnected indicates the MDServer has been disconnected for clients waiting on an update channel.

func (MDServerDisconnected) Error

func (e MDServerDisconnected) Error() string

Error implements the error interface for MDServerDisconnected.

type MDServerDisk

type MDServerDisk struct {
	// contains filtered or unexported fields
}

MDServerDisk stores all info on disk, either in levelDBs, or disk journals and flat files for the actual MDs.

func NewMDServerDir

func NewMDServerDir(
	config mdServerLocalConfig, dirPath string) (*MDServerDisk, error)

NewMDServerDir constructs a new MDServerDisk that stores its data in the given directory.

func NewMDServerTempDir

func NewMDServerTempDir(config mdServerLocalConfig) (*MDServerDisk, error)

NewMDServerTempDir constructs a new MDServerDisk that stores its data in a temp directory which is cleaned up on shutdown.

func (*MDServerDisk) CancelRegistration

func (md *MDServerDisk) CancelRegistration(_ context.Context, id tlf.ID)

CancelRegistration implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) CheckForRekeys

func (md *MDServerDisk) CheckForRekeys(ctx context.Context) <-chan error

CheckForRekeys implements the MDServer interface.

func (*MDServerDisk) CheckReachability

func (md *MDServerDisk) CheckReachability(ctx context.Context)

CheckReachability implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) DisableRekeyUpdatesForTesting

func (md *MDServerDisk) DisableRekeyUpdatesForTesting()

DisableRekeyUpdatesForTesting implements the MDServer interface.

func (*MDServerDisk) FastForwardBackoff

func (md *MDServerDisk) FastForwardBackoff()

FastForwardBackoff implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) FindNextMD

func (md *MDServerDisk) FindNextMD(
	ctx context.Context, tlfID tlf.ID, rootSeqno keybase1.Seqno) (
	nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
	nextRootSeqno keybase1.Seqno, err error)

FindNextMD implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) GetForHandle

func (md *MDServerDisk) GetForHandle(ctx context.Context, handle tlf.Handle,
	mStatus kbfsmd.MergeStatus, _ *keybase1.LockID) (
	tlf.ID, *RootMetadataSigned, error)

GetForHandle implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) GetForTLF

func (md *MDServerDisk) GetForTLF(ctx context.Context, id tlf.ID,
	bid kbfsmd.BranchID, mStatus kbfsmd.MergeStatus, _ *keybase1.LockID) (
	*RootMetadataSigned, error)

GetForTLF implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) GetForTLFByTime

func (md *MDServerDisk) GetForTLFByTime(
	ctx context.Context, id tlf.ID, serverTime time.Time) (
	*RootMetadataSigned, error)

GetForTLFByTime implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) GetKeyBundles

GetKeyBundles implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) GetLatestHandleForTLF

func (md *MDServerDisk) GetLatestHandleForTLF(ctx context.Context, id tlf.ID) (
	tlf.Handle, error)

GetLatestHandleForTLF implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) GetMerkleRootLatest

func (md *MDServerDisk) GetMerkleRootLatest(
	ctx context.Context, treeID keybase1.MerkleTreeID) (
	root *kbfsmd.MerkleRoot, err error)

GetMerkleRootLatest implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) GetRange

func (md *MDServerDisk) GetRange(ctx context.Context, id tlf.ID,
	bid kbfsmd.BranchID, mStatus kbfsmd.MergeStatus, start, stop kbfsmd.Revision,
	_ *keybase1.LockID) ([]*RootMetadataSigned, error)

GetRange implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) IsConnected

func (md *MDServerDisk) IsConnected() bool

IsConnected implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) Lock

func (*MDServerDisk) Lock(ctx context.Context,
	tlfID tlf.ID, lockID keybase1.LockID) error

Lock (does not) implement the MDServer interface for MDServerDisk.

func (*MDServerDisk) OffsetFromServerTime

func (md *MDServerDisk) OffsetFromServerTime() (time.Duration, bool)

OffsetFromServerTime implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) PruneBranch

func (md *MDServerDisk) PruneBranch(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID) error

PruneBranch implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) Put

Put implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) RefreshAuthToken

func (md *MDServerDisk) RefreshAuthToken(ctx context.Context)

RefreshAuthToken implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) RegisterForUpdate

func (md *MDServerDisk) RegisterForUpdate(ctx context.Context, id tlf.ID,
	currHead kbfsmd.Revision) (<-chan error, error)

RegisterForUpdate implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) ReleaseLock

func (*MDServerDisk) ReleaseLock(ctx context.Context,
	tlfID tlf.ID, lockID keybase1.LockID) error

ReleaseLock (does not) implement the MDServer interface for MDServerDisk.

func (*MDServerDisk) Shutdown

func (md *MDServerDisk) Shutdown()

Shutdown implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) StartImplicitTeamMigration

func (md *MDServerDisk) StartImplicitTeamMigration(
	ctx context.Context, id tlf.ID) (err error)

StartImplicitTeamMigration implements the MDServer interface.

func (*MDServerDisk) TruncateLock

func (md *MDServerDisk) TruncateLock(ctx context.Context, id tlf.ID) (
	bool, error)

TruncateLock implements the MDServer interface for MDServerDisk.

func (*MDServerDisk) TruncateUnlock

func (md *MDServerDisk) TruncateUnlock(ctx context.Context, id tlf.ID) (
	bool, error)

TruncateUnlock implements the MDServer interface for MDServerDisk.

type MDServerMemory

type MDServerMemory struct {
	// contains filtered or unexported fields
}

MDServerMemory just stores metadata objects in memory.

func NewMDServerMemory

func NewMDServerMemory(config mdServerLocalConfig) (*MDServerMemory, error)

NewMDServerMemory constructs a new MDServerMemory object that stores all data in-memory.

func (*MDServerMemory) CancelRegistration

func (md *MDServerMemory) CancelRegistration(_ context.Context, id tlf.ID)

CancelRegistration implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) CheckForRekeys

func (md *MDServerMemory) CheckForRekeys(ctx context.Context) <-chan error

CheckForRekeys implements the MDServer interface.

func (*MDServerMemory) CheckReachability

func (md *MDServerMemory) CheckReachability(ctx context.Context)

CheckReachability implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) DisableRekeyUpdatesForTesting

func (md *MDServerMemory) DisableRekeyUpdatesForTesting()

DisableRekeyUpdatesForTesting implements the MDServer interface.

func (*MDServerMemory) FastForwardBackoff

func (md *MDServerMemory) FastForwardBackoff()

FastForwardBackoff implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) FindNextMD

func (md *MDServerMemory) FindNextMD(
	ctx context.Context, tlfID tlf.ID, rootSeqno keybase1.Seqno) (
	nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
	nextRootSeqno keybase1.Seqno, err error)

FindNextMD implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) GetForHandle

func (md *MDServerMemory) GetForHandle(ctx context.Context, handle tlf.Handle,
	mStatus kbfsmd.MergeStatus, _ *keybase1.LockID) (
	tlf.ID, *RootMetadataSigned, error)

GetForHandle implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) GetForTLF

GetForTLF implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) GetForTLFByTime

func (md *MDServerMemory) GetForTLFByTime(
	ctx context.Context, id tlf.ID, serverTime time.Time) (
	*RootMetadataSigned, error)

GetForTLFByTime implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) GetKeyBundles

GetKeyBundles implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) GetLatestHandleForTLF

func (md *MDServerMemory) GetLatestHandleForTLF(ctx context.Context,
	id tlf.ID) (tlf.Handle, error)

GetLatestHandleForTLF implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) GetMerkleRootLatest

func (md *MDServerMemory) GetMerkleRootLatest(
	ctx context.Context, treeID keybase1.MerkleTreeID) (
	root *kbfsmd.MerkleRoot, err error)

GetMerkleRootLatest implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) GetRange

func (md *MDServerMemory) GetRange(ctx context.Context, id tlf.ID,
	bid kbfsmd.BranchID, mStatus kbfsmd.MergeStatus, start, stop kbfsmd.Revision,
	lockBeforeGet *keybase1.LockID) ([]*RootMetadataSigned, error)

GetRange implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) IsConnected

func (md *MDServerMemory) IsConnected() bool

IsConnected implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) Lock

func (md *MDServerMemory) Lock(ctx context.Context,
	tlfID tlf.ID, lockID keybase1.LockID) error

Lock implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) OffsetFromServerTime

func (md *MDServerMemory) OffsetFromServerTime() (time.Duration, bool)

OffsetFromServerTime implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) PruneBranch

func (md *MDServerMemory) PruneBranch(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID) error

PruneBranch implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) Put

Put implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) RefreshAuthToken

func (md *MDServerMemory) RefreshAuthToken(ctx context.Context)

RefreshAuthToken implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) RegisterForUpdate

func (md *MDServerMemory) RegisterForUpdate(ctx context.Context, id tlf.ID,
	currHead kbfsmd.Revision) (<-chan error, error)

RegisterForUpdate implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) ReleaseLock

func (md *MDServerMemory) ReleaseLock(ctx context.Context,
	tlfID tlf.ID, lockID keybase1.LockID) error

ReleaseLock implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) Shutdown

func (md *MDServerMemory) Shutdown()

Shutdown implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) StartImplicitTeamMigration

func (md *MDServerMemory) StartImplicitTeamMigration(
	ctx context.Context, id tlf.ID) (err error)

StartImplicitTeamMigration implements the MDServer interface.

func (*MDServerMemory) TruncateLock

func (md *MDServerMemory) TruncateLock(ctx context.Context, id tlf.ID) (
	bool, error)

TruncateLock implements the MDServer interface for MDServerMemory.

func (*MDServerMemory) TruncateUnlock

func (md *MDServerMemory) TruncateUnlock(ctx context.Context, id tlf.ID) (
	bool, error)

TruncateUnlock implements the MDServer interface for MDServerMemory.

type MDServerRemote

type MDServerRemote struct {
	// contains filtered or unexported fields
}

MDServerRemote is an implementation of the MDServer interface.

func NewMDServerRemote

func NewMDServerRemote(config Config, srvRemote rpc.Remote,
	rpcLogFactory rpc.LogFactory) *MDServerRemote

NewMDServerRemote returns a new instance of MDServerRemote.

func (*MDServerRemote) CancelRegistration

func (md *MDServerRemote) CancelRegistration(ctx context.Context, id tlf.ID)

CancelRegistration implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) CheckForRekeys

func (md *MDServerRemote) CheckForRekeys(ctx context.Context) <-chan error

CheckForRekeys implements the MDServer interface.

func (*MDServerRemote) CheckReachability

func (md *MDServerRemote) CheckReachability(ctx context.Context)

CheckReachability implements the MDServer interface.

func (*MDServerRemote) DeleteTLFCryptKeyServerHalf

func (md *MDServerRemote) DeleteTLFCryptKeyServerHalf(ctx context.Context,
	uid keybase1.UID, key kbfscrypto.CryptPublicKey,
	serverHalfID kbfscrypto.TLFCryptKeyServerHalfID) (err error)

DeleteTLFCryptKeyServerHalf is an implementation of the KeyServer interface.

func (*MDServerRemote) DisableRekeyUpdatesForTesting

func (md *MDServerRemote) DisableRekeyUpdatesForTesting()

DisableRekeyUpdatesForTesting implements the MDServer interface.

func (*MDServerRemote) FastForwardBackoff

func (md *MDServerRemote) FastForwardBackoff()

FastForwardBackoff implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) FindNextMD

func (md *MDServerRemote) FindNextMD(
	ctx context.Context, tlfID tlf.ID, rootSeqno keybase1.Seqno) (
	nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
	nextRootSeqno keybase1.Seqno, err error)

FindNextMD implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) FolderNeedsRekey

func (md *MDServerRemote) FolderNeedsRekey(ctx context.Context,
	arg keybase1.FolderNeedsRekeyArg) error

FolderNeedsRekey implements the MetadataUpdateProtocol interface.

func (*MDServerRemote) FoldersNeedRekey

func (md *MDServerRemote) FoldersNeedRekey(ctx context.Context,
	requests []keybase1.RekeyRequest) error

FoldersNeedRekey implements the MetadataUpdateProtocol interface.

func (*MDServerRemote) GetForHandle

func (md *MDServerRemote) GetForHandle(ctx context.Context,
	handle tlf.Handle, mStatus kbfsmd.MergeStatus, lockBeforeGet *keybase1.LockID) (
	tlfID tlf.ID, rmds *RootMetadataSigned, err error)

GetForHandle implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) GetForTLF

func (md *MDServerRemote) GetForTLF(ctx context.Context, id tlf.ID,
	bid kbfsmd.BranchID, mStatus kbfsmd.MergeStatus, lockBeforeGet *keybase1.LockID) (rmds *RootMetadataSigned, err error)

GetForTLF implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) GetForTLFByTime

func (md *MDServerRemote) GetForTLFByTime(
	ctx context.Context, id tlf.ID, serverTime time.Time) (
	rmds *RootMetadataSigned, err error)

GetForTLFByTime implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) GetKeyBundles

GetKeyBundles implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) GetLatestHandleForTLF

func (md *MDServerRemote) GetLatestHandleForTLF(ctx context.Context, id tlf.ID) (
	handle tlf.Handle, err error)

GetLatestHandleForTLF implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) GetMerkleRootLatest

func (md *MDServerRemote) GetMerkleRootLatest(
	ctx context.Context, treeID keybase1.MerkleTreeID) (
	root *kbfsmd.MerkleRoot, err error)

GetMerkleRootLatest implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) GetRange

func (md *MDServerRemote) GetRange(ctx context.Context, id tlf.ID,
	bid kbfsmd.BranchID, mStatus kbfsmd.MergeStatus, start, stop kbfsmd.Revision,
	lockBeforeGet *keybase1.LockID) (rmdses []*RootMetadataSigned, err error)

GetRange implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) GetTLFCryptKeyServerHalf

func (md *MDServerRemote) GetTLFCryptKeyServerHalf(ctx context.Context,
	serverHalfID kbfscrypto.TLFCryptKeyServerHalfID,
	cryptKey kbfscrypto.CryptPublicKey) (
	serverHalf kbfscrypto.TLFCryptKeyServerHalf, err error)

GetTLFCryptKeyServerHalf is an implementation of the KeyServer interface.

func (*MDServerRemote) HandlerName

func (*MDServerRemote) HandlerName() string

HandlerName implements the ConnectionHandler interface.

func (*MDServerRemote) IsConnected

func (md *MDServerRemote) IsConnected() bool

IsConnected implements the MDServer interface for MDServerLocal

func (*MDServerRemote) Lock

func (md *MDServerRemote) Lock(ctx context.Context,
	tlfID tlf.ID, lockID keybase1.LockID) error

Lock implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) MetadataUpdate

func (md *MDServerRemote) MetadataUpdate(_ context.Context, arg keybase1.MetadataUpdateArg) error

MetadataUpdate implements the MetadataUpdateProtocol interface.

func (*MDServerRemote) OffsetFromServerTime

func (md *MDServerRemote) OffsetFromServerTime() (time.Duration, bool)

OffsetFromServerTime implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) OnConnect

func (md *MDServerRemote) OnConnect(ctx context.Context,
	conn *rpc.Connection, client rpc.GenericClient,
	server *rpc.Server) (err error)

OnConnect implements the ConnectionHandler interface.

func (*MDServerRemote) OnConnectError

func (md *MDServerRemote) OnConnectError(err error, wait time.Duration)

OnConnectError implements the ConnectionHandler interface.

func (*MDServerRemote) OnDisconnected

func (md *MDServerRemote) OnDisconnected(ctx context.Context,
	status rpc.DisconnectStatus)

OnDisconnected implements the ConnectionHandler interface.

func (*MDServerRemote) OnDoCommandError

func (md *MDServerRemote) OnDoCommandError(err error, wait time.Duration)

OnDoCommandError implements the ConnectionHandler interface.

func (*MDServerRemote) PruneBranch

func (md *MDServerRemote) PruneBranch(
	ctx context.Context, id tlf.ID, bid kbfsmd.BranchID) (err error)

PruneBranch implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) Put

func (md *MDServerRemote) Put(ctx context.Context, rmds *RootMetadataSigned,
	extra kbfsmd.ExtraMetadata, lockContext *keybase1.LockContext,
	priority keybase1.MDPriority) (err error)

Put implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) PutTLFCryptKeyServerHalves

func (md *MDServerRemote) PutTLFCryptKeyServerHalves(ctx context.Context,
	keyServerHalves kbfsmd.UserDeviceKeyServerHalves) (err error)

PutTLFCryptKeyServerHalves is an implementation of the KeyServer interface.

func (*MDServerRemote) RefreshAuthToken

func (md *MDServerRemote) RefreshAuthToken(ctx context.Context)

RefreshAuthToken implements the AuthTokenRefreshHandler interface.

func (*MDServerRemote) RegisterForUpdate

func (md *MDServerRemote) RegisterForUpdate(ctx context.Context, id tlf.ID,
	currHead kbfsmd.Revision) (<-chan error, error)

RegisterForUpdate implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) ReleaseLock

func (md *MDServerRemote) ReleaseLock(ctx context.Context,
	tlfID tlf.ID, lockID keybase1.LockID) error

ReleaseLock implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) RemoteAddress

func (md *MDServerRemote) RemoteAddress() string

RemoteAddress returns the remote mdserver this client is talking to

func (*MDServerRemote) ShouldRetry

func (md *MDServerRemote) ShouldRetry(name string, err error) bool

ShouldRetry implements the ConnectionHandler interface.

func (*MDServerRemote) ShouldRetryOnConnect

func (md *MDServerRemote) ShouldRetryOnConnect(err error) bool

ShouldRetryOnConnect implements the ConnectionHandler interface.

func (*MDServerRemote) Shutdown

func (md *MDServerRemote) Shutdown()

Shutdown implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) StartImplicitTeamMigration

func (md *MDServerRemote) StartImplicitTeamMigration(
	ctx context.Context, id tlf.ID) (err error)

StartImplicitTeamMigration implements the MDServer interface.

func (*MDServerRemote) TruncateLock

func (md *MDServerRemote) TruncateLock(ctx context.Context, id tlf.ID) (
	locked bool, err error)

TruncateLock implements the MDServer interface for MDServerRemote.

func (*MDServerRemote) TruncateUnlock

func (md *MDServerRemote) TruncateUnlock(ctx context.Context, id tlf.ID) (
	unlocked bool, err error)

TruncateUnlock implements the MDServer interface for MDServerRemote.

type MDUpdateInvertError

type MDUpdateInvertError struct {
	// contains filtered or unexported fields
}

MDUpdateInvertError indicates that we tried to apply a revision that was not the next in line.

func (MDUpdateInvertError) Error

func (e MDUpdateInvertError) Error() string

Error implements the error interface for MDUpdateInvertError.

type MDWriteNeededInRequest

type MDWriteNeededInRequest struct {
}

MDWriteNeededInRequest indicates that the system needs MD write permissions to successfully complete an operation, so it should retry in mdWrite mode.

func (MDWriteNeededInRequest) Error

func (e MDWriteNeededInRequest) Error() string

Error implements the error interface for MDWriteNeededInRequest

type MDWrittenAfterRevokeError

type MDWrittenAfterRevokeError struct {
	// contains filtered or unexported fields
}

MDWrittenAfterRevokeError indicates that we failed to verify an MD revision because it was written after the last valid revision that the corresponding device could have written.

func (MDWrittenAfterRevokeError) Error

Error implements the Error interface for MDWrittenAfterRevokeError.

type MeterSnapshot

type MeterSnapshot struct {
	// contains filtered or unexported fields
}

MeterSnapshot is a read-only copy of another Meter.

func (*MeterSnapshot) Count

func (m *MeterSnapshot) Count() int64

Count returns the count of events at the time the snapshot was taken.

func (*MeterSnapshot) Mark

func (*MeterSnapshot) Mark(n int64)

Mark panics.

func (*MeterSnapshot) Rate1

func (m *MeterSnapshot) Rate1() float64

Rate1 returns the one-minute moving average rate of events per second at the time the snapshot was taken.

func (*MeterSnapshot) Rate15

func (m *MeterSnapshot) Rate15() float64

Rate15 returns the fifteen-minute moving average rate of events per second at the time the snapshot was taken.

func (*MeterSnapshot) Rate5

func (m *MeterSnapshot) Rate5() float64

Rate5 returns the five-minute moving average rate of events per second at the time the snapshot was taken.

func (*MeterSnapshot) RateMean

func (m *MeterSnapshot) RateMean() float64

RateMean returns the meter's mean rate of events per second at the time the snapshot was taken.

func (*MeterSnapshot) Snapshot

func (m *MeterSnapshot) Snapshot() metrics.Meter

Snapshot returns the snapshot.

type MeterStatus

type MeterStatus struct {
	Minutes1  float64
	Minutes5  float64
	Minutes15 float64
	Count     int64
}

MeterStatus represents the status of a rate meter.

type NameExistsError

type NameExistsError struct {
	Name string
}

NameExistsError indicates that the user tried to create an entry for a name that already existed in a subdirectory.

func (NameExistsError) Error

func (e NameExistsError) Error() string

Error implements the error interface for NameExistsError

type NameTooLongError

type NameTooLongError struct {
	// contains filtered or unexported fields
}

NameTooLongError indicates that the user tried to write a directory entry name that would be bigger than KBFS's supported size.

func (NameTooLongError) Error

func (e NameTooLongError) Error() string

Error implements the error interface for NameTooLongError.

type NaïveStaller

type NaïveStaller struct {
	// contains filtered or unexported fields
}

NaïveStaller is used to stall certain ops in BlockServer or MDOps. Unlike StallBlockOp and StallMDOp which provides a way to precisely control which particular op is stalled by passing in ctx with corresponding stallKey, NaïveStaller simply stalls all instances of specified op.

func NewNaïveStaller

func NewNaïveStaller(config Config) *NaïveStaller

NewNaïveStaller returns a new NaïveStaller

func (*NaïveStaller) StallBlockOp

func (s *NaïveStaller) StallBlockOp(stalledOp StallableBlockOp, maxStalls int)

StallBlockOp wraps the internal BlockServer so that all subsequent stalledOp will be stalled. This can be undone by calling UndoStallBlockOp.

func (*NaïveStaller) StallMDOp

func (s *NaïveStaller) StallMDOp(stalledOp StallableMDOp, maxStalls int,
	stallDelegate bool)

StallMDOp wraps the internal MDOps so that all subsequent stalledOp will be stalled. This can be undone by calling UndoStallMDOp.

func (*NaïveStaller) UndoStallBlockOp

func (s *NaïveStaller) UndoStallBlockOp(stalledOp StallableBlockOp)

UndoStallBlockOp reverts StallBlockOp so that future stalledOp are not stalled anymore. It also unstalls any stalled stalledOp. StallBlockOp should have been called upon stalledOp, otherwise this would panic.

func (*NaïveStaller) UndoStallMDOp

func (s *NaïveStaller) UndoStallMDOp(stalledOp StallableMDOp)

UndoStallMDOp reverts StallMDOp so that future stalledOp are not stalled anymore. It also unstalls any stalled stalledOp. StallMDOp should have been called upon stalledOp, otherwise this would panic.

func (*NaïveStaller) UnstallOneBlockOp

func (s *NaïveStaller) UnstallOneBlockOp(stalledOp StallableBlockOp)

UnstallOneBlockOp unstalls exactly one stalled stalledOp. StallBlockOp should have been called upon stalledOp, otherwise this would panic.

func (*NaïveStaller) UnstallOneMDOp

func (s *NaïveStaller) UnstallOneMDOp(stalledOp StallableMDOp)

UnstallOneMDOp unstalls exactly one stalled stalledOp. StallMDOp should have been called upon stalledOp, otherwise this would panic.

func (*NaïveStaller) WaitForStallBlockOp

func (s *NaïveStaller) WaitForStallBlockOp(stalledOp StallableBlockOp)

WaitForStallBlockOp blocks until stalledOp is stalled. StallBlockOp should have been called upon stalledOp, otherwise this would panic.

func (*NaïveStaller) WaitForStallMDOp

func (s *NaïveStaller) WaitForStallMDOp(stalledOp StallableMDOp)

WaitForStallMDOp blocks until stalledOp is stalled. StallMDOp should have been called upon stalledOp, otherwise this would panic.

type NeedOtherRekeyError

type NeedOtherRekeyError struct {
	Tlf tlf.CanonicalName
	Err error
}

NeedOtherRekeyError indicates that the folder in question needs to be rekeyed for the local device, and can only done so by one of the other users.

func (NeedOtherRekeyError) Error

func (e NeedOtherRekeyError) Error() string

Error implements the error interface for NeedOtherRekeyError

func (NeedOtherRekeyError) ToStatus

func (e NeedOtherRekeyError) ToStatus() keybase1.Status

ToStatus exports error to status

type NeedSelfRekeyError

type NeedSelfRekeyError struct {
	Tlf tlf.CanonicalName
	Err error
}

NeedSelfRekeyError indicates that the folder in question needs to be rekeyed for the local device, and can be done so by one of the other user's devices.

func (NeedSelfRekeyError) Error

func (e NeedSelfRekeyError) Error() string

Error implements the error interface for NeedSelfRekeyError

func (NeedSelfRekeyError) ToStatus

func (e NeedSelfRekeyError) ToStatus() keybase1.Status

ToStatus exports error to status

type NewDataVersionError

type NewDataVersionError struct {
	DataVer DataVer
	// contains filtered or unexported fields
}

NewDataVersionError indicates that the data at the given path has been written using a new data version that our client doesn't understand.

func (NewDataVersionError) Error

func (e NewDataVersionError) Error() string

Error implements the error interface for NewDataVersionError.

type NextMDNotCachedError

type NextMDNotCachedError struct {
	TlfID     tlf.ID
	RootSeqno keybase1.Seqno
}

NextMDNotCachedError indicates we haven't cached the next MD after the given Merkle seqno.

func (NextMDNotCachedError) Error

func (e NextMDNotCachedError) Error() string

Error implements the Error interface for NextMDNotCachedError.

type NoCancellationDelayerError

type NoCancellationDelayerError struct{}

NoCancellationDelayerError is returned when EnableDelayedCancellationWithGracePeriod or ExitCritical are called on a ctx without Critical Awareness

func (NoCancellationDelayerError) Error

type NoChainFoundError

type NoChainFoundError struct {
	// contains filtered or unexported fields
}

NoChainFoundError indicates that a conflict resolution chain corresponding to the given pointer could not be found.

func (NoChainFoundError) Error

func (e NoChainFoundError) Error() string

Error implements the error interface for NoChainFoundError.

type NoCurrentSessionError

type NoCurrentSessionError struct {
}

NoCurrentSessionError indicates that the daemon has no current session. This is basically a wrapper for session.ErrNoSession, needed to give the correct return error code to the OS.

func (NoCurrentSessionError) Error

func (e NoCurrentSessionError) Error() string

Error implements the error interface for NoCurrentSessionError.

type NoKeysError

type NoKeysError struct{}

NoKeysError indicates that no keys were provided for a decryption allowing multiple device keys

func (NoKeysError) Error

func (e NoKeysError) Error() string

type NoMergedMDError

type NoMergedMDError struct {
	// contains filtered or unexported fields
}

NoMergedMDError indicates that no MDs for this folder have been created yet.

func (NoMergedMDError) Error

func (e NoMergedMDError) Error() string

Error implements the error interface for NoMergedMDError.

type NoSigChainError

type NoSigChainError struct {
	User kbname.NormalizedUsername
}

NoSigChainError means that a user we were trying to identify does not have a sigchain.

func (NoSigChainError) Error

func (e NoSigChainError) Error() string

Error implements the error interface for NoSigChainError.

type NoSuchBlockError

type NoSuchBlockError struct {
	ID kbfsblock.ID
}

NoSuchBlockError indicates that a block for the associated ID doesn't exist.

func (NoSuchBlockError) Error

func (e NoSuchBlockError) Error() string

Error implements the error interface for NoSuchBlockError

type NoSuchFolderListError

type NoSuchFolderListError struct {
	Name     string
	PrivName string
	PubName  string
}

NoSuchFolderListError indicates that the user tried to access a subdirectory of /keybase that doesn't exist.

func (NoSuchFolderListError) Error

func (e NoSuchFolderListError) Error() string

Error implements the error interface for NoSuchFolderListError

type NoSuchMDError

type NoSuchMDError struct {
	Tlf tlf.ID
	Rev kbfsmd.Revision
	BID kbfsmd.BranchID
}

NoSuchMDError indicates that there is no MD object for the given folder, revision, and merged status.

func (NoSuchMDError) Error

func (e NoSuchMDError) Error() string

Error implements the error interface for NoSuchMDError

type NoSuchNameError

type NoSuchNameError struct {
	Name string
}

NoSuchNameError indicates that the user tried to access a subdirectory entry that doesn't exist.

func (NoSuchNameError) Error

func (e NoSuchNameError) Error() string

Error implements the error interface for NoSuchNameError

type NoSuchTeamError

type NoSuchTeamError struct {
	Input string
}

NoSuchTeamError indicates that the given team couldn't be resolved.

func (NoSuchTeamError) Error

func (e NoSuchTeamError) Error() string

Error implements the error interface for NoSuchTeamError

type NoSuchTlfHandleError

type NoSuchTlfHandleError struct {
	ID tlf.ID
}

NoSuchTlfHandleError indicates we were unable to resolve a folder ID to a folder handle.

func (NoSuchTlfHandleError) Error

func (e NoSuchTlfHandleError) Error() string

Error implements the error interface for NoSuchTlfHandleError

type NoSuchTlfIDError

type NoSuchTlfIDError struct {
	// contains filtered or unexported fields
}

NoSuchTlfIDError indicates we were unable to resolve a folder handle to a folder ID.

func (NoSuchTlfIDError) Error

func (e NoSuchTlfIDError) Error() string

Error implements the error interface for NoSuchTlfIDError

type NoSuchUserError

type NoSuchUserError struct {
	Input string
}

NoSuchUserError indicates that the given user couldn't be resolved.

func (NoSuchUserError) Error

func (e NoSuchUserError) Error() string

Error implements the error interface for NoSuchUserError

func (NoSuchUserError) ToStatus

func (e NoSuchUserError) ToStatus() keybase1.Status

ToStatus implements the keybase1.ToStatusAble interface for NoSuchUserError

type NoUpdatesWhileDirtyError

type NoUpdatesWhileDirtyError struct{}

NoUpdatesWhileDirtyError indicates that updates aren't being accepted while a TLF is locally dirty.

func (NoUpdatesWhileDirtyError) Error

func (e NoUpdatesWhileDirtyError) Error() string

Error implements the error interface for NoUpdatesWhileDirtyError.

type Node

type Node interface {
	// GetID returns the ID of this Node. This should be used as a
	// map key instead of the Node itself.
	GetID() NodeID
	// GetFolderBranch returns the folder ID and branch for this Node.
	GetFolderBranch() FolderBranch
	// GetBasename returns the current basename of the node, or ""
	// if the node has been unlinked.
	GetBasename() string
	// Readonly returns true if KBFS should outright reject any write
	// attempts on data or directory structures of this node.  Though
	// note that even if it returns false, KBFS can reject writes to
	// the node for other reasons, such as TLF permissions.  An
	// implementation that wraps another `Node` (`inner`) must return
	// `inner.Readonly()` if it decides not to return `true` on its
	// own.
	Readonly(ctx context.Context) bool
	// ShouldCreateMissedLookup is called for Nodes representing
	// directories, whenever `name` is looked up but is not found in
	// the directory.  If the Node decides a new entry should be
	// created matching this lookup, it should return `true` as well
	// as a context to use for the creation, the type of the new entry
	// and the symbolic link contents if the entry is a Sym; the
	// caller should then create this entry.  Otherwise it should
	// return false.  It may return the type `FakeDir` to indicate
	// that the caller should pretend the entry exists, even if it
	// really does not.  An implementation that wraps another `Node`
	// (`inner`) must return `inner.ShouldCreateMissedLookup()` if it
	// decides not to return `true` on its own.
	ShouldCreateMissedLookup(ctx context.Context, name string) (
		shouldCreate bool, newCtx context.Context, et EntryType, sympath string)
	// ShouldRetryOnDirRead is called for Nodes representing
	// directories, whenever a `Lookup` or `GetDirChildren` is done on
	// them.  It should return true to instruct the caller that it
	// should re-sync its view of the directory and retry the
	// operation.
	ShouldRetryOnDirRead(ctx context.Context) bool
	// RemoveDir is called on a `Node` before going through the normal
	// `RemoveDir` flow, to give the Node a chance to handle it in a
	// custom way.  If the `Node` handles it internally, it should
	// return `true`.
	RemoveDir(ctx context.Context, dirName string) (
		removeHandled bool, err error)
	// WrapChild returns a wrapped version of child, if desired, to
	// add custom behavior to the child node. An implementation that
	// wraps another `Node` (`inner`) must first call
	// `inner.WrapChild(child)` before performing its own wrapping
	// operation, to ensure that all wrapping is preserved and that it
	// happens in the correct order.
	WrapChild(child Node) Node
	// Unwrap returns the initial, unwrapped Node that was used to
	// create this Node.
	Unwrap() Node
	// GetFS returns a file system interface that, if non-nil, should
	// be used to satisfy any directory-related calls on this Node,
	// instead of the standard, block-based method of acessing data.
	// The provided context will be used, if possible, for any
	// subsequent calls on the file system.
	GetFS(ctx context.Context) billy.Filesystem
	// GetFile returns a file interface that, if non-nil, should be
	// used to satisfy any file-related calls on this Node, instead of
	// the standard, block-based method of accessing data.  The
	// provided context will be used, if possible, for any subsequent
	// calls on the file.
	GetFile(ctx context.Context) billy.File
	// EntryType is the type of the entry represented by this node.
	EntryType() EntryType
	// GetBlockID returns the block ID of the node.
	GetBlockID() kbfsblock.ID
}

Node represents a direct pointer to a file or directory in KBFS. It is somewhat like an inode in a regular file system. Users of KBFS can use Node as a handle when accessing files or directories they have previously looked up.

func GetRootNodeForTest

func GetRootNodeForTest(
	ctx context.Context, config Config, name string,
	t tlf.Type) (Node, error)

GetRootNodeForTest gets the root node for the given TLF name, which must be canonical, creating it if necessary.

func GetRootNodeOrBust

func GetRootNodeOrBust(
	ctx context.Context, t logger.TestLogBackend,
	config Config, name string, ty tlf.Type) Node

GetRootNodeOrBust gets the root node for the given TLF name, which must be canonical, creating it if necessary, and failing if there's an error.

type NodeCache

type NodeCache interface {
	// GetOrCreate either makes a new Node for the given
	// BlockPointer, or returns an existing one. TODO: If we ever
	// support hard links, we will have to revisit the "name" and
	// "parent" parameters here.  name must not be empty. Returns
	// an error if parent cannot be found.
	GetOrCreate(
		ptr BlockPointer, name string, parent Node, et EntryType) (Node, error)
	// Get returns the Node associated with the given ptr if one
	// already exists.  Otherwise, it returns nil.
	Get(ref BlockRef) Node
	// UpdatePointer updates the BlockPointer for the corresponding
	// Node.  NodeCache ignores this call when oldRef is not cached in
	// any Node. Returns whether the ID of the node that was updated,
	// or `nil` if nothing was updated.
	UpdatePointer(oldRef BlockRef, newPtr BlockPointer) NodeID
	// Move swaps the parent node for the corresponding Node, and
	// updates the node's name.  NodeCache ignores the call when ptr
	// is not cached.  If newParent is nil, it treats the ptr's
	// corresponding node as being unlinked from the old parent
	// completely. If successful, it returns a function that can be
	// called to undo the effect of the move (or `nil` if nothing
	// needs to be done); if newParent cannot be found, it returns an
	// error and a `nil` undo function.
	Move(ref BlockRef, newParent Node, newName string) (
		undoFn func(), err error)
	// Unlink set the corresponding node's parent to nil and caches
	// the provided path in case the node is still open. NodeCache
	// ignores the call when ptr is not cached.  The path is required
	// because the caller may have made changes to the parent nodes
	// already that shouldn't be reflected in the cached path.  It
	// returns a function that can be called to undo the effect of the
	// unlink (or `nil` if nothing needs to be done).
	Unlink(ref BlockRef, oldPath path, oldDe DirEntry) (undoFn func())
	// IsUnlinked returns whether `Unlink` has been called for the
	// reference behind this node.
	IsUnlinked(node Node) bool
	// UnlinkedDirEntry returns a directory entry if `Unlink` has been
	// called for the reference behind this node.
	UnlinkedDirEntry(node Node) DirEntry
	// UpdateUnlinkedDirEntry modifies a cached directory entry for a
	// node that has already been unlinked.
	UpdateUnlinkedDirEntry(node Node, newDe DirEntry)
	// PathFromNode creates the path up to a given Node.
	PathFromNode(node Node) path
	// AllNodes returns the complete set of nodes currently in the
	// cache.  The returned Nodes are not wrapped, and shouldn't be
	// used for data access.
	AllNodes() []Node
	// AllNodeChildren returns the complete set of nodes currently in
	// the cache, for which the given node `n` is a parent (direct or
	// indirect).  The returned slice does not include `n` itself.
	// The returned Nodes are not wrapped, and shouldn't be used for
	// data access.
	AllNodeChildren(n Node) []Node
	// AddRootWrapper adds a new wrapper function that will be applied
	// whenever a root Node is created.
	AddRootWrapper(func(Node) Node)
}

NodeCache holds Nodes, and allows libkbfs to update them when things change about the underlying KBFS blocks. It is probably most useful to instantiate this on a per-folder-branch basis, so that it can create a Path with the correct DirId and Branch name.

type NodeChange

type NodeChange struct {
	Node Node
	// Basenames of entries added/removed.
	DirUpdated  []string
	FileUpdated []WriteRange
}

NodeChange represents a change made to a node as part of an atomic file system operation.

type NodeID

type NodeID interface {
	// ParentID returns the NodeID of the directory containing the
	// pointed-to file or directory, or nil if none exists.
	ParentID() NodeID
}

NodeID is a unique but transient ID for a Node. That is, two Node objects in memory at the same time represent the same file or directory if and only if their NodeIDs are equal (by pointer).

type NodeMetadata

type NodeMetadata struct {
	// LastWriterUnverified is the last writer of this
	// node according to the last writer of the TLF.
	// A more thorough check is possible in the future.
	LastWriterUnverified kbname.NormalizedUsername
	BlockInfo            BlockInfo
	PrefetchStatus       PrefetchStatus
}

NodeMetadata has metadata about a node needed for higher level operations.

type NodeNotFoundError

type NodeNotFoundError struct {
	// contains filtered or unexported fields
}

NodeNotFoundError indicates that we tried to find a node for the given BlockPointer and failed.

func (NodeNotFoundError) Error

func (e NodeNotFoundError) Error() string

Error implements the error interface for NodeNotFoundError.

type NoopBlockMetadataStore

type NoopBlockMetadataStore struct{}

NoopBlockMetadataStore satisfies the BlockMetadataStore interface but does nothing.

func (NoopBlockMetadataStore) GetMetadata

func (NoopBlockMetadataStore) GetMetadata(ctx context.Context,
	blockID kbfsblock.ID) (value BlockMetadataValue, err error)

GetMetadata always returns ldberrors.ErrNotFound.

func (NoopBlockMetadataStore) Shutdown

func (NoopBlockMetadataStore) Shutdown()

Shutdown does nothing.

func (NoopBlockMetadataStore) UpdateMetadata

func (NoopBlockMetadataStore) UpdateMetadata(ctx context.Context,
	blockID kbfsblock.ID, updater BlockMetadataUpdater) error

UpdateMetadata returns nil error but does nothing.

type NotDirBlockError

type NotDirBlockError struct {
	// contains filtered or unexported fields
}

NotDirBlockError indicates that a file block was expected but a block of a different type was found.

ptr and branch should be filled in, but p may be empty.

func (NotDirBlockError) Error

func (e NotDirBlockError) Error() string

type NotDirError

type NotDirError struct {
	// contains filtered or unexported fields
}

NotDirError indicates that the user tried to perform a dir-specific operation on something that isn't a directory.

func (NotDirError) Error

func (e NotDirError) Error() string

Error implements the error interface for NotDirError

type NotDirectFileBlockError

type NotDirectFileBlockError struct {
}

NotDirectFileBlockError indicates that a direct file block was expected, but something else (e.g., an indirect file block) was given instead.

func (NotDirectFileBlockError) Error

func (e NotDirectFileBlockError) Error() string

type NotFileBlockError

type NotFileBlockError struct {
	// contains filtered or unexported fields
}

NotFileBlockError indicates that a file block was expected but a block of a different type was found.

ptr and branch should be filled in, but p may be empty.

func (NotFileBlockError) Error

func (e NotFileBlockError) Error() string

type NotFileError

type NotFileError struct {
	// contains filtered or unexported fields
}

NotFileError indicates that the user tried to perform a file-specific operation on something that isn't a file.

func (NotFileError) Error

func (e NotFileError) Error() string

Error implements the error interface for NotFileError

type NotPermittedWhileDirtyError

type NotPermittedWhileDirtyError struct {
}

NotPermittedWhileDirtyError indicates that some operation failed because of outstanding dirty files, and may be retried later.

func (NotPermittedWhileDirtyError) Error

Error implements the error interface for NotPermittedWhileDirtyError.

type Notifier

type Notifier interface {
	// RegisterForChanges declares that the given Observer wants to
	// subscribe to updates for the given top-level folders.
	RegisterForChanges(folderBranches []FolderBranch, obs Observer) error
	// UnregisterFromChanges declares that the given Observer no
	// longer wants to subscribe to updates for the given top-level
	// folders.
	UnregisterFromChanges(folderBranches []FolderBranch, obs Observer) error
}

Notifier notifies registrants of directory changes

type Observer

type Observer interface {
	// LocalChange announces that the file at this Node has been
	// updated locally, but not yet saved at the server.
	LocalChange(ctx context.Context, node Node, write WriteRange)
	// BatchChanges announces that the nodes have all been updated
	// together atomically.  Each NodeChange in `changes` affects the
	// same top-level folder and branch. `allAffectedNodeIDs` is a
	// list of all the nodes that had their underlying data changed,
	// even if it wasn't an user-visible change (e.g., if a
	// subdirectory was updated, the directory block for the TLF root
	// is updated but that wouldn't be visible to a user).
	BatchChanges(ctx context.Context, changes []NodeChange,
		allAffectedNodeIDs []NodeID)
	// TlfHandleChange announces that the handle of the corresponding
	// folder branch has changed, likely due to previously-unresolved
	// assertions becoming resolved.  This indicates that the listener
	// should switch over any cached paths for this folder-branch to
	// the new name.  Nodes that were acquired under the old name will
	// still continue to work, but new lookups on the old name may
	// either encounter alias errors or entirely new TLFs (in the case
	// of conflicts).
	TlfHandleChange(ctx context.Context, newHandle *TlfHandle)
}

Observer can be notified that there is an available update for a given directory. The notification callbacks should not block, or make any calls to the Notifier interface. Nodes passed to the observer should not be held past the end of the notification callback.

type OfflineArchivedError

type OfflineArchivedError struct {
	// contains filtered or unexported fields
}

OfflineArchivedError indicates trying to access archived data while offline.

func (OfflineArchivedError) Error

func (e OfflineArchivedError) Error() string

Error implements the Error interface for OfflineArchivedError.

type OfflineUnsyncedError

type OfflineUnsyncedError struct {
	// contains filtered or unexported fields
}

OfflineUnsyncedError indicates trying to access unsynced data while offline.

func (OfflineUnsyncedError) Error

func (e OfflineUnsyncedError) Error() string

Error implements the Error interface for OfflineUnsyncedError.

type Offset

type Offset interface {
	Equals(other Offset) bool
	Less(other Offset) bool
}

Offset is a generic representation of an offset to an indirect pointer within an indirect Block.

type OngoingWorkLimiter

type OngoingWorkLimiter struct {
	// contains filtered or unexported fields
}

OngoingWorkLimiter limits maximum number of routines that can work on a same type of thing at the same time. For example, it can be used for limiting number of ongoing rekeys.

func NewOngoingWorkLimiter

func NewOngoingWorkLimiter(maxNumOngoingWorks int) *OngoingWorkLimiter

NewOngoingWorkLimiter creates a new *OngoingWorkLimiter with capacity of maxNumOngoingWorks.

func (*OngoingWorkLimiter) Done

func (owl *OngoingWorkLimiter) Done()

Done tells the limiter that the caller is done working on the thing, and somebody else is free to start work.

func (*OngoingWorkLimiter) WaitToStart

func (owl *OngoingWorkLimiter) WaitToStart(ctx context.Context) error

WaitToStart blocks until the limiter would allow one more routine to start working on the thing.

type OpCommon

type OpCommon struct {
	RefBlocks   []BlockPointer `codec:"r,omitempty"`
	UnrefBlocks []BlockPointer `codec:"u,omitempty"`
	Updates     []blockUpdate  `codec:"o,omitempty"`

	codec.UnknownFieldSetHandler
	// contains filtered or unexported fields
}

OpCommon are data structures needed by all ops. It is only exported for serialization purposes.

func (*OpCommon) AddRefBlock

func (oc *OpCommon) AddRefBlock(ptr BlockPointer)

AddRefBlock adds this block to the list of newly-referenced blocks for this op.

func (*OpCommon) AddSelfUpdate

func (oc *OpCommon) AddSelfUpdate(ptr BlockPointer)

AddSelfUpdate implements the op interface for OpCommon -- see the comment in op.

func (*OpCommon) AddUnrefBlock

func (oc *OpCommon) AddUnrefBlock(ptr BlockPointer)

AddUnrefBlock adds this block to the list of newly-unreferenced blocks for this op.

func (*OpCommon) AddUpdate

func (oc *OpCommon) AddUpdate(oldPtr BlockPointer, newPtr BlockPointer)

AddUpdate adds a mapping from an old block to the new version of that block, for this op.

func (*OpCommon) DelRefBlock

func (oc *OpCommon) DelRefBlock(ptr BlockPointer)

DelRefBlock removes the first reference of the given block from the list of newly-referenced blocks for this op.

func (*OpCommon) DelUnrefBlock

func (oc *OpCommon) DelUnrefBlock(ptr BlockPointer)

DelUnrefBlock removes the first unreference of the given block from the list of unreferenced blocks for this op.

func (*OpCommon) Refs

func (oc *OpCommon) Refs() []BlockPointer

Refs returns a slice containing all the blocks that were initially referenced during this op.

func (*OpCommon) ToEditNotification

ToEditNotification implements the op interface for OpCommon.

func (*OpCommon) Unrefs

func (oc *OpCommon) Unrefs() []BlockPointer

Unrefs returns a slice containing all the blocks that were unreferenced during this op.

type OpSummary

type OpSummary struct {
	Op      string
	Refs    []string
	Unrefs  []string
	Updates map[string]string
}

OpSummary describes the changes performed by a single op, and is suitable for encoding directly as JSON.

type OpsCantHandleFavorite

type OpsCantHandleFavorite struct {
	Msg string
}

OpsCantHandleFavorite means that folderBranchOps wasn't able to deal with a favorites request.

func (OpsCantHandleFavorite) Error

func (e OpsCantHandleFavorite) Error() string

Error implements the error interface for OpsCantHandleFavorite.

type OutdatedVersionError

type OutdatedVersionError struct {
}

OutdatedVersionError indicates that we have encountered some new data version we don't understand, and the user should be prompted to upgrade.

func (OutdatedVersionError) Error

func (e OutdatedVersionError) Error() string

Error implements the error interface for OutdatedVersionError.

type OverQuotaWarning

type OverQuotaWarning struct {
	UsageBytes int64
	LimitBytes int64
}

OverQuotaWarning indicates that the user is over their quota, and is being slowed down by the server.

func (OverQuotaWarning) Error

func (w OverQuotaWarning) Error() string

Error implements the error interface for OverQuotaWarning.

type PaddedBlockReadError

type PaddedBlockReadError struct {
	ActualLen   int
	ExpectedLen int
}

PaddedBlockReadError occurs if the number of bytes read do not equal the number of bytes specified.

func (PaddedBlockReadError) Error

func (e PaddedBlockReadError) Error() string

Error implements the error interface of PaddedBlockReadError.

type ParentNodeNotFoundError

type ParentNodeNotFoundError struct {
	// contains filtered or unexported fields
}

ParentNodeNotFoundError indicates that we tried to update a Node's parent with a BlockPointer that we don't yet know about.

func (ParentNodeNotFoundError) Error

func (e ParentNodeNotFoundError) Error() string

Error implements the error interface for ParentNodeNotFoundError.

type PathType

type PathType string

PathType describes the types for different paths

const (
	// KeybasePathType is the keybase root (like /keybase)
	KeybasePathType PathType = "keybase"
	// PublicPathType is the keybase public folder list (like /keybase/public)
	PublicPathType PathType = "public"
	// PrivatePathType is the keybase private folder list (like
	// /keybase/private)
	PrivatePathType PathType = "private"
	// SingleTeamPathType is the keybase team folder list (like /keybase/teams)
	SingleTeamPathType PathType = "team"
)

type PrefetchStatus

type PrefetchStatus int

PrefetchStatus denotes the prefetch status of a block.

const (
	// NoPrefetch represents an entry that hasn't been prefetched.
	NoPrefetch PrefetchStatus = iota
	// TriggeredPrefetch represents a block for which prefetching has been
	// triggered, but the full tree has not been completed.
	TriggeredPrefetch
	// FinishedPrefetch represents a block whose full subtree is synced.
	FinishedPrefetch
)

func PrefetchStatusFromProtocol

func PrefetchStatusFromProtocol(
	protocolPrefetchStatus kbgitkbfs.PrefetchStatus) PrefetchStatus

PrefetchStatusFromProtocol transforms a kbgitkbfs.PrefetchStatus to a PrefetchStatus, while validating its value.

func (PrefetchStatus) MarshalJSON

func (s PrefetchStatus) MarshalJSON() ([]byte, error)

MarshalJSON converts a PrefetchStatus to JSON

func (PrefetchStatus) String

func (s PrefetchStatus) String() string

func (PrefetchStatus) ToProtocol

func (s PrefetchStatus) ToProtocol() kbgitkbfs.PrefetchStatus

ToProtocol transforms a PrefetchStatus to a kbgitkbfs.PrefetchStatus, while validating its value.

func (*PrefetchStatus) UnmarshalJSON

func (s *PrefetchStatus) UnmarshalJSON(b []byte) error

UnmarshalJSON converts a PrefetchStatus from JSON

type Prefetcher

type Prefetcher interface {
	// ProcessBlockForPrefetch potentially triggers and monitors a prefetch.
	ProcessBlockForPrefetch(ctx context.Context, ptr BlockPointer, block Block,
		kmd KeyMetadata, priority int, lifetime BlockCacheLifetime,
		prefetchStatus PrefetchStatus, action BlockRequestAction)
	// WaitChannelForBlockPrefetch returns a channel that can be used
	// to wait for a block to finish prefetching or be canceled.  If
	// the block isn't currently being prefetched, it will return an
	// already-closed channel.  When the channel is closed, the caller
	// should still verify that the prefetch status of the block is
	// what they expect it to be, in case there was an error.
	WaitChannelForBlockPrefetch(ctx context.Context, ptr BlockPointer) (
		<-chan struct{}, error)
	// CancelPrefetch notifies the prefetcher that a prefetch should be
	// canceled.
	CancelPrefetch(BlockPointer)
	// Shutdown shuts down the prefetcher idempotently. Future calls to
	// the various Prefetch* methods will return io.EOF. The returned channel
	// allows upstream components to block until all pending prefetches are
	// complete. This feature is mainly used for testing, but also to toggle
	// the prefetcher on and off.
	Shutdown() <-chan struct{}
}

Prefetcher is an interface to a block prefetcher.

type PrevRevisionAndCount

type PrevRevisionAndCount struct {
	Revision kbfsmd.Revision `codec:"r"`
	Count    uint8           `codec:"c"`

	codec.UnknownFieldSetHandler
}

PrevRevisionAndCount track the MD version of a previous revision of a dir entry, and how many revisions ago that was from the current revision.

type PrevRevisions

type PrevRevisions []PrevRevisionAndCount

PrevRevisions tracks several previous versions of a file in order of descending revision number, starting with the most recent.

type PrivateMetadata

type PrivateMetadata struct {
	// directory entry for the root directory block
	Dir DirEntry

	// m_f as described in § 4.1.1 of https://keybase.io/docs/crypto/kbfs.
	TLFPrivateKey kbfscrypto.TLFPrivateKey
	// The block changes done as part of the update that created this MD
	Changes BlockChanges

	// The last revision up to and including which garbage collection
	// was performed on this TLF.
	LastGCRevision kbfsmd.Revision `codec:"lgc"`

	codec.UnknownFieldSetHandler
	// contains filtered or unexported fields
}

PrivateMetadata contains the portion of metadata that's secret for private directories

func (PrivateMetadata) ChangesBlockInfo

func (p PrivateMetadata) ChangesBlockInfo() BlockInfo

ChangesBlockInfo returns the block info for any unembedded changes.

type ReadAccessError

type ReadAccessError struct {
	User     kbname.NormalizedUsername
	Filename string
	Tlf      tlf.CanonicalName
	Type     tlf.Type
}

ReadAccessError indicates that the user tried to read from a top-level folder without read permission.

func (ReadAccessError) Error

func (e ReadAccessError) Error() string

Error implements the error interface for ReadAccessError

type ReadOnlyRootMetadata

type ReadOnlyRootMetadata struct {
	*RootMetadata
}

A ReadOnlyRootMetadata is a thin wrapper around a *RootMetadata. Functions that take a ReadOnlyRootMetadata parameter must not modify it, and therefore code that passes a ReadOnlyRootMetadata to a function can assume that it is not modified by that function. However, callers that convert a *RootMetadata to a ReadOnlyRootMetadata may still modify the underlying RootMetadata through the original pointer, so care must be taken if a function stores a ReadOnlyRootMetadata object past the end of the function, or when a function takes both a *RootMetadata and a ReadOnlyRootMetadata (see decryptMDPrivateData).

func (ReadOnlyRootMetadata) CheckValidSuccessor

func (md ReadOnlyRootMetadata) CheckValidSuccessor(
	currID kbfsmd.ID, nextMd ReadOnlyRootMetadata) error

CheckValidSuccessor makes sure the given ReadOnlyRootMetadata is a valid successor to the current one, and returns an error otherwise.

type ReadonlyNode

type ReadonlyNode struct {
	Node
}

ReadonlyNode is a read-only node by default, unless `CtxReadWriteKey` has a value set in the context.

func (ReadonlyNode) Readonly

func (rn ReadonlyNode) Readonly(ctx context.Context) bool

Readonly implements the Node interface for ReadonlyNode.

func (ReadonlyNode) WrapChild

func (rn ReadonlyNode) WrapChild(child Node) Node

WrapChild implements the Node interface for ReadonlyNode.

type ReadyBlockData

type ReadyBlockData struct {
	// contains filtered or unexported fields
}

ReadyBlockData is a block that has been encoded (and encrypted).

func (ReadyBlockData) GetEncodedSize

func (r ReadyBlockData) GetEncodedSize() int

GetEncodedSize returns the size of the encoded (and encrypted) block data.

type RekeyConflictError

type RekeyConflictError struct {
	Err error
}

RekeyConflictError indicates a conflict happened while trying to rekey.

func (RekeyConflictError) Error

func (e RekeyConflictError) Error() string

Error implements the error interface for RekeyConflictError.

type RekeyEvent

type RekeyEvent struct {
	// contains filtered or unexported fields
}

RekeyEvent describes an event to send into the RekeyFSM. A function, e.g., NewRekeyRequestEvent, should be used to construct one.

func NewRekeyNotNeededEvent

func NewRekeyNotNeededEvent() RekeyEvent

NewRekeyNotNeededEvent creates a rekeyNotNeededEvent typed event. If the FSM is in rekeyStateScheduled, this causes FSM to unset paperkey prompt. In other states nothing happens. This event is sent to the FSM when we see a MD update with rekey flag unset. It can be an indication that an old outstanding rekey request has been served by another device, or just a regular rekey updates.

func NewRekeyRequestEvent

func NewRekeyRequestEvent() RekeyEvent

NewRekeyRequestEvent creates a non-delayed rekey request Event.

func NewRekeyRequestWithPaperPromptEvent

func NewRekeyRequestWithPaperPromptEvent() RekeyEvent

NewRekeyRequestWithPaperPromptEvent creates a non-delayed rekey request Event that causes a paper prompt.

func (RekeyEvent) String

func (e RekeyEvent) String() string

type RekeyFSM

type RekeyFSM interface {
	// Event sends an event to the FSM.
	Event(event RekeyEvent)
	// Shutdown shuts down the FSM. No new event should be sent into the FSM
	// after this method is called.
	Shutdown()
	// contains filtered or unexported methods
}

RekeyFSM is a Finite State Machine (FSM) for housekeeping rekey states for a FolderBranch. Each FolderBranch has its own FSM for rekeys.

See rekey_fsm.go for implementation details.

TODO: report FSM status in FolderBranchStatus?

func NewRekeyFSM

func NewRekeyFSM(fbo *folderBranchOps) RekeyFSM

NewRekeyFSM creates a new rekey FSM.

type RekeyIncompleteError

type RekeyIncompleteError struct{}

RekeyIncompleteError is returned when a rekey is partially done but needs a writer to finish it.

func (RekeyIncompleteError) Error

func (e RekeyIncompleteError) Error() string

type RekeyPermissionError

type RekeyPermissionError struct {
	User kbname.NormalizedUsername
	Dir  string
}

RekeyPermissionError indicates that the user tried to rekey a top-level folder in a manner inconsistent with their permissions.

func (RekeyPermissionError) Error

func (e RekeyPermissionError) Error() string

Error implements the error interface for RekeyPermissionError

type RekeyQueue

type RekeyQueue interface {
	// Enqueue enqueues a folder for rekey action. If the TLF is already in the
	// rekey queue, the error channel of the existing one is returned.
	Enqueue(tlf.ID)
	// IsRekeyPending returns true if the given folder is in the rekey queue.
	// Note that an ongoing rekey doesn't count as "pending".
	IsRekeyPending(tlf.ID) bool
	// Shutdown cancels all pending rekey actions and clears the queue. It
	// doesn't cancel ongoing rekeys. After Shutdown() is called, the same
	// RekeyQueue shouldn't be used anymore.
	Shutdown()
}

RekeyQueue is a managed queue of folders needing some rekey action taken upon them by the current client.

type RekeyQueueStandard

type RekeyQueueStandard struct {
	// contains filtered or unexported fields
}

RekeyQueueStandard implements the RekeyQueue interface.

func NewRekeyQueueStandard

func NewRekeyQueueStandard(config Config) (rkq *RekeyQueueStandard)

NewRekeyQueueStandard creates a new rekey queue.

func (*RekeyQueueStandard) Enqueue

func (rkq *RekeyQueueStandard) Enqueue(id tlf.ID)

Enqueue implements the RekeyQueue interface for RekeyQueueStandard.

func (*RekeyQueueStandard) IsRekeyPending

func (rkq *RekeyQueueStandard) IsRekeyPending(id tlf.ID) bool

IsRekeyPending implements the RekeyQueue interface for RekeyQueueStandard.

func (*RekeyQueueStandard) Shutdown

func (rkq *RekeyQueueStandard) Shutdown()

Shutdown implements the RekeyQueue interface for RekeyQueueStandard.

type RekeyResult

type RekeyResult struct {
	DidRekey      bool
	NeedsPaperKey bool
}

RekeyResult represents the result of an rekey operation.

func RequestRekeyAndWaitForOneFinishEvent

func RequestRekeyAndWaitForOneFinishEvent(ctx context.Context,
	ops KBFSOps, tlfID tlf.ID) (res RekeyResult, err error)

RequestRekeyAndWaitForOneFinishEvent sends a rekey request to the FSM associated with tlfID, and wait for exact one rekeyFinished event. This can be useful for waiting for a rekey result in tests.

Note that the supplied ctx is injected to the rekey task, so canceling ctx would actually cancel the rekey.

Currently this is only used in tests and RekeyFile. Normal rekey activities should go through the FSM asychronously.

type RenameAcrossDirsError

type RenameAcrossDirsError struct {
	// ApplicationExecPath, if not empty, is the exec path of the application
	// that issued the rename.
	ApplicationExecPath string
}

RenameAcrossDirsError indicates that the user tried to do an atomic rename across directories.

func (RenameAcrossDirsError) Error

func (e RenameAcrossDirsError) Error() string

Error implements the error interface for RenameAcrossDirsError

type ReportedError

type ReportedError struct {
	Time  time.Time
	Error error
	Stack []uintptr
}

ReportedError represents an error reported by KBFS.

type Reporter

type Reporter interface {
	// ReportErr records that a given error happened.
	ReportErr(ctx context.Context, tlfName tlf.CanonicalName, t tlf.Type,
		mode ErrorModeType, err error)
	// AllKnownErrors returns all errors known to this Reporter.
	AllKnownErrors() []ReportedError
	// Notify sends the given notification to any sink.
	Notify(ctx context.Context, notification *keybase1.FSNotification)
	// NotifyPathUpdated sends the given notification to any sink.
	NotifyPathUpdated(ctx context.Context, path string)
	// NotifySyncStatus sends the given path sync status to any sink.
	NotifySyncStatus(ctx context.Context, status *keybase1.FSPathSyncStatus)
	// Shutdown frees any resources allocated by a Reporter.
	Shutdown()
}

Reporter exports events (asynchronously) to any number of sinks

type ReporterKBPKI

type ReporterKBPKI struct {
	*ReporterSimple
	// contains filtered or unexported fields
}

ReporterKBPKI implements the Notify function of the Reporter interface in addition to embedding ReporterSimple for error tracking. Notify will make RPCs to the keybase daemon.

func NewReporterKBPKI

func NewReporterKBPKI(config Config, maxErrors, bufSize int) *ReporterKBPKI

NewReporterKBPKI creates a new ReporterKBPKI.

func (*ReporterKBPKI) Notify

func (r *ReporterKBPKI) Notify(ctx context.Context, notification *keybase1.FSNotification)

Notify implements the Reporter interface for ReporterKBPKI.

TODO: might be useful to get the debug tags out of ctx and store

them in the notifyBuffer as well so that send() can put
them back in its context.

func (*ReporterKBPKI) NotifyPathUpdated

func (r *ReporterKBPKI) NotifyPathUpdated(ctx context.Context, path string)

NotifyPathUpdated implements the Reporter interface for ReporterKBPKI.

TODO: might be useful to get the debug tags out of ctx and store

them in the notifyPathBuffer as well so that send() can put
them back in its context.

func (*ReporterKBPKI) NotifySyncStatus

func (r *ReporterKBPKI) NotifySyncStatus(ctx context.Context,
	status *keybase1.FSPathSyncStatus)

NotifySyncStatus implements the Reporter interface for ReporterKBPKI.

TODO: might be useful to get the debug tags out of ctx and store

them in the notifyBuffer as well so that send() can put
them back in its context.

func (*ReporterKBPKI) ReportErr

func (r *ReporterKBPKI) ReportErr(ctx context.Context,
	tlfName tlf.CanonicalName, t tlf.Type, mode ErrorModeType, err error)

ReportErr implements the Reporter interface for ReporterKBPKI.

func (*ReporterKBPKI) Shutdown

func (r *ReporterKBPKI) Shutdown()

Shutdown implements the Reporter interface for ReporterKBPKI.

type ReporterSimple

type ReporterSimple struct {
	// contains filtered or unexported fields
}

ReporterSimple remembers the last maxErrors errors, or all errors if maxErrors < 1.

func NewReporterSimple

func NewReporterSimple(clock Clock, maxErrors int) *ReporterSimple

NewReporterSimple creates a new ReporterSimple.

func (*ReporterSimple) AllKnownErrors

func (r *ReporterSimple) AllKnownErrors() []ReportedError

AllKnownErrors implements the Reporter interface for ReporterSimple.

func (*ReporterSimple) Notify

Notify implements the Reporter interface for ReporterSimple.

func (*ReporterSimple) NotifyPathUpdated

func (r *ReporterSimple) NotifyPathUpdated(_ context.Context, _ string)

NotifyPathUpdated implements the Reporter interface for ReporterSimple.

func (*ReporterSimple) NotifySyncStatus

func (r *ReporterSimple) NotifySyncStatus(_ context.Context,
	_ *keybase1.FSPathSyncStatus)

NotifySyncStatus implements the Reporter interface for ReporterSimple.

func (*ReporterSimple) ReportErr

func (r *ReporterSimple) ReportErr(ctx context.Context,
	_ tlf.CanonicalName, _ tlf.Type, _ ErrorModeType, err error)

ReportErr implements the Reporter interface for ReporterSimple.

func (*ReporterSimple) Shutdown

func (r *ReporterSimple) Shutdown()

Shutdown implements the Reporter interface for ReporterSimple.

type RevGarbageCollectedError

type RevGarbageCollectedError struct {
	// contains filtered or unexported fields
}

RevGarbageCollectedError indicates that the user is trying to access a revision that's already been garbage-collected.

func (RevGarbageCollectedError) Error

func (e RevGarbageCollectedError) Error() string

Error implements the Error interface for RevGarbageCollectedError.

type RevokedDeviceVerificationError

type RevokedDeviceVerificationError struct {
	// contains filtered or unexported fields
}

RevokedDeviceVerificationError indicates that the user is trying to verify a key that has been revoked. It includes useful information about the revocation, so the code receiving the error can check if the device was valid at the time of the data being checked.

func (RevokedDeviceVerificationError) Error

Error implements the Error interface for RevokedDeviceVerificationError.

type RootMetadata

type RootMetadata struct {
	// contains filtered or unexported fields
}

A RootMetadata is a BareRootMetadata but with a deserialized PrivateMetadata. However, note that it is possible that the PrivateMetadata has to be left serialized due to not having the right keys.

func (*RootMetadata) AddDiskUsage

func (md *RootMetadata) AddDiskUsage(diskUsage uint64)

AddDiskUsage wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) AddKeyGeneration

func (md *RootMetadata) AddKeyGeneration(codec kbfscodec.Codec,
	wKeys, rKeys kbfsmd.UserDevicePublicKeys,
	ePubKey kbfscrypto.TLFEphemeralPublicKey,
	ePrivKey kbfscrypto.TLFEphemeralPrivateKey,
	pubKey kbfscrypto.TLFPublicKey,
	privKey kbfscrypto.TLFPrivateKey,
	currCryptKey, nextCryptKey kbfscrypto.TLFCryptKey) (
	serverHalves kbfsmd.UserDeviceKeyServerHalves, err error)

AddKeyGeneration adds a new key generation to this revision of metadata.

func (*RootMetadata) AddMDDiskUsage

func (md *RootMetadata) AddMDDiskUsage(mdDiskUsage uint64)

AddMDDiskUsage wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) AddMDRefBytes

func (md *RootMetadata) AddMDRefBytes(mdRefBytes uint64)

AddMDRefBytes wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) AddOp

func (md *RootMetadata) AddOp(o op)

AddOp starts a new operation for this MD update. Subsequent AddRefBlock, AddUnrefBlock, and AddUpdate calls will be applied to this operation.

func (*RootMetadata) AddRefBlock

func (md *RootMetadata) AddRefBlock(info BlockInfo)

AddRefBlock adds the newly-referenced block to the add block change list.

func (*RootMetadata) AddRefBytes

func (md *RootMetadata) AddRefBytes(refBytes uint64)

AddRefBytes wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) AddUnrefBlock

func (md *RootMetadata) AddUnrefBlock(info BlockInfo)

AddUnrefBlock adds the newly-unreferenced block to the add block change list.

func (*RootMetadata) AddUnrefBytes

func (md *RootMetadata) AddUnrefBytes(unrefBytes uint64)

AddUnrefBytes wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) AddUpdate

func (md *RootMetadata) AddUpdate(oldInfo BlockInfo, newInfo BlockInfo)

AddUpdate adds the newly-updated block to the add block change list.

func (*RootMetadata) BID

func (md *RootMetadata) BID() kbfsmd.BranchID

BID wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) ClearBlockChanges

func (md *RootMetadata) ClearBlockChanges()

ClearBlockChanges resets the block change lists to empty for this RootMetadata.

func (*RootMetadata) Data

func (md *RootMetadata) Data() *PrivateMetadata

Data returns the private metadata of this RootMetadata.

func (*RootMetadata) DiskUsage

func (md *RootMetadata) DiskUsage() uint64

DiskUsage wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) Extra

func (md *RootMetadata) Extra() kbfsmd.ExtraMetadata

Extra returns the extra metadata of this RootMetadata.

func (*RootMetadata) GetBareRootMetadata

func (md *RootMetadata) GetBareRootMetadata() kbfsmd.RootMetadata

GetBareRootMetadata returns an interface to the underlying serializeable metadata.

func (*RootMetadata) GetHistoricTLFCryptKey

func (md *RootMetadata) GetHistoricTLFCryptKey(
	codec kbfscodec.Codec, keyGen kbfsmd.KeyGen,
	currentKey kbfscrypto.TLFCryptKey) (kbfscrypto.TLFCryptKey, error)

GetHistoricTLFCryptKey implements the KeyMetadata interface for RootMetadata.

func (*RootMetadata) GetRootDirEntry

func (md *RootMetadata) GetRootDirEntry() DirEntry

GetRootDirEntry implements the KeyMetadataWithRootDirEntry interface for RootMetadata.

func (*RootMetadata) GetSerializedPrivateMetadata

func (md *RootMetadata) GetSerializedPrivateMetadata() []byte

GetSerializedPrivateMetadata wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) GetSerializedWriterMetadata

func (md *RootMetadata) GetSerializedWriterMetadata(
	codec kbfscodec.Codec) ([]byte, error)

GetSerializedWriterMetadata wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) GetTLFCryptKeyParams

GetTLFCryptKeyParams wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) GetTLFReaderKeyBundleID

func (md *RootMetadata) GetTLFReaderKeyBundleID() kbfsmd.TLFReaderKeyBundleID

GetTLFReaderKeyBundleID returns the ID of the externally-stored reader key bundle, or the zero value if this object stores it internally.

func (*RootMetadata) GetTLFWriterKeyBundleID

func (md *RootMetadata) GetTLFWriterKeyBundleID() kbfsmd.TLFWriterKeyBundleID

GetTLFWriterKeyBundleID returns the ID of the externally-stored writer key bundle, or the zero value if this object stores it internally.

func (*RootMetadata) GetTlfHandle

func (md *RootMetadata) GetTlfHandle() *TlfHandle

GetTlfHandle returns the TlfHandle for this RootMetadata.

func (*RootMetadata) HasKeyForUser

func (md *RootMetadata) HasKeyForUser(user keybase1.UID) (
	bool, error)

HasKeyForUser wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) IsFinal

func (md *RootMetadata) IsFinal() bool

IsFinal wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) IsInitialized

func (md *RootMetadata) IsInitialized() bool

IsInitialized returns whether or not this RootMetadata has been initialized

func (*RootMetadata) IsReadable

func (md *RootMetadata) IsReadable() bool

IsReadable returns true if the private metadata can be read.

func (*RootMetadata) IsReader

func (md *RootMetadata) IsReader(
	ctx context.Context, checker kbfsmd.TeamMembershipChecker,
	uid keybase1.UID) (bool, error)

IsReader checks that the given user is a valid reader of the TLF right now.

func (*RootMetadata) IsRekeySet

func (md *RootMetadata) IsRekeySet() bool

IsRekeySet wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) IsUnmergedSet

func (md *RootMetadata) IsUnmergedSet() bool

IsUnmergedSet wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) IsWriter

func (md *RootMetadata) IsWriter(
	ctx context.Context, checker kbfsmd.TeamMembershipChecker,
	uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey) (
	bool, error)

IsWriter checks that the given user is a valid writer of the TLF right now. Implements the KeyMetadata interface for RootMetadata.

func (*RootMetadata) IsWriterMetadataCopiedSet

func (md *RootMetadata) IsWriterMetadataCopiedSet() bool

IsWriterMetadataCopiedSet wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) KeyGenerationsToUpdate

func (md *RootMetadata) KeyGenerationsToUpdate() (kbfsmd.KeyGen, kbfsmd.KeyGen)

KeyGenerationsToUpdate wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) LastModifyingUser

func (md *RootMetadata) LastModifyingUser() keybase1.UID

LastModifyingUser wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) LastModifyingWriter

func (md *RootMetadata) LastModifyingWriter() keybase1.UID

LastModifyingWriter wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) LatestKeyGeneration

func (md *RootMetadata) LatestKeyGeneration() kbfsmd.KeyGen

LatestKeyGeneration wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) MDDiskUsage

func (md *RootMetadata) MDDiskUsage() uint64

MDDiskUsage wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) MDRefBytes

func (md *RootMetadata) MDRefBytes() uint64

MDRefBytes wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) MakeBareTlfHandle

func (md *RootMetadata) MakeBareTlfHandle() (tlf.Handle, error)

MakeBareTlfHandle makes a BareTlfHandle for this RootMetadata. Should be used only by servers and MDOps.

func (*RootMetadata) MakeSuccessor

func (md *RootMetadata) MakeSuccessor(
	ctx context.Context, latestMDVer kbfsmd.MetadataVer, codec kbfscodec.Codec,
	keyManager KeyManager, merkleGetter merkleRootGetter,
	teamKeyer teamKeysGetter, mdID kbfsmd.ID, isWriter bool) (
	*RootMetadata, error)

MakeSuccessor returns a complete copy of this RootMetadata (but with cleared block change lists and cleared serialized metadata), with the revision incremented and a correct backpointer.

func (*RootMetadata) MakeSuccessorWithNewHandle

func (md *RootMetadata) MakeSuccessorWithNewHandle(
	ctx context.Context, newHandle *TlfHandle, latestMDVer kbfsmd.MetadataVer,
	codec kbfscodec.Codec, keyManager KeyManager, merkleGetter merkleRootGetter,
	teamKeyer teamKeysGetter, mdID kbfsmd.ID, isWriter bool) (
	*RootMetadata, error)

MakeSuccessorWithNewHandle does the same thing as MakeSuccessor, plus it changes the handle. (The caller is responsible for ensuring that the handle change is valid.)

func (*RootMetadata) MergedStatus

func (md *RootMetadata) MergedStatus() kbfsmd.MergeStatus

MergedStatus wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) MerkleRoot

func (md *RootMetadata) MerkleRoot() keybase1.MerkleRootV2

MerkleRoot wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) PrevRoot

func (md *RootMetadata) PrevRoot() kbfsmd.ID

PrevRoot wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) ReadOnly

func (md *RootMetadata) ReadOnly() ReadOnlyRootMetadata

ReadOnly makes a ReadOnlyRootMetadata from the current *RootMetadata.

func (*RootMetadata) RefBytes

func (md *RootMetadata) RefBytes() uint64

RefBytes wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) Revision

func (md *RootMetadata) Revision() kbfsmd.Revision

Revision wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetBranchID

func (md *RootMetadata) SetBranchID(bid kbfsmd.BranchID)

SetBranchID wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetConflictInfo

func (md *RootMetadata) SetConflictInfo(ci *tlf.HandleExtension)

SetConflictInfo wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetDiskUsage

func (md *RootMetadata) SetDiskUsage(diskUsage uint64)

SetDiskUsage wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetFinalBit

func (md *RootMetadata) SetFinalBit()

SetFinalBit wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetFinalizedInfo

func (md *RootMetadata) SetFinalizedInfo(fi *tlf.HandleExtension)

SetFinalizedInfo wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetLastGCRevision

func (md *RootMetadata) SetLastGCRevision(rev kbfsmd.Revision)

SetLastGCRevision sets the last revision up to and including which garbage collection was performed on this TLF.

func (*RootMetadata) SetLastModifyingUser

func (md *RootMetadata) SetLastModifyingUser(user keybase1.UID)

SetLastModifyingUser wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetLastModifyingWriter

func (md *RootMetadata) SetLastModifyingWriter(user keybase1.UID)

SetLastModifyingWriter wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetMDDiskUsage

func (md *RootMetadata) SetMDDiskUsage(mdDiskUsage uint64)

SetMDDiskUsage wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetMDRefBytes

func (md *RootMetadata) SetMDRefBytes(mdRefBytes uint64)

SetMDRefBytes wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetMerkleRoot

func (md *RootMetadata) SetMerkleRoot(root keybase1.MerkleRootV2)

SetMerkleRoot wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetPrevRoot

func (md *RootMetadata) SetPrevRoot(mdID kbfsmd.ID)

SetPrevRoot wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetRefBytes

func (md *RootMetadata) SetRefBytes(refBytes uint64)

SetRefBytes wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetRekeyBit

func (md *RootMetadata) SetRekeyBit()

SetRekeyBit wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetRevision

func (md *RootMetadata) SetRevision(revision kbfsmd.Revision)

SetRevision wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetSerializedPrivateMetadata

func (md *RootMetadata) SetSerializedPrivateMetadata(spmd []byte)

SetSerializedPrivateMetadata wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetTlfID

func (md *RootMetadata) SetTlfID(tlf tlf.ID)

SetTlfID wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetUnmerged

func (md *RootMetadata) SetUnmerged()

SetUnmerged wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetUnrefBytes

func (md *RootMetadata) SetUnrefBytes(unrefBytes uint64)

SetUnrefBytes wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetUnresolvedReaders

func (md *RootMetadata) SetUnresolvedReaders(readers []keybase1.SocialAssertion)

SetUnresolvedReaders wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetUnresolvedWriters

func (md *RootMetadata) SetUnresolvedWriters(writers []keybase1.SocialAssertion)

SetUnresolvedWriters wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetWriterMetadataCopiedBit

func (md *RootMetadata) SetWriterMetadataCopiedBit()

SetWriterMetadataCopiedBit wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) SetWriters

func (md *RootMetadata) SetWriters(writers []keybase1.UserOrTeamID)

SetWriters wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) StoresHistoricTLFCryptKeys

func (md *RootMetadata) StoresHistoricTLFCryptKeys() bool

StoresHistoricTLFCryptKeys implements the KeyMetadata interface for RootMetadata.

func (*RootMetadata) TlfID

func (md *RootMetadata) TlfID() tlf.ID

TlfID wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) TypeForKeying

func (md *RootMetadata) TypeForKeying() tlf.KeyingType

TypeForKeying returns the keying type for the RootMetadata.

func (*RootMetadata) UnrefBytes

func (md *RootMetadata) UnrefBytes() uint64

UnrefBytes wraps the respective method of the underlying BareRootMetadata for convenience.

func (*RootMetadata) Version

func (md *RootMetadata) Version() kbfsmd.MetadataVer

Version returns the underlying BareRootMetadata version.

type RootMetadataSigned

type RootMetadataSigned struct {
	kbfsmd.RootMetadataSigned
	// contains filtered or unexported fields
}

RootMetadataSigned is a wrapper around kbfsmd.RootMetadataSigned that adds an untrusted server timestamp.

func DecodeRootMetadataSigned

func DecodeRootMetadataSigned(
	codec kbfscodec.Codec, tlf tlf.ID, ver, max kbfsmd.MetadataVer, buf []byte,
	untrustedServerTimestamp time.Time) (
	*RootMetadataSigned, error)

DecodeRootMetadataSigned deserializes a metadata block into the specified versioned structure.

func SignBareRootMetadata

func SignBareRootMetadata(
	ctx context.Context, codec kbfscodec.Codec,
	rootMetadataSigner, writerMetadataSigner kbfscrypto.Signer,
	md kbfsmd.RootMetadata, untrustedServerTimestamp time.Time) (
	*RootMetadataSigned, error)

SignBareRootMetadata signs the given BareRootMetadata and returns a *RootMetadataSigned object. rootMetadataSigner and writerMetadataSigner should be the same, except in tests.

func (*RootMetadataSigned) MakeFinalCopy

func (rmds *RootMetadataSigned) MakeFinalCopy(
	codec kbfscodec.Codec, now time.Time,
	finalizedInfo *tlf.HandleExtension) (*RootMetadataSigned, error)

MakeFinalCopy returns a complete copy of this RootMetadataSigned with the revision incremented and the final bit set.

type SessionInfo

type SessionInfo struct {
	Name           kbname.NormalizedUsername
	UID            keybase1.UID
	CryptPublicKey kbfscrypto.CryptPublicKey
	VerifyingKey   kbfscrypto.VerifyingKey
}

SessionInfo contains all the info about the keybase session that kbfs cares about.

func GetCurrentSessionIfPossible

func GetCurrentSessionIfPossible(
	ctx context.Context, kbpki KBPKI, sessionNotRequired bool) (
	SessionInfo, error)

GetCurrentSessionIfPossible returns the current username and UID from kbpki.GetCurrentSession. If sessionNotRequired is true NoCurrentSessionError is ignored and empty username and uid will be returned. If it is false all errors are returned.

func SessionInfoFromProtocol

func SessionInfoFromProtocol(session keybase1.Session) (SessionInfo, error)

SessionInfoFromProtocol returns SessionInfo from Session

type SharedKeybaseTransport

type SharedKeybaseTransport struct {
	// contains filtered or unexported fields
}

SharedKeybaseTransport is a ConnectionTransport implementation that uses a shared local socket to a keybase daemon.

func (*SharedKeybaseTransport) Close

func (kt *SharedKeybaseTransport) Close()

Close is an implementation of the ConnectionTransport interface.

func (*SharedKeybaseTransport) Dial

Dial is an implementation of the ConnectionTransport interface.

func (*SharedKeybaseTransport) Finalize

func (kt *SharedKeybaseTransport) Finalize()

Finalize is an implementation of the ConnectionTransport interface.

func (*SharedKeybaseTransport) IsConnected

func (kt *SharedKeybaseTransport) IsConnected() bool

IsConnected is an implementation of the ConnectionTransport interface.

type ShutdownHappenedError

type ShutdownHappenedError struct {
}

ShutdownHappenedError indicates that shutdown has happened.

func (ShutdownHappenedError) Error

func (e ShutdownHappenedError) Error() string

Error implements the error interface for ShutdownHappenedError.

type SizeFlag

type SizeFlag struct {
	// contains filtered or unexported fields
}

SizeFlag is for specifying sizes with the flag package.

func (SizeFlag) Get

func (sf SizeFlag) Get() interface{}

Get for flag interface.

func (SizeFlag) Set

func (sf SizeFlag) Set(raw string) error

Set for flag interface.

func (SizeFlag) String

func (sf SizeFlag) String() string

String for flag interface.

type StallableBlockOp

type StallableBlockOp stallableOp

StallableBlockOp defines an Op that is stallable using StallBlockOp

type StallableMDOp

type StallableMDOp stallableOp

StallableMDOp defines an Op that is stallable using StallMDOp

type StateChecker

type StateChecker struct {
	// contains filtered or unexported fields
}

StateChecker verifies that the server-side state for KBFS is consistent. Useful mostly for testing because it isn't scalable and loads all the state in memory.

func NewStateChecker

func NewStateChecker(config Config) *StateChecker

NewStateChecker returns a new StateChecker instance.

func (*StateChecker) CheckMergedState

func (sc *StateChecker) CheckMergedState(ctx context.Context, tlfID tlf.ID) error

CheckMergedState verifies that the state for the given tlf is consistent.

type StatusUpdate

type StatusUpdate struct{}

StatusUpdate is a dummy type used to indicate status has been updated.

type StringOffset

type StringOffset string

StringOffset represents the offset of a block within a directory.

func (*StringOffset) Equals

func (s *StringOffset) Equals(other Offset) bool

Equals implements the Offset interface for StringOffset.

func (*StringOffset) Less

func (s *StringOffset) Less(other Offset) bool

Less implements the Offset interface for StringOffset.

func (*StringOffset) String

func (s *StringOffset) String() string

type TLFJournalBackgroundWorkStatus

type TLFJournalBackgroundWorkStatus int

TLFJournalBackgroundWorkStatus indicates whether a journal should be doing background work or not.

const (
	// TLFJournalBackgroundWorkPaused indicates that the journal
	// should not currently be doing background work.
	TLFJournalBackgroundWorkPaused TLFJournalBackgroundWorkStatus = iota
	// TLFJournalBackgroundWorkEnabled indicates that the journal
	// should be doing background work.
	TLFJournalBackgroundWorkEnabled
	// TLFJournalSingleOpBackgroundWorkEnabled indicates that the
	// journal should make all of its work visible to other readers as
	// a single operation. That means blocks may be uploaded as they
	// come in, but MDs must be squashed together and only one MD
	// update total should be uploaded.  The end of the operation will
	// be indicated by an explicit call to
	// `tlfJournal.finishSingleOp`.
	//
	// Note that this is an explicit per-TLF setting, rather than
	// taken from `Config.Mode()`, in case we find it useful in the
	// future to be able to turn this on for individual TLFs running
	// in normal KBFS mode.
	TLFJournalSingleOpBackgroundWorkEnabled
)

func (TLFJournalBackgroundWorkStatus) String

type TLFJournalStatus

type TLFJournalStatus struct {
	Dir           string
	RevisionStart kbfsmd.Revision
	RevisionEnd   kbfsmd.Revision
	BranchID      string
	BlockOpCount  uint64
	// The byte counters below are signed because
	// os.FileInfo.Size() is signed. The file counter is signed
	// for consistency.
	StoredBytes     int64
	StoredFiles     int64
	UnflushedBytes  int64
	UnflushedPaths  []string
	EndEstimate     *time.Time
	QuotaUsedBytes  int64
	QuotaLimitBytes int64
	LastFlushErr    string `json:",omitempty"`
}

TLFJournalStatus represents the status of a TLF's journal for display in diagnostics. It is suitable for encoding directly as JSON.

type TLFUpdateHistory

type TLFUpdateHistory struct {
	ID      string
	Name    string
	Updates []UpdateSummary
}

TLFUpdateHistory gives all the summaries of all updates in a TLF's history.

type TeamInfo

type TeamInfo struct {
	// Maybe this should be bare string?  The service doesn't give us
	// a nice type, unfortunately.  Also note that for implicit teams,
	// this is an auto-generated name that shouldn't be shown to
	// users.
	Name         kbname.NormalizedUsername
	TID          keybase1.TeamID
	CryptKeys    map[kbfsmd.KeyGen]kbfscrypto.TLFCryptKey
	LatestKeyGen kbfsmd.KeyGen
	RootID       keybase1.TeamID // for subteams only

	Writers map[keybase1.UID]bool
	Readers map[keybase1.UID]bool

	// Last writers map a KID to the last time the writer associated
	// with that KID trasitioned from writer to non-writer.
	LastWriters map[kbfscrypto.VerifyingKey]keybase1.MerkleRootV2
}

TeamInfo contains all the info about a keybase team that kbfs cares about.

func AddEmptyTeamsForTest

func AddEmptyTeamsForTest(
	config Config, teams ...kbname.NormalizedUsername) ([]TeamInfo, error)

AddEmptyTeamsForTest creates teams for the given names with empty membership lists.

func AddEmptyTeamsForTestOrBust

func AddEmptyTeamsForTestOrBust(t logger.TestLogBackend,
	config Config, teams ...kbname.NormalizedUsername) []TeamInfo

AddEmptyTeamsForTestOrBust is like AddEmptyTeamsForTest, but dies if there's an error.

func MakeLocalTeams

func MakeLocalTeams(teams []kbname.NormalizedUsername) []TeamInfo

MakeLocalTeams is a helper function to generate a list of local teams suitable to use with KeybaseDaemonLocal. Any subteams must come after their root team names in the `teams` slice.

type TestClock

type TestClock struct {
	// contains filtered or unexported fields
}

TestClock returns a set time as the current time.

func (*TestClock) Add

func (tc *TestClock) Add(d time.Duration)

Add adds to the test clock time.

func (*TestClock) Now

func (tc *TestClock) Now() time.Time

Now implements the Clock interface for TestClock.

func (*TestClock) Set

func (tc *TestClock) Set(t time.Time)

Set sets the test clock time.

type TimeoutError

type TimeoutError struct {
}

TimeoutError is just a replacement for context.DeadlineExceeded with a more friendly error string.

func (TimeoutError) Error

func (e TimeoutError) Error() string

type TlfAccessError

type TlfAccessError struct {
	ID tlf.ID
}

TlfAccessError that the user tried to perform an unpermitted operation on a top-level folder.

func (TlfAccessError) Error

func (e TlfAccessError) Error() string

Error implements the error interface for TlfAccessError

type TlfHandle

type TlfHandle struct {
	// contains filtered or unexported fields
}

TlfHandle contains all the info in a tlf.Handle as well as additional info. This doesn't embed tlf.Handle to avoid having to keep track of data in multiple places.

func GetHandleFromFolderNameAndType

func GetHandleFromFolderNameAndType(
	ctx context.Context, kbpki KBPKI, idGetter tlfIDGetter, tlfName string,
	t tlf.Type) (*TlfHandle, error)

GetHandleFromFolderNameAndType returns a TLFHandle given a folder name (e.g., "u1,u2#u3") and a TLF type.

func MakeTlfHandle

func MakeTlfHandle(
	ctx context.Context, bareHandle tlf.Handle, t tlf.Type,
	resolver resolver, nug normalizedUsernameGetter, idGetter tlfIDGetter) (
	*TlfHandle, error)

MakeTlfHandle creates a TlfHandle from the given tlf.Handle and the given normalizedUsernameGetter (which is usually a KBPKI). `t` is the `tlf.Type` of the new handle. (Note this could be different from `bareHandle.Type()`, if this is an implicit team TLF.)

func ParseTlfHandle

func ParseTlfHandle(
	ctx context.Context, kbpki KBPKI, idGetter tlfIDGetter, name string,
	t tlf.Type) (*TlfHandle, error)

ParseTlfHandle parses a TlfHandle from an encoded string. See TlfHandle.GetCanonicalName() for the opposite direction.

Some errors that may be returned and can be specially handled:

TlfNameNotCanonical: Returned when the given name is not canonical -- another name to try (which itself may not be canonical) is in the error. Usually, you want to treat this as a symlink to the name to try.

NoSuchNameError: Returned when public is set and the given folder has no public folder.

TODO In future perhaps all code should switch over to preferred handles, and rename TlfNameNotCanonical to TlfNameNotPreferred.

func ParseTlfHandlePreferred

func ParseTlfHandlePreferred(
	ctx context.Context, kbpki KBPKI, idGetter tlfIDGetter, name string,
	t tlf.Type) (*TlfHandle, error)

ParseTlfHandlePreferred returns TlfNameNotCanonical if not in the preferred format. Preferred format means that the users own username (from kbpki) as a writer is put before other usernames in the tlf name. i.e. Canon Preferred myname,other myname,other another,myname myname,another This function also can return NoSuchNameError or TlfNameNotCanonical. TlfNameNotCanonical is returned from this function when the name is not the *preferred* name.

func (TlfHandle) ConflictInfo

func (h TlfHandle) ConflictInfo() *tlf.HandleExtension

ConflictInfo returns the handle's conflict info, if any.

func (TlfHandle) Equals

func (h TlfHandle) Equals(
	codec kbfscodec.Codec, other TlfHandle) (bool, error)

Equals returns whether h and other contain the same info.

func (TlfHandle) EqualsIgnoreName

func (h TlfHandle) EqualsIgnoreName(
	codec kbfscodec.Codec, other TlfHandle) (bool, error)

EqualsIgnoreName returns whether h and other contain the same info ignoring the name.

func (TlfHandle) Extensions

func (h TlfHandle) Extensions() (extensions []tlf.HandleExtension)

Extensions returns a list of extensions for the given handle.

func (TlfHandle) FinalizedInfo

func (h TlfHandle) FinalizedInfo() *tlf.HandleExtension

FinalizedInfo returns the handle's finalized info, if any.

func (TlfHandle) FirstResolvedWriter

func (h TlfHandle) FirstResolvedWriter() keybase1.UserOrTeamID

FirstResolvedWriter returns the handle's first resolved writer ID (when sorted). For SingleTeam handles, this returns the team to which the TLF belongs.

func (*TlfHandle) GetCanonicalName

func (h *TlfHandle) GetCanonicalName() tlf.CanonicalName

GetCanonicalName returns the canonical name of this TLF.

func (*TlfHandle) GetCanonicalPath

func (h *TlfHandle) GetCanonicalPath() string

GetCanonicalPath returns the full canonical path of this TLF.

func (TlfHandle) GetPreferredFormat

func (h TlfHandle) GetPreferredFormat(
	username kbname.NormalizedUsername) tlf.PreferredName

GetPreferredFormat returns a TLF name formatted with the username given as the parameter first. This calls tlf.CanonicalToPreferredName with the canonical tlf name which will be reordered into the preferred format. An empty username is allowed here and results in the canonical ordering.

func (TlfHandle) IsBackedByTeam

func (h TlfHandle) IsBackedByTeam() bool

IsBackedByTeam returns true if h represents a TLF backed by a team. It could be either a SingleTeam TLF or a private/public TLF backed by an implicit team.

func (TlfHandle) IsConflict

func (h TlfHandle) IsConflict() bool

IsConflict returns whether or not this TlfHandle represents a conflicted top-level folder.

func (TlfHandle) IsFinal

func (h TlfHandle) IsFinal() bool

IsFinal returns whether or not this TlfHandle represents a finalized top-level folder.

func (TlfHandle) IsReader

func (h TlfHandle) IsReader(user keybase1.UID) bool

IsReader returns whether or not the given user is a reader for the top-level folder represented by this TlfHandle.

func (TlfHandle) IsWriter

func (h TlfHandle) IsWriter(user keybase1.UID) bool

IsWriter returns whether or not the given user is a writer for the top-level folder represented by this TlfHandle.

func (TlfHandle) MutuallyResolvesTo

func (h TlfHandle) MutuallyResolvesTo(
	ctx context.Context, codec kbfscodec.Codec,
	resolver resolver, idGetter tlfIDGetter, other TlfHandle,
	rev kbfsmd.Revision, tlfID tlf.ID, log logger.Logger) error

MutuallyResolvesTo checks that the target handle, and the provided `other` handle, resolve to each other.

func (*TlfHandle) ResolveAgain

func (h *TlfHandle) ResolveAgain(
	ctx context.Context, resolver resolver, idGetter tlfIDGetter) (
	*TlfHandle, error)

ResolveAgain tries to resolve any unresolved assertions in the given handle and returns a new handle with the results. As an optimization, if h contains no unresolved assertions, it just returns itself.

func (*TlfHandle) ResolveAgainForUser

func (h *TlfHandle) ResolveAgainForUser(ctx context.Context, resolver resolver,
	idGetter tlfIDGetter, uid keybase1.UID) (*TlfHandle, error)

ResolveAgainForUser tries to resolve any unresolved assertions in the given handle and returns a new handle with the results. As an optimization, if h contains no unresolved assertions, it just returns itself. If uid != keybase1.UID(""), it only allows assertions that resolve to uid.

func (TlfHandle) ResolvedReaders

func (h TlfHandle) ResolvedReaders() []keybase1.UserOrTeamID

ResolvedReaders returns the handle's resolved reader IDs in sorted order. If the handle is public, nil will be returned.

func (TlfHandle) ResolvedUsersMap

func (h TlfHandle) ResolvedUsersMap() map[keybase1.UserOrTeamID]kbname.NormalizedUsername

ResolvedUsersMap returns a map of resolved users from uid to usernames.

func (TlfHandle) ResolvedWriters

func (h TlfHandle) ResolvedWriters() []keybase1.UserOrTeamID

ResolvedWriters returns the handle's resolved writer IDs in sorted order.

func (TlfHandle) ResolvesTo

func (h TlfHandle) ResolvesTo(
	ctx context.Context, codec kbfscodec.Codec, resolver resolver,
	idGetter tlfIDGetter, other TlfHandle) (
	resolvesTo bool, partialResolvedH *TlfHandle, err error)

ResolvesTo returns whether this handle resolves to the given one. It also returns the partially-resolved version of h, i.e. h resolved except for unresolved assertions in other; this should equal other if and only if true is returned.

func (*TlfHandle) SetFinalizedInfo

func (h *TlfHandle) SetFinalizedInfo(info *tlf.HandleExtension)

SetFinalizedInfo sets the handle's finalized info to the given one, which may be nil. TODO: remove this to make TlfHandle fully immutable

func (TlfHandle) TlfID

func (h TlfHandle) TlfID() tlf.ID

TlfID returns the TLF ID corresponding to this handle, if it's known. If it's wasn't known at the time the handle was constructed, tlf.NullID is returned.

func (TlfHandle) ToBareHandle

func (h TlfHandle) ToBareHandle() (tlf.Handle, error)

ToBareHandle returns a tlf.Handle corresponding to this handle.

func (TlfHandle) ToBareHandleOrBust

func (h TlfHandle) ToBareHandleOrBust() tlf.Handle

ToBareHandleOrBust returns a tlf.Handle corresponding to this handle, and panics if there's an error. Used by tests.

func (*TlfHandle) ToFavorite

func (h *TlfHandle) ToFavorite() Favorite

ToFavorite converts a TlfHandle into a Favorite, suitable for Favorites calls.

func (TlfHandle) Type

func (h TlfHandle) Type() tlf.Type

Type returns the type of the TLF this TlfHandle represents.

func (TlfHandle) TypeForKeying

func (h TlfHandle) TypeForKeying() tlf.KeyingType

TypeForKeying returns the keying type for the handle h.

func (TlfHandle) UnresolvedReaders

func (h TlfHandle) UnresolvedReaders() []keybase1.SocialAssertion

UnresolvedReaders returns the handle's unresolved readers in sorted order. If the handle is public, nil will be returned.

func (TlfHandle) UnresolvedWriters

func (h TlfHandle) UnresolvedWriters() []keybase1.SocialAssertion

UnresolvedWriters returns the handle's unresolved writers in sorted order.

func (TlfHandle) WithUpdatedConflictInfo

func (h TlfHandle) WithUpdatedConflictInfo(
	codec kbfscodec.Codec, info *tlf.HandleExtension) (*TlfHandle, error)

WithUpdatedConflictInfo returns a new handle with the conflict info set to the given one, if the existing one is nil. (In this case, the given one may also be nil.) Otherwise, the given conflict info must match the existing one.

type TlfHandleFinalizedError

type TlfHandleFinalizedError struct {
}

TlfHandleFinalizedError is returned when something attempts to modify a finalized TLF handle.

func (TlfHandleFinalizedError) Error

func (e TlfHandleFinalizedError) Error() string

Error implements the error interface for TlfHandleFinalizedError.

type TlfNameNotCanonical

type TlfNameNotCanonical struct {
	Name, NameToTry string
}

TlfNameNotCanonical indicates that a name isn't a canonical, and that another (not necessarily canonical) name should be tried.

func (TlfNameNotCanonical) Error

func (e TlfNameNotCanonical) Error() string

type TooLowByteCountError

type TooLowByteCountError struct {
	ExpectedMinByteCount int
	ByteCount            int
}

TooLowByteCountError indicates that size of a block is smaller than the expected size.

func (TooLowByteCountError) Error

func (e TooLowByteCountError) Error() string

Error implements the error interface for TooLowByteCountError

type Tracer

type Tracer interface {
	// MaybeStartTrace, if tracing is on, returns a new context
	// based on the given one with an attached trace made with the
	// given family and title. Otherwise, it returns the given
	// context unchanged.
	MaybeStartTrace(ctx context.Context, family, title string) context.Context
	// MaybeFinishTrace, finishes the trace attached to the given
	// context, if any.
	MaybeFinishTrace(ctx context.Context, err error)
}

Tracer maybe adds traces to contexts.

type UnexpectedUnmergedPutError

type UnexpectedUnmergedPutError struct {
}

UnexpectedUnmergedPutError indicates that we tried to do an unmerged put when that was disallowed.

func (UnexpectedUnmergedPutError) Error

Error implements the error interface for UnexpectedUnmergedPutError

type UnmergedError

type UnmergedError struct {
}

UnmergedError indicates that fbo is on an unmerged local revision

func (UnmergedError) Error

func (e UnmergedError) Error() string

Error implements the error interface for UnmergedError.

type UnmergedSelfConflictError

type UnmergedSelfConflictError struct {
	Err error
}

UnmergedSelfConflictError indicates that we hit a conflict on the unmerged branch, so a previous MD PutUnmerged we thought had failed, had actually succeeded.

func (UnmergedSelfConflictError) Error

Error implements the error interface for UnmergedSelfConflictError.

type UnsupportedOpInUnlinkedDirError

type UnsupportedOpInUnlinkedDirError struct {
	Dirpath string
}

UnsupportedOpInUnlinkedDirError indicates an error when trying to create a file.

func (UnsupportedOpInUnlinkedDirError) Error

Error implements the error interface for UnsupportedOpInUnlinkedDirError.

type UnverifiableTlfUpdateError

type UnverifiableTlfUpdateError struct {
	Tlf  string
	User kbname.NormalizedUsername
	Err  error
}

UnverifiableTlfUpdateError indicates that a MD update could not be verified.

func (UnverifiableTlfUpdateError) Error

Error implements the error interface for UnverifiableTlfUpdateError.

type UpdateSummary

type UpdateSummary struct {
	Revision  kbfsmd.Revision
	Date      time.Time
	Writer    string
	LiveBytes uint64 // the "DiskUsage" for the TLF as of this revision
	Ops       []OpSummary
}

UpdateSummary describes the operations done by a single MD revision.

type UserInfo

type UserInfo struct {
	Name            kbname.NormalizedUsername
	UID             keybase1.UID
	VerifyingKeys   []kbfscrypto.VerifyingKey
	CryptPublicKeys []kbfscrypto.CryptPublicKey
	KIDNames        map[keybase1.KID]string
	EldestSeqno     keybase1.Seqno

	// Revoked keys, and the time at which they were revoked.
	RevokedVerifyingKeys   map[kbfscrypto.VerifyingKey]revokedKeyInfo
	RevokedCryptPublicKeys map[kbfscrypto.CryptPublicKey]revokedKeyInfo
}

UserInfo contains all the info about a keybase user that kbfs cares about.

func (UserInfo) DeepCopy

func (ui UserInfo) DeepCopy() UserInfo

DeepCopy returns a copy of `ui`, including deep copies of all slice and map members.

type VerifyingKeyNotFoundError

type VerifyingKeyNotFoundError struct {
	// contains filtered or unexported fields
}

VerifyingKeyNotFoundError indicates that a verifying key matching the given one couldn't be found.

func (VerifyingKeyNotFoundError) Error

type Warninger

type Warninger interface {
	Warning(format string, args ...interface{})
}

Warninger is an interface that only waprs the Warning method.

type WrapError

type WrapError struct {
	Err error
}

WrapError simply wraps an error in a fmt.Stringer interface, so that it can be reported.

func (WrapError) String

func (e WrapError) String() string

String implements the fmt.Stringer interface for WrapError

type WriteAccessError

type WriteAccessError struct {
	User     kbname.NormalizedUsername
	Filename string
	Tlf      tlf.CanonicalName
	Type     tlf.Type
}

WriteAccessError indicates an error when trying to write a file

func (WriteAccessError) Error

func (e WriteAccessError) Error() string

Error implements the error interface for WriteAccessError

type WriteRange

type WriteRange struct {
	Off uint64 `codec:"o"`
	Len uint64 `codec:"l,omitempty"` // 0 for truncates

	codec.UnknownFieldSetHandler
}

WriteRange represents a file modification. Len is 0 for a truncate.

func (WriteRange) Affects

func (w WriteRange) Affects(other WriteRange) bool

Affects returns true if the regions affected by this write operation and `other` overlap in some way. Specifically, it returns true if:

  • both operations are writes and their write ranges overlap;
  • one operation is a write and one is a truncate, and the truncate is within the write's range or before it; or
  • both operations are truncates.

func (WriteRange) End

func (w WriteRange) End() uint64

End returns the index of the largest byte not affected by this write. It only makes sense to call this for non-truncates.

type WriteToReadonlyNodeError

type WriteToReadonlyNodeError struct {
	Filename string
}

WriteToReadonlyNodeError indicates an error when trying to write a node that's marked as read-only.

func (WriteToReadonlyNodeError) Error

func (e WriteToReadonlyNodeError) Error() string

Error implements the error interface for WriteToReadonlyNodeError

type WriteUnsupportedError

type WriteUnsupportedError struct {
	Filename string
}

WriteUnsupportedError indicates an error when trying to write a file

func (WriteUnsupportedError) Error

func (e WriteUnsupportedError) Error() string

Error implements the error interface for WriteUnsupportedError

type WriterDeviceDateConflictRenamer

type WriterDeviceDateConflictRenamer struct {
	// contains filtered or unexported fields
}

WriterDeviceDateConflictRenamer renames a file using a username, device name, and date.

func (WriterDeviceDateConflictRenamer) ConflictRename

func (cr WriterDeviceDateConflictRenamer) ConflictRename(
	ctx context.Context, op op, original string) (string, error)

ConflictRename implements the ConflictRename interface for TimeAndWriterConflictRenamer.

func (WriterDeviceDateConflictRenamer) ConflictRenameHelper

func (WriterDeviceDateConflictRenamer) ConflictRenameHelper(t time.Time, user, device, original string) string

ConflictRenameHelper is a helper for ConflictRename especially useful from tests.

type WrongOpsError

type WrongOpsError struct {
	// contains filtered or unexported fields
}

WrongOpsError indicates that an unexpected path got passed into a FolderBranchOps instance

func (WrongOpsError) Error

func (e WrongOpsError) Error() string

Error implements the error interface for WrongOpsError.

type XattrStore

type XattrStore interface {
	// GetXattr looks for and returns the Xattr value of xattrType for blockID
	// if it's found, and an error whose Cause is ldberrors.ErrNotFound if it's
	// not found.
	GetXattr(ctx context.Context,
		blockID kbfsblock.ID, xattrType XattrType) ([]byte, error)
	// SetXattr sets xattrType Xattr to xattrValue for blockID.
	SetXattr(ctx context.Context,
		blockID kbfsblock.ID, xattrType XattrType, xattrValue []byte) error
}

XattrStore defines a type that handles locally stored xattr values by interacting with a BlockMetadataStore.

func NewXattrStoreFromBlockMetadataStore

func NewXattrStoreFromBlockMetadataStore(store BlockMetadataStore) XattrStore

NewXattrStoreFromBlockMetadataStore returns a XattrStore which is a wrapper around the passed in store.

type XattrType

type XattrType int

XattrType represents the xattr type.

const (
	XattrAppleQuarantine XattrType
)

New types can only be added at end.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL