// ClearPrivateFolderMD implements the KBFSOps interface for
// folderBranchOps.
350713
func (fbo *folderBranchOps) ClearPrivateFolderMD(ctx context.Context) {
	func() {
		// Cancel the edits goroutine and forget the old history, evem
		// for public folders, since some of the state in the history
		// is dependent on your login state.
		fbo.editsLock.Lock()
		defer fbo.editsLock.Unlock()
		if fbo.cancelEdits != nil {
			fbo.cancelEdits()
			fbo.cancelEdits = nil
		}
		fbo.editHistory = kbfsedits.NewTlfHistory()
		// Allow the edit monitor to be re-launched later whenever the
		// MD is set again.
		fbo.launchEditMonitor = sync.Once{}
		fbo.convLock.Lock()
		defer fbo.convLock.Unlock()
		fbo.convID = nil
	}()

	lState := makeFBOLockState()
	fbo.mdWriterLock.Lock(lState)
	defer fbo.mdWriterLock.Unlock(lState)
	fbo.headLock.Lock(lState)
	defer fbo.headLock.Unlock(lState)

	fbo.blocks.ClearChargedTo(lState)

	if fbo.folderBranch.Tlf.Type() == tlf.Public {
		return
	}

	if fbo.head == (ImmutableRootMetadata{}) {
		// Nothing to clear.
		return
	}

	fbo.log.CDebugf(ctx, "Clearing folder MD")

	// First cancel the background goroutine that's registered for
	// updates, because the next time we set the head in this FBO
	// we'll launch another one.
	fbo.cancelUpdatesLock.Lock()
	defer fbo.cancelUpdatesLock.Unlock()
	if fbo.cancelUpdates != nil {
		fbo.cancelUpdates()
		select {
		case <-fbo.updateDoneChan:
		case <-ctx.Done():
			fbo.log.CDebugf(
				ctx, "Context canceled before updater was canceled")
			return
		}
		fbo.config.MDServer().CancelRegistration(ctx, fbo.id())
	}

	fbo.head = ImmutableRootMetadata{}
	fbo.headStatus = headUntrusted
	fbo.latestMergedRevision = kbfsmd.RevisionUninitialized
	fbo.hasBeenCleared = true
}
142359
func removePrivateKeyMaterial(o *kops.Keyset) *kops.Keyset {
	copy := o.DeepCopy()

	for i := range copy.Spec.Keys {
		copy.Spec.Keys[i].PrivateMaterial = nil
	}

	return copy
}
1142182
func NewPrivateKeyFileStorage(baseDir, fileExt string) (*FilesystemStore, error) {
	baseDir = filepath.Join(baseDir, notary.PrivDir)
	myStore, err := NewFileStore(baseDir, fileExt)
	myStore.migrateTo0Dot4()
	return myStore, err
}
524301
func (md *MDOpsStandard) ResolveBranch(
	ctx context.Context, id tlf.ID, bid kbfsmd.BranchID, _ []kbfsblock.ID,
	rmd *RootMetadata, verifyingKey kbfscrypto.VerifyingKey) (
	ImmutableRootMetadata, error) {
	// Put the MD first.
	irmd, err := md.Put(ctx, rmd, verifyingKey, nil, keybase1.MDPriorityNormal)
	if err != nil {
		return ImmutableRootMetadata{}, err
	}

	// Prune the branch ia the journal, if there is one.  If the
	// client fails before this is completed, we'll need to check for
	// resolutions on the next restart (see KBFS-798).
	err = md.PruneBranch(ctx, id, bid)
	if err != nil {
		return ImmutableRootMetadata{}, err
	}
	return irmd, nil
}
357743
func (fbo *folderBranchOps) setHeadPredecessorLocked(ctx context.Context,
	lState *kbfssync.LockState, md ImmutableRootMetadata) error {
	fbo.mdWriterLock.AssertLocked(lState)
	fbo.headLock.AssertLocked(lState)
	if fbo.head == (ImmutableRootMetadata{}) {
		return errors.New("Unexpected nil head in setHeadPredecessorLocked")
	}
	if fbo.head.Revision() <= kbfsmd.RevisionInitial {
		return errors.Errorf("setHeadPredecessorLocked unexpectedly called with revision %d", fbo.head.Revision())
	}

	if fbo.head.MergedStatus() != kbfsmd.Unmerged {
		return errors.New("Unexpected merged head in setHeadPredecessorLocked")
	}

	err := md.CheckValidSuccessor(md.mdID, fbo.head.ReadOnly())
	if err != nil {
		return err
	}

	oldHandle := fbo.head.GetTlfHandle()
	newHandle := md.GetTlfHandle()

	// The two handles must be the same, since no rekeying is done
	// while unmerged.

	eq, err := oldHandle.Equals(fbo.config.Codec(), *newHandle)
	if err != nil {
		return err
	}
	if !eq {
		return errors.Errorf(
			"head handle %v unexpectedly not equal to new handle = %v",
			oldHandle, newHandle)
	}

	return fbo.setHeadLocked(ctx, lState, md, headTrusted, mdToCommitType(md))
}
1350454
func DumpPrivateMetadata(
	codec kbfscodec.Codec, serializedPMDLength int, pmd PrivateMetadata) (string, error) {
	s := fmt.Sprintf("Size: %d bytes\n", serializedPMDLength)

	eq, err := kbfscodec.Equal(codec, pmd, PrivateMetadata{})
	if err != nil {
		return "", err
	}

	if eq {
		s += "<Undecryptable>\n"
	} else {
		c := kbfsmd.DumpConfig()
		// Hardcode the indent level, which depends on the
		// position of the Ops list.
		indent := strings.Repeat(c.Indent, 4)

		var pmdCopy PrivateMetadata
		kbfscodec.Update(codec, &pmdCopy, pmd)
		ops := pmdCopy.Changes.Ops
		for i, op := range ops {
			ops[i] = verboseOp{op, indent}
		}

		s += c.Sdump(pmdCopy)
	}
	return s, nil
}
768644
func (u *Unit) ClearResolved() error {
	ops := []txn.Op{{
		C:      unitsC,
		Id:     u.doc.DocID,
		Assert: txn.DocExists,
		Update: bson.D{{"$set", bson.D{{"resolved", ResolvedNone}}}},
	}}
	err := u.st.db().RunTransaction(ops)
	if err != nil {
		return fmt.Errorf("cannot clear resolved mode for unit %q: %v", u, errors.NotFoundf("unit"))
	}
	u.doc.Resolved = ResolvedNone
	return nil
}
327353
func clearActionFunc(manager Manager, filters ...Filter) error {
	myAlerts, err := manager.Enumerate(filters...)
	if err != nil {
		return err
	}

	for _, myAlert := range myAlerts {
		myAlert.Cleared = true
		if err := manager.Raise(myAlert); err != nil {
			return err
		}
	}

	return nil
}
834448
func CleanKeyLocks(lockDir string) error {
	f, err := os.Open(lockDir)
	if err != nil {
		return errwrap.Wrap(errors.New("error opening lockDir"), err)
	}
	defer f.Close()
	files, err := f.Readdir(0)
	if err != nil {
		return errwrap.Wrap(errors.New("error getting lock files list"), err)
	}
	for _, f := range files {
		filename := filepath.Join(lockDir, f.Name())
		keyLock, err := TryExclusiveKeyLock(lockDir, f.Name())
		if err == ErrLocked {
			continue
		}
		if err != nil {
			return err
		}

		err = os.Remove(filename)
		if err != nil {
			keyLock.Close()
			return errwrap.Wrap(errors.New("error removing lock file"), err)
		}
		keyLock.Close()
	}
	return nil
}
538891
func (gp *EpgPolicy) Clear() error {
	key := fmt.Sprintf(policyConfigPath, gp.ID)
	return gp.StateDriver.ClearState(key)
}
630111
func (r *repository) ClearDelegationPaths(name data.RoleName) error {

	if !data.IsDelegation(name) {
		return data.ErrInvalidRole{Role: name, Reason: "invalid delegation role name"}
	}

	logrus.Debugf(`Removing all paths from delegation "%s"\n`, name)

	tdJSON, err := json.Marshal(&changelist.TUFDelegation{
		ClearAllPaths: true,
	})
	if err != nil {
		return err
	}

	template := newUpdateDelegationChange(name, tdJSON)
	return addChange(r.changelist, template, name)
}
1361668
func TryLoadPrivatePublicKeyFromDisk(pkiPath, name string) (*rsa.PrivateKey, *rsa.PublicKey, error) {
	privateKeyPath := pathForKey(pkiPath, name)

	// Parse the private key from a file
	privKey, err := keyutil.PrivateKeyFromFile(privateKeyPath)
	if err != nil {
		return nil, nil, errors.Wrapf(err, "couldn't load the private key file %s", privateKeyPath)
	}

	publicKeyPath := pathForPublicKey(pkiPath, name)

	// Parse the public key from a file
	pubKeys, err := keyutil.PublicKeysFromFile(publicKeyPath)
	if err != nil {
		return nil, nil, errors.Wrapf(err, "couldn't load the public key file %s", publicKeyPath)
	}

	// Allow RSA format only
	k, ok := privKey.(*rsa.PrivateKey)
	if !ok {
		return nil, nil, errors.Errorf("the private key file %s isn't in RSA format", privateKeyPath)
	}

	p := pubKeys[0].(*rsa.PublicKey)

	return k, p, nil
}
316734
func (fbo *folderBlockOps) cleanUpUnusedBlocks(ctx context.Context,
	md ReadOnlyRootMetadata, syncState fileSyncState, fbm *folderBlockManager) error {
	numToClean := len(syncState.si.toCleanIfUnused)
	if numToClean == 0 {
		return nil
	}

	// What blocks are referenced in the successful MD?
	refs := make(map[data.BlockPointer]bool)
	for _, op := range md.data.Changes.Ops {
		for _, ptr := range op.Refs() {
			if ptr == data.ZeroPtr {
				panic("Unexpected zero ref ptr in a sync MD revision")
			}
			refs[ptr] = true
		}
		for _, update := range op.allUpdates() {
			if update.Ref == data.ZeroPtr {
				panic("Unexpected zero update ref ptr in a sync MD revision")
			}

			refs[update.Ref] = true
		}
	}

	// For each MD to clean, clean up the old failed blocks
	// immediately if the merge status matches the successful put, if
	// they didn't get referenced in the successful put.  If the merge
	// status is different (e.g., we ended up on a conflict branch),
	// clean it up only if the original revision failed.  If the same
	// block appears more than once, the one with a different merged
	// status takes precedence (which will always come earlier in the
	// list of MDs).
	blocksSeen := make(map[data.BlockPointer]bool)
	for _, oldMD := range syncState.si.toCleanIfUnused {
		bdType := blockDeleteAlways
		if oldMD.md.MergedStatus() != md.MergedStatus() {
			bdType = blockDeleteOnMDFail
		}

		failedBps := newBlockPutStateMemory(oldMD.bps.numBlocks())
		for _, ptr := range oldMD.bps.ptrs() {
			if ptr == data.ZeroPtr {
				panic("Unexpected zero block ptr in an old sync MD revision")
			}
			if blocksSeen[ptr] {
				continue
			}
			blocksSeen[ptr] = true
			if refs[ptr] && bdType == blockDeleteAlways {
				continue
			}
			failedBps.blockStates[ptr] = blockState{}
			fbo.vlog.CLogf(
				ctx, libkb.VLog1, "Cleaning up block %v from a previous "+
					"failed revision %d (oldMD is %s, bdType=%d)", ptr,
				oldMD.md.Revision(), oldMD.md.MergedStatus(), bdType)
		}

		if len(failedBps.blockStates) > 0 {
			fbm.cleanUpBlockState(oldMD.md, failedBps, bdType)
		}
	}
	return nil
}
1282215
func (fbm *folderBlockManager) deleteBlockRefs(ctx context.Context,
	tlfID tlf.ID, ptrs []data.BlockPointer) ([]kbfsblock.ID, error) {
	return fbm.doChunkedDowngrades(ctx, tlfID, ptrs, false)
}
157817
func (r *Repository) GetPrivate() bool {
	if r == nil || r.Private == nil {
		return false
	}
	return *r.Private
}
1062617
func (mcp *MCP23S17) ClearInterrupts(port int) {
	var address byte
	address = INTCAPA
	if port == GPIOA {
		address = INTCAPB
	}
	mcp.Read(address)
}
832720
func (pset *Permset) ClearPerms() error {
	rv, _ := C.acl_clear_perms(pset.p)
	if rv < 0 {
		return fmt.Errorf("unable to clear perms")
	}
	return nil
}