// FindPKCS11Lib IS ONLY USED FOR TESTING
// This is a convenience function. Useful to self-configure, for tests where usual configuration is not
// available
506902
func FindPKCS11Lib() (lib, pin, label string) {
	//FIXME: Till we workout the configuration piece, look for the libraries in the familiar places
	lib = os.Getenv("PKCS11_LIB")
	if lib == "" {
		pin = "98765432"
		label = "ForFabric"
		possibilities := []string{
			"/usr/lib/softhsm/libsofthsm2.so",                            //Debian
			"/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so",           //Ubuntu
			"/usr/lib/s390x-linux-gnu/softhsm/libsofthsm2.so",            //Ubuntu
			"/usr/lib/powerpc64le-linux-gnu/softhsm/libsofthsm2.so",      //Power
			"/usr/local/Cellar/softhsm/2.1.0/lib/softhsm/libsofthsm2.so", //MacOS
		}
		for _, path := range possibilities {
			if _, err := os.Stat(path); !os.IsNotExist(err) {
				lib = path
				break
			}
		}
	} else {
		pin = os.Getenv("PKCS11_PIN")
		label = os.Getenv("PKCS11_LABEL")
	}
	return lib, pin, label
}
1100783
func GetChaincodeFromFS(ccname string, ccversion string) (CCPackage, error) {
	return ccInfoFSProvider.GetChaincode(ccname, ccversion)
}
41324
func (c *Cloud) FindVPCInfo(id string) (*fi.VPCInfo, error) {
	return nil, errors.New("not implemented")
}
584274
func (s *VPCRouterSetting) FindBelongsDHCPServer(ip net.IP) (int, *VPCRouterDHCPServerConfig) {
	target := ip.To4()
	for i, c := range s.DHCPServer.Config {
		start := net.ParseIP(c.RangeStart).To4()
		end := net.ParseIP(c.RangeStop).To4()

		if bytes.Compare(target, start) >= 0 && bytes.Compare(target, end) <= 0 {
			return i, c
		}
	}
	return -1, nil
}
915077
func FindEPConfigCHeader(basePath string, epFiles []os.FileInfo) string {
	for _, epFile := range epFiles {
		if epFile.Name() == CHeaderFileName {
			return filepath.Join(basePath, epFile.Name())
		}
	}
	return ""
}
1160230
func SetupHSMEnv(libraryPath string, libLoader pkcs11LibLoader) (
	IPKCS11Ctx, pkcs11.SessionHandle, error) {

	if libraryPath == "" {
		return nil, 0, errHSMNotPresent{err: "no library found"}
	}
	p := libLoader(libraryPath)

	if p == nil {
		return nil, 0, fmt.Errorf("failed to load library %s", libraryPath)
	}

	if err := p.Initialize(); err != nil {
		defer finalizeAndDestroy(p)
		return nil, 0, fmt.Errorf("found library %s, but initialize error %s", libraryPath, err.Error())
	}

	slots, err := p.GetSlotList(true)
	if err != nil {
		defer finalizeAndDestroy(p)
		return nil, 0, fmt.Errorf(
			"loaded library %s, but failed to list HSM slots %s", libraryPath, err)
	}
	// Check to see if we got any slots from the HSM.
	if len(slots) < 1 {
		defer finalizeAndDestroy(p)
		return nil, 0, fmt.Errorf(
			"loaded library %s, but no HSM slots found", libraryPath)
	}

	// CKF_SERIAL_SESSION: TRUE if cryptographic functions are performed in serial with the application; FALSE if the functions may be performed in parallel with the application.
	// CKF_RW_SESSION: TRUE if the session is read/write; FALSE if the session is read-only
	session, err := p.OpenSession(slots[0], pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION)
	if err != nil {
		defer cleanup(p, session)
		return nil, 0, fmt.Errorf(
			"loaded library %s, but failed to start session with HSM %s",
			libraryPath, err)
	}

	logrus.Debugf("Initialized PKCS11 library %s and started HSM session", libraryPath)
	return p, session, nil
}
1319791
func getKerberosClient() (*krb.Client, error) {
	configPath := os.Getenv("KRB5_CONFIG")
	if configPath == "" {
		configPath = "/etc/krb5.conf"
	}

	cfg, err := config.Load(configPath)
	if err != nil {
		return nil, err
	}

	// Determine the ccache location from the environment, falling back to the
	// default location.
	ccachePath := os.Getenv("KRB5CCNAME")
	if strings.Contains(ccachePath, ":") {
		if strings.HasPrefix(ccachePath, "FILE:") {
			ccachePath = strings.SplitN(ccachePath, ":", 2)[1]
		} else {
			return nil, fmt.Errorf("unusable ccache: %s", ccachePath)
		}
	} else if ccachePath == "" {
		u, err := user.Current()
		if err != nil {
			return nil, err
		}

		ccachePath = fmt.Sprintf("/tmp/krb5cc_%s", u.Uid)
	}

	ccache, err := credentials.LoadCCache(ccachePath)
	if err != nil {
		return nil, err
	}

	client, err := krb.NewClientFromCCache(ccache)
	if err != nil {
		return nil, err
	}

	return client.WithConfig(cfg), nil
}
624990
func findBuildFile(pkgPath string) (bool, string) {
	options := []string{"BUILD.bazel", "BUILD"}
	for _, b := range options {
		path := filepath.Join(pkgPath, b)
		info, err := os.Stat(path)
		if err == nil && !info.IsDir() {
			return true, path
		}
	}
	return false, filepath.Join(pkgPath, "BUILD")
}
227544
func ReloadPKCS11ContextHandle(lib, label, pin string, opts ...Options) (*ContextHandle, error) {
	return getInstance(&pkcs11CtxCacheKey{lib: lib, label: label, pin: pin, opts: getCtxOpts(opts...)}, true)
}
801265
func GodelPropsDistPkgInfo(projectDir string) (godelgetter.PkgSrc, error) {
	wrapperSpec, err := specdir.New(projectDir, layout.WrapperSpec(), nil, specdir.Validate)
	if err != nil {
		return nil, errors.Wrapf(err, "unable to create wrapper spec")
	}
	configDir := wrapperSpec.Path(layout.WrapperConfigDir)

	propsFilePath := path.Join(configDir, fmt.Sprintf("%s.properties", layout.AppName))
	props, err := readPropertiesFile(propsFilePath)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to read properties file %s", propsFilePath)
	}
	url, ok := props[propertiesURLKey]
	if !ok {
		return nil, errors.Wrapf(err, "properties file %s does not contain key %s", propsFilePath, propertiesURLKey)
	}
	checksum := props[propertiesChecksumKey]
	return godelgetter.NewPkgSrc(url, checksum), nil
}
419077
func findPaperKeys(m libkb.MetaContext, me *libkb.User) (*libkb.DeviceWithKeys, error) {
	cki := me.GetComputedKeyInfos()
	if cki == nil {
		return nil, fmt.Errorf("no computed key infos")
	}
	bdevs := cki.PaperDevices()
	if len(bdevs) == 0 {
		return nil, libkb.NoPaperKeysError{}
	}

	passphrase, err := libkb.GetPaperKeyPassphrase(m, m.UIs().SecretUI, me.GetName(), nil, nil)
	if err != nil {
		return nil, err
	}

	return matchPaperKey(m, me, passphrase)
}
1270879
func findTxOutByPkScript(txn *wire.MsgTx,
	pkScript []byte) (uint32, *wire.TxOut, error) {

	found, index := input.FindScriptOutputIndex(txn, pkScript)
	if !found {
		return 0, nil, ErrOutputNotFound
	}

	return index, txn.TxOut[index], nil
}
1130201
func (c *Client) FindSources(ctx context.Context, opt platform.FindOptions) ([]*platform.Source, int, error) {
	ss := []*platform.Source{}
	err := c.db.View(func(tx *bolt.Tx) error {
		srcs, err := c.findSources(ctx, tx, opt)
		if err != nil {
			return err
		}
		ss = srcs
		return nil
	})

	if err != nil {
		return nil, 0, &platform.Error{
			Op:  platform.OpFindSources,
			Err: err,
		}
	}

	return ss, len(ss), nil
}
1200426
func kbfsLibdokanLockFile(
	fname C.LPCWSTR,
	offset C.LONGLONG,
	length C.LONGLONG,
	pfi C.PDOKAN_FILE_INFO) C.NTSTATUS {
	debugf("LockFile '%v' %v", d16{fname}, *pfi)
	ctx, cancel := getContext(pfi)
	if cancel != nil {
		defer cancel()
	}

	err := getfi(pfi).LockFile(ctx, makeFI(fname, pfi), int64(offset), int64(length))
	return errToNT(err)
}
1312618
func (c *VSphereCloud) FindVPCInfo(id string) (*fi.VPCInfo, error) {
	glog.Warning("FindVPCInfo not (yet) implemented on VSphere")
	return nil, nil
}
962309
func (handle *ContextHandle) createNewPKCS11Ctx() *mPkcs11.Ctx {
	newCtx := mPkcs11.New(handle.lib)
	if newCtx == nil {
		logger.Warn("Failed to recreate new context for given library")
		return nil
	}

	//initialize new context
	err := newCtx.Initialize()
	if err != nil {
		if err != mPkcs11.Error(mPkcs11.CKR_CRYPTOKI_ALREADY_INITIALIZED) {
			logger.Warn("Failed to initialize context:", err)
			return nil
		}
	}

	return newCtx
}
121452
func findFolderList(filename string) string {
	// KBFS always sets the filenames in the protocol to be like
	// `/keybase/private/alice/...`, regardless of the OS.  So we just
	// need to split by `/` and take the third component.
	components := strings.Split(filename, "/")
	if len(components) < 3 {
		return ""
	}
	return components[2]
}