// pathRoleTagUpdate is used to create an EC2 instance tag which will
// identify the Vault resources that the instance will be authorized for.
556837
func (b *backend) pathRoleTagUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	roleName := strings.ToLower(data.Get("role").(string))
	if roleName == "" {
		return logical.ErrorResponse("missing role"), nil
	}

	// Fetch the role entry
	roleEntry, err := b.lockedAWSRole(ctx, req.Storage, roleName)
	if err != nil {
		return nil, err
	}
	if roleEntry == nil {
		return logical.ErrorResponse(fmt.Sprintf("entry not found for role %s", roleName)), nil
	}

	// If RoleTag is empty, disallow creation of tag.
	if roleEntry.RoleTag == "" {
		return logical.ErrorResponse("tag creation is not enabled for this role"), nil
	}

	// There should be a HMAC key present in the role entry
	if roleEntry.HMACKey == "" {
		// Not being able to find the HMACKey is an internal error
		return nil, fmt.Errorf("failed to find the HMAC key")
	}

	resp := &logical.Response{}

	// Instance ID is an optional field.
	instanceID := strings.ToLower(data.Get("instance_id").(string))

	// If no policies field was not supplied, then the tag should inherit all the policies
	// on the role. But, it was provided, but set to empty explicitly, only "default" policy
	// should be inherited. So, by leaving the policies var unset to anything when it is not
	// supplied, we ensure that it inherits all the policies on the role.
	var policies []string
	policiesRaw, ok := data.GetOk("policies")
	if ok {
		policies = policyutil.ParsePolicies(policiesRaw)
	}
	if !strutil.StrListSubset(roleEntry.Policies, policies) {
		resp.AddWarning("Policies on the tag are not a subset of the policies set on the role. Login will not be allowed with this tag unless the role policies are updated.")
	}

	// This is an optional field.
	disallowReauthentication := data.Get("disallow_reauthentication").(bool)

	// This is an optional field.
	allowInstanceMigration := data.Get("allow_instance_migration").(bool)
	if allowInstanceMigration && !roleEntry.AllowInstanceMigration {
		resp.AddWarning("Role does not allow instance migration. Login will not be allowed with this tag unless the role value is updated.")
	}

	if disallowReauthentication && allowInstanceMigration {
		return logical.ErrorResponse("cannot set both disallow_reauthentication and allow_instance_migration"), nil
	}

	// max_ttl for the role tag should be less than the max_ttl set on the role.
	maxTTL := time.Duration(data.Get("max_ttl").(int)) * time.Second

	// max_ttl on the tag should not be greater than the system view's max_ttl value.
	if maxTTL > b.System().MaxLeaseTTL() {
		resp.AddWarning(fmt.Sprintf("Given max TTL of %d is greater than the mount maximum of %d seconds, and will be capped at login time.", maxTTL/time.Second, b.System().MaxLeaseTTL()/time.Second))
	}
	// If max_ttl is set for the role, check the bounds for tag's max_ttl value using that.
	if roleEntry.MaxTTL != time.Duration(0) && maxTTL > roleEntry.MaxTTL {
		resp.AddWarning(fmt.Sprintf("Given max TTL of %d is greater than the role maximum of %d seconds, and will be capped at login time.", maxTTL/time.Second, roleEntry.MaxTTL/time.Second))
	}

	if maxTTL < time.Duration(0) {
		return logical.ErrorResponse("max_ttl cannot be negative"), nil
	}

	// Create a random nonce.
	nonce, err := createRoleTagNonce()
	if err != nil {
		return nil, err
	}

	// Create a role tag out of all the information provided.
	rTagValue, err := createRoleTagValue(&roleTag{
		Version:                  roleTagVersion,
		Role:                     roleName,
		Nonce:                    nonce,
		Policies:                 policies,
		MaxTTL:                   maxTTL,
		InstanceID:               instanceID,
		DisallowReauthentication: disallowReauthentication,
		AllowInstanceMigration:   allowInstanceMigration,
	}, roleEntry)
	if err != nil {
		return nil, err
	}

	// Return the key to be used for the tag and the value to be used for that tag key.
	// This key value pair should be set on the EC2 instance.
	resp.Data = map[string]interface{}{
		"tag_key":   roleEntry.RoleTag,
		"tag_value": rTagValue,
	}

	return resp, nil
}
176480
func (b *backend) pathRoleSecretIDLookupUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	roleName := data.Get("role_name").(string)
	if roleName == "" {
		return logical.ErrorResponse("missing role_name"), nil
	}

	secretID := data.Get("secret_id").(string)
	if secretID == "" {
		return logical.ErrorResponse("missing secret_id"), nil
	}

	lock := b.roleLock(roleName)
	lock.RLock()
	defer lock.RUnlock()

	// Fetch the role
	role, err := b.roleEntry(ctx, req.Storage, roleName)
	if err != nil {
		return nil, err
	}
	if role == nil {
		return nil, fmt.Errorf("role %q does not exist", roleName)
	}

	// Create the HMAC of the secret ID using the per-role HMAC key
	secretIDHMAC, err := createHMAC(role.HMACKey, secretID)
	if err != nil {
		return nil, errwrap.Wrapf("failed to create HMAC of secret_id: {{err}}", err)
	}

	// Create the HMAC of the roleName using the per-role HMAC key
	roleNameHMAC, err := createHMAC(role.HMACKey, role.name)
	if err != nil {
		return nil, errwrap.Wrapf("failed to create HMAC of role_name: {{err}}", err)
	}

	// Create the index at which the secret_id would've been stored
	entryIndex := fmt.Sprintf("%s%s/%s", role.SecretIDPrefix, roleNameHMAC, secretIDHMAC)

	secretLock := b.secretIDLock(secretIDHMAC)
	secretLock.Lock()
	defer secretLock.Unlock()

	secretIDEntry, err := b.nonLockedSecretIDStorageEntry(ctx, req.Storage, role.SecretIDPrefix, roleNameHMAC, secretIDHMAC)
	if err != nil {
		return nil, err
	}
	if secretIDEntry == nil {
		return nil, nil
	}

	// If a secret ID entry does not have a corresponding accessor
	// entry, revoke the secret ID immediately
	accessorEntry, err := b.secretIDAccessorEntry(ctx, req.Storage, secretIDEntry.SecretIDAccessor, role.SecretIDPrefix)
	if err != nil {
		return nil, errwrap.Wrapf("failed to read secret ID accessor entry: {{err}}", err)
	}
	if accessorEntry == nil {
		if err := req.Storage.Delete(ctx, entryIndex); err != nil {
			return nil, errwrap.Wrapf(fmt.Sprintf("error deleting secret ID %q from storage: {{err}}", secretIDHMAC), err)
		}
		return logical.ErrorResponse("invalid secret id"), nil
	}

	return &logical.Response{
		Data: secretIDEntry.ToResponseData(),
	}, nil
}
548871
func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	roleName := data.Get("role").(string)
	if roleName == "" {
		return logical.ErrorResponse("missing role"), nil
	}

	b.roleMutex.Lock()
	defer b.roleMutex.Unlock()

	return nil, req.Storage.Delete(ctx, "role/"+strings.ToLower(roleName))
}
611601
func (cm *Validator) ProposeConfigUpdate(update *cb.Envelope) (*cb.ConfigEnvelope, error) {
	return cm.ProposeConfigUpdateVal, cm.ProposeConfigUpdateError
}
34977
func (c *Client) LinodeConfigUpdate(configID int, conf LinodeConfigUpdateOpts) error {
	args, err := c.argMarshal(conf)
	if err != nil {
		return err
	}
	args["ConfigID"] = configID

	_, err = c.apiCall("linode.config.update", args)
	if err != nil {
		return err
	}

	return nil
}
240010
func (pgb *ChainDBRPC) UpdateChainState(blockChainInfo *dcrjson.GetBlockChainInfoResult) {
	if pgb == nil || pgb.ChainDB == nil {
		return
	}
	pgb.ChainDB.UpdateChainState(blockChainInfo)
}
638778
func (b *backend) pathRoletagBlacklistUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	// The role_tag value provided, optionally can be base64 encoded.
	tagInput := data.Get("role_tag").(string)
	if tagInput == "" {
		return logical.ErrorResponse("missing role_tag"), nil
	}

	tag := ""

	// Try to base64 decode the value.
	tagBytes, err := base64.StdEncoding.DecodeString(tagInput)
	if err != nil {
		// If the decoding failed, use the value as-is.
		tag = tagInput
	} else {
		// If the decoding succeeded, use the decoded value.
		tag = string(tagBytes)
	}

	// Parse and verify the role tag from string form to a struct form and verify it.
	rTag, err := b.parseAndVerifyRoleTagValue(ctx, req.Storage, tag)
	if err != nil {
		return nil, err
	}
	if rTag == nil {
		return logical.ErrorResponse("failed to verify the role tag and parse it"), nil
	}

	// Get the entry for the role mentioned in the role tag.
	roleEntry, err := b.lockedAWSRole(ctx, req.Storage, rTag.Role)
	if err != nil {
		return nil, err
	}
	if roleEntry == nil {
		return logical.ErrorResponse("role entry not found"), nil
	}

	b.blacklistMutex.Lock()
	defer b.blacklistMutex.Unlock()

	// Check if the role tag is already blacklisted. If yes, update it.
	blEntry, err := b.nonLockedBlacklistRoleTagEntry(ctx, req.Storage, tag)
	if err != nil {
		return nil, err
	}
	if blEntry == nil {
		blEntry = &roleTagBlacklistEntry{}
	}

	currentTime := time.Now()

	// Check if this is a creation of blacklist entry.
	if blEntry.CreationTime.IsZero() {
		// Set the creation time for the blacklist entry.
		// This should not be updated after setting it once.
		// If blacklist operation is invoked more than once, only update the expiration time.
		blEntry.CreationTime = currentTime
	}

	// Decide the expiration time based on the max_ttl values. Since this is
	// restricting access, use the greatest duration, not the least.
	maxDur := rTag.MaxTTL
	if roleEntry.MaxTTL > maxDur {
		maxDur = roleEntry.MaxTTL
	}
	if b.System().MaxLeaseTTL() > maxDur {
		maxDur = b.System().MaxLeaseTTL()
	}

	blEntry.ExpirationTime = currentTime.Add(maxDur)

	entry, err := logical.StorageEntryJSON("blacklist/roletag/"+base64.StdEncoding.EncodeToString([]byte(tag)), blEntry)
	if err != nil {
		return nil, err
	}

	// Store the blacklist entry.
	if err := req.Storage.Put(ctx, entry); err != nil {
		return nil, err
	}

	return nil, nil
}
767833
func TLSConfigFromCertPath(path string) (*tls.Config, error) {
	cert, err := ioutil.ReadFile(filepath.Join(path, "cert.pem"))
	if err != nil {
		return nil, err
	}
	key, err := ioutil.ReadFile(filepath.Join(path, "key.pem"))
	if err != nil {
		return nil, err
	}
	ca, err := ioutil.ReadFile(filepath.Join(path, "ca.pem"))
	if err != nil {
		return nil, err
	}
	tlsCert, err := tls.X509KeyPair(cert, key)
	if err != nil {
		return nil, err
	}
	tlsConfig := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
	tlsConfig.RootCAs = x509.NewCertPool()
	if !tlsConfig.RootCAs.AppendCertsFromPEM(ca) {
		return nil, errors.New("Could not add RootCA pem")
	}
	return tlsConfig, nil
}
864456
func ConfigUpdate(info *model.ConfigUpdateInfo) error {
	return mgr.Do(func(ctx context.Context, cli *client.Client) (err error) {
		var cfg swarm.Config
		cfg, _, err = cli.ConfigInspectWithRaw(ctx, info.ID)
		if err != nil {
			return err
		}

		spec := cfg.Spec
		// only the Labels field can be updated on API 1.30
		//spec.Name = info.Name
		//spec.Data = []byte(info.Data)
		spec.Labels = info.Labels.ToMap()
		return cli.ConfigUpdate(ctx, info.ID, version(info.Version), spec)
	})
}
724609
func fromProto(b *pb.Resource) (Resource, error) {
	base := &resource{
		paths: b.Path,
		mode:  os.FileMode(b.Mode),
		uid:   b.Uid,
		gid:   b.Gid,
	}

	base.xattrs = make(map[string][]byte, len(b.Xattr))

	for _, attr := range b.Xattr {
		base.xattrs[attr.Name] = attr.Data
	}

	switch {
	case base.Mode().IsRegular():
		dgsts := make([]digest.Digest, len(b.Digest))
		for i, dgst := range b.Digest {
			// TODO(stevvooe): Should we be validating at this point?
			dgsts[i] = digest.Digest(dgst)
		}

		return newRegularFile(*base, b.Path, int64(b.Size), dgsts...)
	case base.Mode().IsDir():
		return newDirectory(*base)
	case base.Mode()&os.ModeSymlink != 0:
		return newSymLink(*base, b.Target)
	case base.Mode()&os.ModeNamedPipe != 0:
		return newNamedPipe(*base, b.Path)
	case base.Mode()&os.ModeDevice != 0:
		return newDevice(*base, b.Path, b.Major, b.Minor)
	}

	return nil, fmt.Errorf("unknown resource record (%#v): %s", b, base.Mode())
}
937079
func (c PGPClient) PGPUpdate(ctx context.Context, __arg PGPUpdateArg) (err error) {
	err = c.Cli.Call(ctx, "keybase.1.pgp.pgpUpdate", []interface{}{__arg}, nil)
	return
}
458078
func (c *AwsAccessConfig) EcrGetLogin(ecrUrl string) (string, string, error) {

	exp := regexp.MustCompile(`(?:http://|https://|)([0-9]*)\.dkr\.ecr\.(.*)\.amazonaws\.com.*`)
	splitUrl := exp.FindStringSubmatch(ecrUrl)
	if len(splitUrl) != 3 {
		return "", "", fmt.Errorf("Failed to parse the ECR URL: %s it should be on the form <account number>.dkr.ecr.<region>.amazonaws.com", ecrUrl)
	}
	accountId := splitUrl[1]
	region := splitUrl[2]

	log.Println(fmt.Sprintf("Getting ECR token for account: %s in %s..", accountId, region))

	c.cfg = &common.AccessConfig{
		AccessKey:   c.AccessKey,
		ProfileName: c.Profile,
		RawRegion:   region,
		SecretKey:   c.SecretKey,
		Token:       c.Token,
	}

	session, err := c.cfg.Session()
	if err != nil {
		return "", "", fmt.Errorf("failed to create session: %s", err)
	}

	service := ecr.New(session)

	params := &ecr.GetAuthorizationTokenInput{
		RegistryIds: []*string{
			aws.String(accountId),
		},
	}
	resp, err := service.GetAuthorizationToken(params)
	if err != nil {
		return "", "", fmt.Errorf(err.Error())
	}

	auth, err := base64.StdEncoding.DecodeString(*resp.AuthorizationData[0].AuthorizationToken)
	if err != nil {
		return "", "", fmt.Errorf("Error decoding ECR AuthorizationToken: %s", err)
	}

	authParts := strings.SplitN(string(auth), ":", 2)
	log.Printf("Successfully got login for ECR: %s", ecrUrl)

	return authParts[0], authParts[1], nil
}
361800
func (bk *Backend) pathToBucket(bucket string) string {
	return filepath.Join(bk.rootDir, bucket)
}
1252019
func (v *vserver) handleConfigUpdate(config *config.Vserver) {
	if config == nil {
		return
	}
	switch {
	case v.config == nil:
		v.configInit(config)
		return

	case v.enabled && !vserverEnabled(config, v.vserverOverride.State()):
		log.Infof("%v: disabling vserver", v)
		v.downAll()
		v.unconfigureVIPs()
		v.configInit(config)
		return

	case !v.enabled && !vserverEnabled(config, v.vserverOverride.State()):
		v.configInit(config)
		return

	case !v.enabled && vserverEnabled(config, v.vserverOverride.State()):
		log.Infof("%v: enabling vserver", v)
		v.configInit(config)
		return

	default:
		// Some updates require changes to the iptables rules. Since we currently
		// can't make fine-grained changes to the iptables rules, we must
		// re-initialise the entire vserver. This is necessary in the following
		// scenarios:
		// - A port or protocol is added, removed or changed
		// - A vserver is changed from FWM to non-FWM or vice versa
		// - A vserverEntry is changed from DSR to NAT or vice versa
		//
		// (Changing a VIP address also requires updating iptables, but
		//  v.configUpdate() handles this case)
		//
		// TODO(angusc): Add support for finer-grained updates to ncc so we can
		// avoid re-initialising the vserver in these cases.
		reInit := false
		switch {
		case config.UseFWM != v.config.UseFWM:
			reInit = true
		case len(config.Entries) != len(v.config.Entries):
			reInit = true
		default:
			for k, entry := range config.Entries {
				if v.config.Entries[k] == nil {
					reInit = true
					break
				}
				if v.config.Entries[k].Mode != entry.Mode {
					reInit = true
					break
				}
			}
		}
		if reInit {
			log.Infof("%v: re-initialising vserver", v)
			v.downAll()
			v.unconfigureVIPs()
			v.configInit(config)
			return
		}

		v.config = config
		v.configUpdate()
	}
}
383054
func (c *Chain) checkConfigUpdateValidity(ctx *common.Envelope) error {
	var err error
	payload, err := utils.UnmarshalPayload(ctx.Payload)
	if err != nil {
		return err
	}
	chdr, err := utils.UnmarshalChannelHeader(payload.Header.ChannelHeader)
	if err != nil {
		return err
	}

	if chdr.Type != int32(common.HeaderType_ORDERER_TRANSACTION) &&
		chdr.Type != int32(common.HeaderType_CONFIG) {
		return errors.Errorf("config transaction has unknown header type: %s", common.HeaderType(chdr.Type))
	}

	if chdr.Type == int32(common.HeaderType_ORDERER_TRANSACTION) {
		newChannelConfig, err := utils.UnmarshalEnvelope(payload.Data)
		if err != nil {
			return err
		}

		payload, err = utils.UnmarshalPayload(newChannelConfig.Payload)
		if err != nil {
			return err
		}
	}

	configUpdate, err := configtx.UnmarshalConfigUpdateFromPayload(payload)
	if err != nil {
		return err
	}

	metadata, err := MetadataFromConfigUpdate(configUpdate)
	if err != nil {
		return err
	}

	if metadata == nil {
		return nil // ConsensusType is not updated
	}

	if err = CheckConfigMetadata(metadata); err != nil {
		return err
	}

	switch chdr.Type {
	case int32(common.HeaderType_ORDERER_TRANSACTION):
		c.raftMetadataLock.RLock()
		set := MembershipByCert(c.opts.Consenters)
		c.raftMetadataLock.RUnlock()

		for _, c := range metadata.Consenters {
			if _, exits := set[string(c.ClientTlsCert)]; !exits {
				return errors.Errorf("new channel has consenter that is not part of system consenter set")
			}
		}

		return nil

	case int32(common.HeaderType_CONFIG):
		c.raftMetadataLock.RLock()
		_, err = ComputeMembershipChanges(c.opts.BlockMetadata, c.opts.Consenters, metadata.Consenters)
		c.raftMetadataLock.RUnlock()

		return err

	default:
		// panic here because we have just check header type and return early
		c.logger.Panicf("Programming error, unknown header type")
	}

	return nil
}
132220
func (a *MovAvgAggregation) BucketsPath(bucketsPaths ...string) *MovAvgAggregation {
	a.bucketsPaths = append(a.bucketsPaths, bucketsPaths...)
	return a
}
190960
func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	lock := b.roleLock("")

	lock.RLock()
	defer lock.RUnlock()

	roles, err := req.Storage.List(ctx, "role/")
	if err != nil {
		return nil, err
	}
	return logical.ListResponse(roles), nil
}