// executeKeyringOp executes the keyring-related operation in the request
// on either the WAN or LAN pools.
765519
func (m *Internal) executeKeyringOp(
	args *structs.KeyringRequest,
	reply *structs.KeyringResponses,
	wan bool) {

	if wan {
		mgr := m.srv.KeyManagerWAN()
		m.executeKeyringOpMgr(mgr, args, reply, wan, "")
	} else {
		segments := m.srv.LANSegments()
		for name, segment := range segments {
			mgr := segment.KeyManager()
			m.executeKeyringOpMgr(mgr, args, reply, wan, name)
		}
	}
}
213212
func (km *KeyManagerStandard) GetTLFCryptKeyForMDDecryption(
	ctx context.Context, kmdToDecrypt, kmdWithKeys libkey.KeyMetadata) (
	tlfCryptKey kbfscrypto.TLFCryptKey, err error) {
	return km.getTLFCryptKey(ctx, kmdWithKeys, kmdToDecrypt.LatestKeyGeneration(),
		getTLFCryptKeyAnyDevice|getTLFCryptKeyDoCache)
}
1072270
func (s *Script) Execute(conn *Conn, keyCount int, keysAndArgs ...interface{}) (*Reply, error) {
	s.lock.RLock()
	defer s.lock.RUnlock()
	if s.body == "" {
		return nil, ErrEmptyScript
	}
	args := make([]interface{}, len(keysAndArgs)+2)
	args[0] = s.sha
	args[1] = keyCount
	for i := range keysAndArgs {
		args[i+2] = keysAndArgs[i]
	}
	rep, err := NewCommand("EVALSHA", args...).Run(conn)
	if err != nil {
		return nil, err
	}
	if !rep.IsError() {
		return rep, nil
	}
	errorMessage, _ := rep.Error()
	if !strings.HasPrefix(errorMessage, "NOSCRIPT") {
		return rep, nil
	}
	args[0] = s.body
	return NewCommand("EVAL", args...).Run(conn)
}
503629
func (c *Client) BitOp(operation, destkey, key string, keys ...string) (int, error) {
	a := append([]string{"BITOP", operation, destkey, key}, keys...)
	v, err := c.execOnFirst(true, vstr2iface(a)...)
	if err != nil {
		return 0, err
	}
	return iface2int(v)
}
674101
func (a *Core) GetKeyAuthorization(token string) (string, error) {
	return a.jws.GetKeyAuthorization(token)
}
392099
func (p *PolicyAuthorizer) KeyringWrite() bool {
	if allow, recurse := enforce(p.keyringRule, PolicyWrite); !recurse {
		return allow
	}

	return p.parent.KeyringWrite()
}
817715
func KeyRing(r io.Reader) (openpgp.KeyRing, error) {
	// decode gpgkey file
	p, err := armor.Decode(r)
	if err != nil {
		return nil, err
	}

	// extract keys
	return openpgp.ReadKeyRing(p.Body)
}
601299
func (c *Cluster) executeN1qlQuery(ctx context.Context, traceCtx opentracing.SpanContext, opts map[string]interface{},
	provider httpProvider, cancel context.CancelFunc) (*QueryResults, error) {

	reqJSON, err := json.Marshal(opts)
	if err != nil {
		return nil, errors.Wrap(err, "failed to marshal query request body")
	}

	req := &gocbcore.HttpRequest{
		Service: gocbcore.N1qlService,
		Path:    "/query/service",
		Method:  "POST",
		Context: ctx,
		Body:    reqJSON,
	}

	dtrace := opentracing.GlobalTracer().StartSpan("dispatch", opentracing.ChildOf(traceCtx))

	resp, err := provider.DoHttpRequest(req)
	if err != nil {
		dtrace.Finish()
		if err == gocbcore.ErrNoN1qlService {
			return nil, serviceNotFoundError{}
		}

		// as we're effectively manually timing out the request using cancellation we need
		// to check if the original context has timed out as err itself will only show as canceled
		if ctx.Err() == context.DeadlineExceeded {
			return nil, timeoutError{}
		}
		return nil, errors.Wrap(err, "could not complete query http request")
	}

	dtrace.Finish()

	// TODO(brett19): place the server_duration in the right place...
	// srvDuration, _ := time.ParseDuration(n1qlResp.Metrics.ExecutionTime)
	// strace.SetTag("server_duration", srvDuration)

	epInfo, err := url.Parse(resp.Endpoint)
	if err != nil {
		logWarnf("Failed to parse N1QL source address")
		epInfo = &url.URL{
			Host: "",
		}
	}

	strace := opentracing.GlobalTracer().StartSpan("streaming", opentracing.ChildOf(traceCtx))

	queryResults := &QueryResults{
		metadata: QueryResultsMetadata{
			sourceAddr: epInfo.Host,
		},
		httpStatus: resp.StatusCode,
	}

	streamResult, err := newStreamingResults(resp.Body, queryResults.readAttribute)
	if err != nil {
		strace.Finish()
		return nil, err
	}

	err = streamResult.readAttributes()
	if err != nil {
		bodyErr := streamResult.Close()
		if bodyErr != nil {
			logDebugf("Failed to close socket (%s)", bodyErr.Error())
		}
		strace.Finish()
		return nil, err
	}

	queryResults.streamResult = streamResult

	strace.SetTag("couchbase.operation_id", queryResults.metadata.requestID)

	if streamResult.HasRows() {
		queryResults.strace = strace
		queryResults.cancel = cancel
		queryResults.ctx = ctx
	} else {
		bodyErr := streamResult.Close()
		if bodyErr != nil {
			logDebugf("Failed to close response body, %s", bodyErr.Error())
		}
		strace.Finish()

		// There are no rows and there are errors so fast fail
		if queryResults.err != nil {
			return nil, queryResults.err
		}
	}
	return queryResults, nil
}
925993
func (csp *impl) KeyGen(opts bccsp.KeyGenOpts) (k bccsp.Key, err error) {
	// Validate arguments
	if opts == nil {
		return nil, errors.New("Invalid Opts parameter. It must not be nil")
	}

	// Parse algorithm
	switch opts.(type) {
	case *bccsp.ECDSAKeyGenOpts:
		ski, pub, err := csp.generateECKey(csp.conf.ellipticCurve, opts.Ephemeral())
		if err != nil {
			return nil, errors.Wrapf(err, "Failed generating ECDSA key")
		}
		k = &ecdsaPrivateKey{ski, ecdsaPublicKey{ski, pub}}

	case *bccsp.ECDSAP256KeyGenOpts:
		ski, pub, err := csp.generateECKey(oidNamedCurveP256, opts.Ephemeral())
		if err != nil {
			return nil, errors.Wrapf(err, "Failed generating ECDSA P256 key")
		}

		k = &ecdsaPrivateKey{ski, ecdsaPublicKey{ski, pub}}

	case *bccsp.ECDSAP384KeyGenOpts:
		ski, pub, err := csp.generateECKey(oidNamedCurveP384, opts.Ephemeral())
		if err != nil {
			return nil, errors.Wrapf(err, "Failed generating ECDSA P384 key")
		}

		k = &ecdsaPrivateKey{ski, ecdsaPublicKey{ski, pub}}

	default:
		return csp.BCCSP.KeyGen(opts)
	}

	return k, nil
}
703524
func (sn *VTGateSession) Execute(ctx context.Context, query string, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
	session, res, err := sn.impl.Execute(ctx, sn.session, query, bindVars)
	sn.session = session
	return res, err
}
147143
func StringKeySet(theMap interface{}) String {
	v := reflect.ValueOf(theMap)
	ret := String{}

	for _, keyValue := range v.MapKeys() {
		ret.Insert(keyValue.Interface().(string))
	}
	return ret
}
450890
func (client *Client) ExecuteHook(ctx context.Context, tablet *topodatapb.Tablet, hk *hook.Hook) (*hook.HookResult, error) {
	cc, c, err := client.dial(tablet)
	if err != nil {
		return nil, err
	}
	defer cc.Close()
	hr, err := c.ExecuteHook(ctx, &tabletmanagerdatapb.ExecuteHookRequest{
		Name:       hk.Name,
		Parameters: hk.Parameters,
		ExtraEnv:   hk.ExtraEnv,
	})
	if err != nil {
		return nil, err
	}
	return &hook.HookResult{
		ExitStatus: int(hr.ExitStatus),
		Stdout:     hr.Stdout,
		Stderr:     hr.Stderr,
	}, nil
}
321448
func (jolokiaClient *JolokiaClient) executePostRequestCallback(pattern string, wrapper func() ([]byte, error)) (string, error) {
	jsonReq, wrapError := wrapper()
	if wrapError != nil {
		return "", fmt.Errorf("JSON Wrap Failed: %v", wrapError)
	}
	requestUrl := jolokiaClient.url
	if pattern != "" {
		requestUrl = requestUrl + "/?" + pattern
	}
	request := &httpRequest{Url: requestUrl, Body: jsonReq}
	response, httpErr := performPostRequest(request, jolokiaClient.user, jolokiaClient.pass)
	if httpErr != nil {
		return "", fmt.Errorf("HTTP Request Failed: %v", httpErr)
	}
	if response.StatusCode != 200 {
		return "", fmt.Errorf("HTTP Request Error Code: %v", response.Status)
	}
	jolokiaResponse := string(response.Body)
	return jolokiaResponse, nil
}
1151722
func (m *Internal) KeyringOperation(
	args *structs.KeyringRequest,
	reply *structs.KeyringResponses) error {

	// Check ACLs
	rule, err := m.srv.ResolveToken(args.Token)
	if err != nil {
		return err
	}
	if rule != nil {
		switch args.Operation {
		case structs.KeyringList:
			if !rule.KeyringRead() {
				return fmt.Errorf("Reading keyring denied by ACLs")
			}
		case structs.KeyringInstall:
			fallthrough
		case structs.KeyringUse:
			fallthrough
		case structs.KeyringRemove:
			if !rule.KeyringWrite() {
				return fmt.Errorf("Modifying keyring denied due to ACLs")
			}
		default:
			panic("Invalid keyring operation")
		}
	}

	// Only perform WAN keyring querying and RPC forwarding once
	if !args.Forwarded && m.srv.serfWAN != nil {
		args.Forwarded = true
		m.executeKeyringOp(args, reply, true)
		return m.srv.globalRPC("Internal.KeyringOperation", args, reply)
	}

	// Query the LAN keyring of this node's DC
	m.executeKeyringOp(args, reply, false)
	return nil
}
484974
func (vtg *VTGate) ExecuteBatch(ctx context.Context, request *vtgatepb.ExecuteBatchRequest) (response *vtgatepb.ExecuteBatchResponse, err error) {
	defer vtg.server.HandlePanic(&err)
	ctx = withCallerIDContext(ctx, request.CallerId)
	sqlQueries := make([]string, len(request.Queries))
	bindVars := make([]map[string]*querypb.BindVariable, len(request.Queries))
	for queryNum, query := range request.Queries {
		sqlQueries[queryNum] = query.Sql
		bindVars[queryNum] = query.BindVariables
	}
	// Handle backward compatibility.
	session := request.Session
	if session == nil {
		session = &vtgatepb.Session{Autocommit: true}
	}
	if session.TargetString == "" {
		session.TargetString = request.KeyspaceShard + "@" + topoproto.TabletTypeLString(request.TabletType)
	}
	if session.Options == nil {
		session.Options = request.Options
	}
	session, results, err := vtg.server.ExecuteBatch(ctx, session, sqlQueries, bindVars)
	return &vtgatepb.ExecuteBatchResponse{
		Results: sqltypes.QueryResponsesToProto3(results),
		Session: session,
		Error:   vterrors.ToVTRPC(err),
	}, nil
}
1268227
func (p *PolicyAuthorizer) executeCodePolicy(policy *Sentinel, scope sentinel.ScopeFn) bool {
	if p.sentinel == nil {
		return true
	}

	if policy.Code == "" || scope == nil {
		return true
	}

	enforcement := policy.EnforcementLevel
	if enforcement == "" {
		enforcement = DefaultPolicyEnforcementLevel
	}

	return p.sentinel.Execute(policy.Code, enforcement, scope())
}
1281077
func (m *Mux) ExecuteString(name string, binding interface{}, options ...map[string]interface{}) (result string, err error) {
	out := m.buffer.Get()
	defer m.buffer.Put(out)
	err = m.ExecuteWriter(out, name, binding, options...)
	if err == nil {
		result = out.String()
	}
	return
}