// ReloadKeyring is used to re-read the underlying keyring.
// This is used for HA deployments to ensure the latest keyring
// is present in the leader.
493720
func (b *AESGCMBarrier) ReloadKeyring(ctx context.Context) error {
	b.l.Lock()
	defer b.l.Unlock()

	// Create the AES-GCM
	gcm, err := b.aeadFromKey(b.keyring.MasterKey())
	if err != nil {
		return err
	}

	// Read in the keyring
	out, err := b.backend.Get(ctx, keyringPath)
	if err != nil {
		return errwrap.Wrapf("failed to check for keyring: {{err}}", err)
	}

	// Ensure that the keyring exists. This should never happen,
	// and indicates something really bad has happened.
	if out == nil {
		return errors.New("keyring unexpectedly missing")
	}

	// Verify the term is always just one
	term := binary.BigEndian.Uint32(out.Value[:4])
	if term != initialKeyTerm {
		return errors.New("term mis-match")
	}

	// Decrypt the barrier init key
	plain, err := b.decrypt(keyringPath, gcm, out.Value)
	defer memzero(plain)
	if err != nil {
		if strings.Contains(err.Error(), "message authentication failed") {
			return ErrBarrierInvalidKey
		}
		return err
	}

	// Recover the keyring
	keyring, err := DeserializeKeyring(plain)
	if err != nil {
		return errwrap.Wrapf("keyring deserialization failed: {{err}}", err)
	}

	// Setup the keyring and finish
	b.keyring = keyring
	return nil
}
788209
func loadKeys(keyFile string, keyStore KeyStore) (jose.Encrypter, interface{}, error) {
	privateKey, _, err := keyStore.LoadPrivateKey(keyFile)
	if err != nil {
		return nil, nil, err
	}
	decryptionKey, err := jose.LoadPrivateKey(privateKey)
	if err != nil {
		return nil, nil, err
	}

	pub, err := keyStore.LoadPublicKey(keyFile)
	if err != nil {
		return nil, nil, err
	}
	publicKey, err := jose.LoadPublicKey(pub)
	if err != nil {
		return nil, nil, err
	}

	encrypter, err := jose.NewEncrypter(keyAlgorithm, contentEncryption, publicKey)
	if err != nil {
		return nil, nil, err
	}

	return encrypter, decryptionKey, err
}
263111
func (c RekeyUIClient) Refresh(ctx context.Context, __arg RefreshArg) (err error) {
	err = c.Cli.Call(ctx, "keybase.1.rekeyUI.refresh", []interface{}{__arg}, nil)
	return
}
629068
func (c *ConfigFile) Reload() (err error) {
	var cfg *ConfigFile
	if len(c.fileNames) == 1 {
		cfg, err = LoadConfigFile(c.fileNames[0])
	} else {
		cfg, err = LoadConfigFile(c.fileNames[0], c.fileNames[1:]...)
	}

	if err == nil {
		*c = *cfg
	}
	return err
}
648617
func (sys *NotificationSys) ReloadFormat(dryRun bool) []NotificationPeerErr {
	ng := WithNPeers(len(sys.peerClients))
	for idx, client := range sys.peerClients {
		if client == nil {
			continue
		}
		client := client
		ng.Go(context.Background(), func() error {
			return client.ReloadFormat(dryRun)
		}, idx, *client.host)
	}
	return ng.Wait()
}
539664
func (km *KeyManagerStandard) Rekey(ctx context.Context, md *RootMetadata, promptPaper bool) (
	mdChanged bool, cryptKey *kbfscrypto.TLFCryptKey, err error) {
	km.log.CDebugf(ctx, "Rekey %s (prompt for paper key: %t)",
		md.TlfID(), promptPaper)
	defer func() { km.deferLog.CDebugf(ctx, "Rekey %s done: %+v", md.TlfID(), err) }()

	if md.TypeForKeying() == tlf.TeamKeying {
		return false, nil, errors.New(
			"Rekeying is not done by KBFS for team TLFs")
	}

	currKeyGen := md.LatestKeyGeneration()
	if (md.TypeForKeying() == tlf.PublicKeying) != (currKeyGen == kbfsmd.PublicKeyGen) {
		return false, nil, errors.Errorf(
			"ID %v has keying type=%s but currKeyGen is %d (isPublic=%t)",
			md.TlfID(), md.TypeForKeying(), currKeyGen,
			currKeyGen == kbfsmd.PublicKeyGen)
	}

	if promptPaper && md.TypeForKeying() != tlf.PrivateKeying {
		return false, nil, errors.Errorf(
			"promptPaper set for non-private TLF %v", md.TlfID())
	}

	handle := md.GetTlfHandle()

	session, err := km.config.KBPKI().GetCurrentSession(ctx)
	if err != nil {
		return false, nil, err
	}

	idGetter := tlfhandle.ConstIDGetter{ID: md.TlfID()}
	resolvedHandle, err := handle.ResolveAgain(
		ctx, km.config.KBPKI(), idGetter, km.config)
	if err != nil {
		return false, nil, err
	}

	isWriter := resolvedHandle.IsWriter(session.UID)
	if md.TypeForKeying() == tlf.PrivateKeying && !isWriter {
		// If I was already a reader, there's nothing more to do
		if handle.IsReader(session.UID) {
			resolvedHandle = handle
			km.log.CDebugf(ctx, "Local user is not a writer, and was "+
				"already a reader; reverting back to the original handle")
		} else {
			// Only allow yourself to change
			resolvedHandle, err = handle.ResolveAgainForUser(
				ctx, km.config.KBPKI(), idGetter, km.config, session.UID)
			if err != nil {
				return false, nil, err
			}
		}
	}

	eq, err := handle.Equals(km.config.Codec(), *resolvedHandle)
	if err != nil {
		return false, nil, err
	}
	handleChanged := !eq
	if handleChanged {
		km.log.CDebugf(ctx, "handle for %s resolved to %s",
			handle.GetCanonicalPath(),
			resolvedHandle.GetCanonicalPath())

		// Check with the server to see if the handle became a conflict.
		latestHandle, err := km.config.MDOps().GetLatestHandleForTLF(ctx, md.TlfID())
		if err != nil {
			return false, nil, err
		}
		if latestHandle.ConflictInfo != nil {
			km.log.CDebugf(ctx, "handle for %s is conflicted",
				handle.GetCanonicalPath())
		}
		resolvedHandle, err = resolvedHandle.WithUpdatedConflictInfo(
			km.config.Codec(), latestHandle.ConflictInfo)
		if err != nil {
			return false, nil, err
		}
	}

	// For a public or team TLF there's no rekeying to be done, but we
	// should still update the writer list.
	if md.TypeForKeying() != tlf.PrivateKeying {
		if !handleChanged {
			km.log.CDebugf(ctx,
				"Skipping rekeying %s (%s): handle hasn't changed",
				md.TlfID(), md.TypeForKeying())
			return false, nil, nil
		}
		return true, nil, md.updateFromTlfHandle(resolvedHandle)
	}

	// Decide whether we have a new device and/or a revoked device, or neither.
	// Look up all the device public keys for all writers and readers first.

	incKeyGen := currKeyGen < kbfsmd.FirstValidKeyGen

	if !isWriter && incKeyGen {
		// Readers cannot create the first key generation
		return false, nil, tlfhandle.NewReadAccessError(
			resolvedHandle, session.Name, resolvedHandle.GetCanonicalPath())
	}

	offline := km.config.OfflineAvailabilityForID(md.TlfID())

	// All writer keys in the desired keyset
	updatedWriterKeys, err := km.generateKeyMapForUsers(
		ctx, resolvedHandle.ResolvedWriters(), offline)
	if err != nil {
		return false, nil, err
	}
	// All reader keys in the desired keyset
	updatedReaderKeys, err := km.generateKeyMapForUsers(
		ctx, resolvedHandle.ResolvedReaders(), offline)
	if err != nil {
		return false, nil, err
	}

	addNewReaderDevice := false
	addNewWriterDevice := false
	var newReaderUsers map[keybase1.UID]bool
	var newWriterUsers map[keybase1.UID]bool
	var readersToPromote map[keybase1.UID]bool

	// Figure out if we need to add or remove any keys.
	// If we're already incrementing the key generation then we don't need to
	// figure out the key delta.
	addNewReaderDeviceForSelf := false
	if !incKeyGen {
		// See if there is at least one new device in relation to the
		// current key bundle
		writers, readers, err := md.getUserDevicePublicKeys()
		if err != nil {
			return false, nil, err
		}

		newWriterUsers = km.usersWithNewDevices(
			ctx, md.TlfID(), writers, updatedWriterKeys)
		newReaderUsers = km.usersWithNewDevices(
			ctx, md.TlfID(), readers, updatedReaderKeys)
		addNewWriterDevice = len(newWriterUsers) > 0
		addNewReaderDevice = len(newReaderUsers) > 0

		wRemoved := km.usersWithRemovedDevices(
			ctx, md.TlfID(), writers, updatedWriterKeys)
		rRemoved := km.usersWithRemovedDevices(
			ctx, md.TlfID(), readers, updatedReaderKeys)

		readersToPromote = make(map[keybase1.UID]bool, len(rRemoved))

		// Before we add the removed devices, check if we are adding a
		// new reader device for ourselves.
		_, addNewReaderDeviceForSelf = newReaderUsers[session.UID]

		for u := range rRemoved {
			// FIXME (potential): this could cause a reader to attempt to rekey
			// in the case of a revocation for the currently logged-in user. I
			// _think_ incKeyGen above protects against this, but I'm not
			// confident.
			newReaderUsers[u] = true
			// Track which readers have been promoted. This must happen before
			// the following line adds all the removed writers to the writer
			// set
			if newWriterUsers[u] {
				readersToPromote[u] = true
			}
		}
		for u := range wRemoved {
			newWriterUsers[u] = true
		}

		incKeyGen = len(wRemoved) > 0 || (len(rRemoved) > len(readersToPromote))

		if err := km.identifyUIDSets(ctx, md.TlfID(), newWriterUsers, newReaderUsers); err != nil {
			return false, nil, err
		}
	}

	if !addNewReaderDevice && !addNewWriterDevice && !incKeyGen &&
		!handleChanged {
		km.log.CDebugf(ctx,
			"Skipping rekeying %s (private): no new or removed devices, no new keygen, and handle hasn't changed",
			md.TlfID())
		return false, nil, nil
	}

	if !isWriter {
		// This shouldn't happen; see the code above where we
		// either use the original handle or resolve only the
		// current UID.
		if len(readersToPromote) != 0 {
			return false, nil, errors.New(
				"promoted readers unexpectedly non-empty")
		}

		if _, userHasNewKeys := newReaderUsers[session.UID]; userHasNewKeys {
			// Only rekey the logged-in reader.
			updatedWriterKeys = nil
			updatedReaderKeys = kbfsmd.UserDevicePublicKeys{
				session.UID: updatedReaderKeys[session.UID],
			}
			delete(newReaderUsers, session.UID)
		} else {
			// No new reader device for our user, so the reader can't do
			// anything
			return false, nil, RekeyIncompleteError{}
		}
	}

	// If promotedReader is non-empty, then isWriter is true (see
	// check above).
	err = md.promoteReaders(readersToPromote)
	if err != nil {
		return false, nil, err
	}

	// Generate ephemeral keys to be used by addNewDevice,
	// incKeygen, or both. ePrivKey will be discarded at the end
	// of the function.
	ePubKey, ePrivKey, err :=
		km.config.Crypto().MakeRandomTLFEphemeralKeys()

	// Note: For MDv3, if incKeyGen is true, then all the
	// manipulations below aren't needed, since they'll just be
	// replaced by the new key generation. However, do them
	// anyway, as they may have some side effects, e.g. removing
	// server key halves.

	// If there's at least one new device, add that device to every key bundle.
	if addNewReaderDevice || addNewWriterDevice {
		start, end := md.KeyGenerationsToUpdate()
		if start >= end {
			return false, nil, errors.New(
				"Unexpected empty range for key generations to update")
		}
		cryptKeys := make([]kbfscrypto.TLFCryptKey, end-start)
		flags := getTLFCryptKeyAnyDevice
		if promptPaper {
			flags |= getTLFCryptKeyPromptPaper
		}
		for keyGen := start; keyGen < end; keyGen++ {
			currTlfCryptKey, err := km.getTLFCryptKey(
				ctx, md.ReadOnly(), keyGen, flags)
			if err != nil {
				return false, nil, err
			}
			cryptKeys[keyGen-start] = currTlfCryptKey
		}
		err = km.updateKeyBundles(ctx, md, updatedWriterKeys,
			updatedReaderKeys, ePubKey, ePrivKey, cryptKeys)
		if err != nil {
			return false, nil, err
		}
	}

	// Make sure the private MD is decrypted if it wasn't already.  We
	// have to do this here, before adding a new key generation, since
	// decryptMDPrivateData assumes that the MD is always encrypted
	// using the latest key gen.
	if !md.IsReadable() && len(md.GetSerializedPrivateMetadata()) > 0 {
		pmd, err := decryptMDPrivateData(
			ctx, km.config.Codec(), km.config.Crypto(),
			km.config.BlockCache(), km.config.BlockOps(), km, km.config.KBPKI(),
			km.config, km.config.Mode(), session.UID,
			md.GetSerializedPrivateMetadata(), md, md, km.log)
		if err != nil {
			return false, nil, err
		}
		md.data = pmd
	}

	defer func() {
		// On our way back out, update the md with the
		// resolved handle if at least part of a rekey was
		// performed.  Also, if we return true for mdChanged
		// with a nil error or RekeyIncompleteError{}, we must
		// call md.finalizeRekey() first.

		_, isRekeyIncomplete := err.(RekeyIncompleteError)
		if err == nil || isRekeyIncomplete {
			updateErr := md.updateFromTlfHandle(resolvedHandle)
			if updateErr != nil {
				mdChanged = false
				cryptKey = nil
				err = updateErr
			}

			if mdChanged {
				finalizeErr := md.finalizeRekey(
					km.config.Codec())
				if finalizeErr != nil {
					mdChanged = false
					cryptKey = nil
					err = finalizeErr
				}
			}
		}
	}()

	if !isWriter {
		if len(newReaderUsers) > 0 || addNewWriterDevice || incKeyGen {
			// If we're a reader but we haven't completed all the work, return
			// RekeyIncompleteError.
			return addNewReaderDeviceForSelf, nil, RekeyIncompleteError{}
		}
		// Otherwise, there's nothing left to do!
		return true, nil, nil
	} else if !incKeyGen {
		// we're done!
		return true, nil, nil
	}

	// Send rekey start notification once we're sure that this device
	// can perform the rekey.  Don't send this for the first key
	// generation though, since that's not really a "re"key.
	//
	// TODO: Shouldn't this happen earlier?
	if currKeyGen >= kbfsmd.FirstValidKeyGen {
		km.config.Reporter().Notify(ctx, rekeyNotification(
			ctx, km.config, resolvedHandle, false))
	}

	// Delete server-side key halves for any revoked devices, if
	// there are any previous key generations. Do this before
	// adding a new key generation, as MDv3 only keeps track of
	// the latest key generation.
	//
	// TODO: Add test coverage for this.
	if currKeyGen >= kbfsmd.FirstValidKeyGen {
		allRemovalInfo, err := md.revokeRemovedDevices(
			updatedWriterKeys, updatedReaderKeys)
		if err != nil {
			return false, nil, err
		}

		if len(allRemovalInfo) == 0 {
			return false, nil, errors.New(
				"Didn't revoke any devices, but indicated incrementing the key generation")
		}

		kops := km.config.KeyOps()
		for uid, userRemovalInfo := range allRemovalInfo {
			if userRemovalInfo.UserRemoved {
				km.log.CInfof(ctx, "Rekey %s: removed user %s entirely",
					md.TlfID(), uid)
			}
			for key, serverHalfIDs := range userRemovalInfo.DeviceServerHalfIDs {
				km.log.CInfof(ctx, "Rekey %s: removing %d server key halves "+
					"for device %s of user %s", md.TlfID(),
					len(serverHalfIDs), key, uid)
				for _, serverHalfID := range serverHalfIDs {
					err := kops.DeleteTLFCryptKeyServerHalf(
						ctx, uid, key, serverHalfID)
					if err != nil {
						return false, nil, err
					}
				}
			}
		}
	}

	pubKey, privKey, tlfCryptKey, err :=
		km.config.Crypto().MakeRandomTLFKeys()
	if err != nil {
		return false, nil, err
	}

	// Get the current TLF crypt key if needed. It's
	// symmetrically encrypted and appended to a list for MDv3
	// metadata.
	var currTLFCryptKey kbfscrypto.TLFCryptKey
	if md.StoresHistoricTLFCryptKeys() && currKeyGen >= kbfsmd.FirstValidKeyGen {
		flags := getTLFCryptKeyAnyDevice
		if promptPaper {
			flags |= getTLFCryptKeyPromptPaper
		}
		var err error
		currTLFCryptKey, err = km.getTLFCryptKey(
			ctx, md.ReadOnly(), currKeyGen, flags)
		if err != nil {
			return false, nil, err
		}
	}
	serverHalves, err := md.AddKeyGeneration(km.config.Codec(),
		updatedWriterKeys, updatedReaderKeys,
		ePubKey, ePrivKey, pubKey, privKey,
		currTLFCryptKey, tlfCryptKey)
	if err != nil {
		return false, nil, err
	}

	err = km.config.KeyOps().PutTLFCryptKeyServerHalves(ctx, serverHalves)
	if err != nil {
		return false, nil, err
	}

	return true, &tlfCryptKey, nil
}
515618
func (k *Keyfile) Load() (err error) {
	if len(k.fname) > 0 {
		var f *os.File
		f, err = os.Open(k.fname)
		if err == nil {
			err = k.read(f)
			f.Close()
		}
	}
	return
}
412785
func NewKeyring() *Keyring {
	return &Keyring{
		encKeys: make(map[PublicKey]SecretKey),
		sigKeys: make(map[SigningPublicKey]SigningSecretKey),
	}
}
648978
func (mod *TelegramBee) ReloadOptions(options bees.BeeOptions) {
	mod.SetOptions(options)

	apiKey := getAPIKey(&options)
	mod.apiKey = apiKey
}
449392
func (fkvs *FileKeyValueStore) Load(key interface{}) (interface{}, error) {
	file, err := fkvs.keySerializer(key)
	if err != nil {
		return nil, err
	}
	if _, err1 := os.Stat(file); os.IsNotExist(err1) {
		return nil, core.ErrKeyValueNotFound
	}
	bytes, err := ioutil.ReadFile(file) // nolint: gas
	if err != nil {
		return nil, err
	}
	if bytes == nil {
		return nil, core.ErrKeyValueNotFound
	}
	return fkvs.unmarshaller(bytes)
}
26746
func reload() {
	// Initialize
	enabledLock.Lock()
	enabled = make(map[string]bool)
	enabledLock.Unlock()

	// Set defaults and check env vars
	for _, id := range All {
		// Get the default value
		def := id.Default()

		// If we set it in the env var, default it to true
		key := fmt.Sprintf("TF_X_%s", strings.ToUpper(id.Env()))
		if v := os.Getenv(key); v != "" {
			def = v != "0"
		}

		// Set the default
		SetEnabled(id, def)
	}
}
343480
func LoadValidatorRing(version int64, ringSize int,
	getImmutable func(version int64) (*storage.ImmutableForest, error)) (*validator.Ring, error) {

	// In this method we have to page through previous version of the tree in order to reconstruct the in-memory
	// ring structure. The corner cases are a little subtle but printing the buckets helps

	// The basic idea is to load each version of the tree ringSize back, work out the difference that must have occurred
	// between each bucket in the ring, and apply each diff to the ring. Once the ring is full it is symmetrical (up to
	// a reindexing). If we are loading a chain whose height is less than the ring size we need to get the initial state
	// correct

	startVersion := version - int64(ringSize)
	if startVersion < 1 {
		// The ring will not be fully populated
		startVersion = 1
	}
	var err error
	// Read state to pull immutable forests from
	rs := &ReadState{}
	// Start with an empty ring - we want the initial bucket to have no cumulative power
	ring := validator.NewRing(nil, ringSize)
	// Load the IAVL state
	rs.Forest, err = getImmutable(startVersion)
	// Write the validator state at startVersion from IAVL tree into the ring's current bucket delta
	err = validator.Write(ring, rs)
	if err != nil {
		return nil, err
	}
	// Rotate, now we have [ {bucket 0: cum: {}, delta: {start version changes} }, {bucket 1: cum: {start version changes}, delta {}, ... ]
	// which is what we need (in particular we need this initial state if we are loading into a incompletely populated ring
	_, _, err = ring.Rotate()
	if err != nil {
		return nil, err
	}

	// Rebuild validator Ring
	for v := startVersion + 1; v <= version; v++ {
		// Update IAVL read state to version of interest
		rs.Forest, err = getImmutable(v)
		if err != nil {
			return nil, err
		}
		// Calculate the difference between the rings current cum and what is in state at this version
		diff, err := validator.Diff(ring.CurrentSet(), rs)
		if err != nil {
			return nil, err
		}
		// Write that diff into the ring (just like it was when it was originally written to setPower)
		err = validator.Write(ring, diff)
		if err != nil {
			return nil, err
		}
		// Rotate just like it was on the original commit
		_, _, err = ring.Rotate()
		if err != nil {
			return nil, err
		}
	}
	// Our ring should be the same up to symmetry in its index so we reindex to regain equality with the version we are loading
	// This is the head index we would have had if we had started from version 1 like the chain did
	ring.ReIndex(int(version % int64(ringSize)))
	return ring, err
}
508265
func (p *siprng) rekey() {
	var k [16]byte
	if _, err := io.ReadFull(rand.Reader, k[:]); err != nil {
		panic(err.Error())
	}
	p.k0 = binary.LittleEndian.Uint64(k[0:8])
	p.k1 = binary.LittleEndian.Uint64(k[8:16])
	p.ctr = 1
}
105390
func (d *daemonDiscoveryReloader) Reload(backendAddress, advertiseAddress string, clusterOpts map[string]string) error {
	d.Stop()

	heartbeat, backend, err := parseDiscoveryOptions(backendAddress, clusterOpts)
	if err != nil {
		return err
	}

	d.backend = backend
	d.ticker = time.NewTicker(heartbeat)
	d.readyCh = make(chan struct{})

	go d.advertiseHeartbeat(advertiseAddress)
	return nil
}
1353227
func (c *Client) ReloadConfig(config *Config) error {
	c.rpcLimiter.Store(rate.NewLimiter(config.RPCRate, config.RPCMaxBurst))
	return nil
}
1272150
func (r *Namespace) Reload() (*Namespace, error) {
	return r.collection.Get(r.Metadata.Name)
}
1248217
func (bow *Browser) Reload() error {
	if bow.state.Request != nil {
		return bow.httpRequest(bow.state.Request)
	}
	return errors.NewPageNotLoaded("Cannot reload, the previous request failed.")
}