// saveCertResource saves the certificate resource to disk. This
// includes the certificate file itself, the private key, and the
// metadata file.
434743
func saveCertResource(storage Storage, cert acme.CertificateResource) error {
	// Save cert, private key, and metadata
	siteData := &SiteData{
		Cert: cert.Certificate,
		Key:  cert.PrivateKey,
	}
	var err error
	siteData.Meta, err = json.MarshalIndent(&cert, "", "\t")
	if err == nil {
		err = storage.StoreSite(cert.Domain, siteData)
	}
	return err
}
1144882
func (p *Package) CreateSourceFile(name string) (*SourceFile, error) {
	os.RemoveAll(filepath.Join(p.Abs(), name))
	return p.OpenSourceFile(name)
}
982212
func (m *Manager) registerSource(s Source) {
	m.sources = append(m.sources, s)
}
93040
func (p *Package) OpenSourceFile(name string) (*SourceFile, error) {
	f := &SourceFile{Name: name, Package: p}
	file, err := os.OpenFile(f.Abs(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return nil, err
	}
	f.osFile = file
	return f, nil
}
1240175
func makeCertificateFromDisk(certFile, keyFile string) (Certificate, error) {
	certPEMBlock, err := ioutil.ReadFile(certFile)
	if err != nil {
		return Certificate{}, err
	}
	keyPEMBlock, err := ioutil.ReadFile(keyFile)
	if err != nil {
		return Certificate{}, err
	}
	return makeCertificate(certPEMBlock, keyPEMBlock)
}
1156620
func (p *Provider) ValidateResource(
	t string, c *terraform.ResourceConfig) ([]string, []error) {
	r, ok := p.ResourcesMap[t]
	if !ok {
		return nil, []error{fmt.Errorf(
			"Provider doesn't support resource: %s", t)}
	}

	return r.Validate(c)
}
356772
func CreateCustomResources(context Context, resources []CustomResource) error {

	var lastErr error
	for _, resource := range resources {
		if err := createCRD(context, resource); err != nil {
			lastErr = err
		}
	}

	for _, resource := range resources {
		if err := waitForCRDInit(context, resource); err != nil {
			lastErr = err
		}
	}

	return lastErr
}
1364566
func (c *Ctx) UseCertificate(cert *Certificate) error {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()
	c.cert = cert
	if int(C.SSL_CTX_use_certificate(c.ctx, cert.x)) != 1 {
		return errorFromErrorQueue()
	}
	return nil
}
767393
func (ec *Envcfg) diskCertProvider(params []string) CertificateProvider {
	// "certname:keyname"
	if len(params) < 2 {
		panic("invalid certificate provider params")
	}

	dir := ec.CertPath()
	certPath, keyPath := filepath.Join(dir, params[0]), filepath.Join(dir, params[1])
	dcp, err := newDiskCertProvider(certPath, keyPath, ec.logf, ec.errf)
	if err != nil {
		panic(fmt.Sprintf("unable to load certificate and key from disk: %v", err))
	}

	return dcp
}
218873
func createCertificate(data *dataBundle) (*certutil.ParsedCertBundle, error) {
	var err error
	result := &certutil.ParsedCertBundle{}

	serialNumber, err := certutil.GenerateSerialNumber()
	if err != nil {
		return nil, err
	}

	if err := certutil.GeneratePrivateKey(data.params.KeyType,
		data.params.KeyBits,
		result); err != nil {
		return nil, err
	}

	subjKeyID, err := certutil.GetSubjKeyID(result.PrivateKey)
	if err != nil {
		return nil, errutil.InternalError{Err: fmt.Sprintf("error getting subject key ID: %s", err)}
	}

	certTemplate := &x509.Certificate{
		SerialNumber:   serialNumber,
		NotBefore:      time.Now().Add(-30 * time.Second),
		NotAfter:       data.params.NotAfter,
		IsCA:           false,
		SubjectKeyId:   subjKeyID,
		Subject:        data.params.Subject,
		DNSNames:       data.params.DNSNames,
		EmailAddresses: data.params.EmailAddresses,
		IPAddresses:    data.params.IPAddresses,
		URIs:           data.params.URIs,
	}
	if data.params.NotBeforeDuration > 0 {
		certTemplate.NotBefore = time.Now().Add(-1 * data.params.NotBeforeDuration)
	}

	if err := handleOtherSANs(certTemplate, data.params.OtherSANs); err != nil {
		return nil, errutil.InternalError{Err: errwrap.Wrapf("error marshaling other SANs: {{err}}", err).Error()}
	}

	// Add this before calling addKeyUsages
	if data.signingBundle == nil {
		certTemplate.IsCA = true
	} else if data.params.BasicConstraintsValidForNonCA {
		certTemplate.BasicConstraintsValid = true
		certTemplate.IsCA = false
	}

	// This will only be filled in from the generation paths
	if len(data.params.PermittedDNSDomains) > 0 {
		certTemplate.PermittedDNSDomains = data.params.PermittedDNSDomains
		certTemplate.PermittedDNSDomainsCritical = true
	}

	addPolicyIdentifiers(data, certTemplate)

	addKeyUsages(data, certTemplate)

	addExtKeyUsageOids(data, certTemplate)

	certTemplate.IssuingCertificateURL = data.params.URLs.IssuingCertificates
	certTemplate.CRLDistributionPoints = data.params.URLs.CRLDistributionPoints
	certTemplate.OCSPServer = data.params.URLs.OCSPServers

	var certBytes []byte
	if data.signingBundle != nil {
		switch data.signingBundle.PrivateKeyType {
		case certutil.RSAPrivateKey:
			certTemplate.SignatureAlgorithm = x509.SHA256WithRSA
		case certutil.ECPrivateKey:
			certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256
		}

		caCert := data.signingBundle.Certificate
		certTemplate.AuthorityKeyId = caCert.SubjectKeyId

		certBytes, err = x509.CreateCertificate(rand.Reader, certTemplate, caCert, result.PrivateKey.Public(), data.signingBundle.PrivateKey)
	} else {
		// Creating a self-signed root
		if data.params.MaxPathLength == 0 {
			certTemplate.MaxPathLen = 0
			certTemplate.MaxPathLenZero = true
		} else {
			certTemplate.MaxPathLen = data.params.MaxPathLength
		}

		switch data.params.KeyType {
		case "rsa":
			certTemplate.SignatureAlgorithm = x509.SHA256WithRSA
		case "ec":
			certTemplate.SignatureAlgorithm = x509.ECDSAWithSHA256
		}

		certTemplate.AuthorityKeyId = subjKeyID
		certTemplate.BasicConstraintsValid = true
		certBytes, err = x509.CreateCertificate(rand.Reader, certTemplate, certTemplate, result.PrivateKey.Public(), result.PrivateKey)
	}

	if err != nil {
		return nil, errutil.InternalError{Err: fmt.Sprintf("unable to create certificate: %s", err)}
	}

	result.CertificateBytes = certBytes
	result.Certificate, err = x509.ParseCertificate(certBytes)
	if err != nil {
		return nil, errutil.InternalError{Err: fmt.Sprintf("unable to parse created certificate: %s", err)}
	}

	if data.signingBundle != nil {
		if len(data.signingBundle.Certificate.AuthorityKeyId) > 0 &&
			!bytes.Equal(data.signingBundle.Certificate.AuthorityKeyId, data.signingBundle.Certificate.SubjectKeyId) {

			result.CAChain = []*certutil.CertBlock{
				&certutil.CertBlock{
					Certificate: data.signingBundle.Certificate,
					Bytes:       data.signingBundle.CertificateBytes,
				},
			}
			result.CAChain = append(result.CAChain, data.signingBundle.CAChain...)
		}
	}

	return result, nil
}
1070758
func (maasStorageProvider) VolumeSource(providerConfig *storage.Config) (storage.VolumeSource, error) {
	// Dynamic volumes not supported.
	return nil, errors.NotSupportedf("volumes")
}
818479
func (r *Rules) Save(filename string) (err error) {
	cfilename := C.CString(filename)
	defer C.free(unsafe.Pointer(cfilename))
	err = newError(C.yr_rules_save(r.cptr, cfilename))
	keepAlive(r)
	return
}
1271995
func ParseCertificateRequest(s Signer, csrBytes []byte) (template *x509.Certificate, err error) {
	csrv, err := x509.ParseCertificateRequest(csrBytes)
	if err != nil {
		err = cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err)
		return
	}

	err = csrv.CheckSignature()
	if err != nil {
		err = cferr.Wrap(cferr.CSRError, cferr.KeyMismatch, err)
		return
	}

	template = &x509.Certificate{
		Subject:            csrv.Subject,
		PublicKeyAlgorithm: csrv.PublicKeyAlgorithm,
		PublicKey:          csrv.PublicKey,
		SignatureAlgorithm: s.SigAlgo(),
		DNSNames:           csrv.DNSNames,
		IPAddresses:        csrv.IPAddresses,
		EmailAddresses:     csrv.EmailAddresses,
		URIs:               csrv.URIs,
	}

	for _, val := range csrv.Extensions {
		// Check the CSR for the X.509 BasicConstraints (RFC 5280, 4.2.1.9)
		// extension and append to template if necessary
		if val.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 19}) {
			var constraints csr.BasicConstraints
			var rest []byte

			if rest, err = asn1.Unmarshal(val.Value, &constraints); err != nil {
				return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, err)
			} else if len(rest) != 0 {
				return nil, cferr.Wrap(cferr.CSRError, cferr.ParseFailed, errors.New("x509: trailing data after X.509 BasicConstraints"))
			}

			template.BasicConstraintsValid = true
			template.IsCA = constraints.IsCA
			template.MaxPathLen = constraints.MaxPathLen
			template.MaxPathLenZero = template.MaxPathLen == 0
		}
	}

	return
}
754360
func (s *storage) SaveAccess(data *osin.AccessData) error {
	token, err := s.convertToAccessToken(data)
	if err != nil {
		return err
	}
	_, err = s.accesstoken.Create(token)
	return err
}
439100
func (settings FileSettings) ServicePrincipalTokenFromClientCertificateWithResource(resource string) (*adal.ServicePrincipalToken, error) {
	cfg, err := settings.clientCertificateConfigWithResource(resource)
	if err != nil {
		return nil, err
	}
	return cfg.ServicePrincipalToken()
}
262193
func newDiskCertProvider(certPath, keyPath string, logf, errf func(string, ...interface{})) (*diskCertProvider, error) {
	dcp := &diskCertProvider{
		certPath: certPath,
		keyPath:  keyPath,
	}
	if err := dcp.loadCertAndKey(); err != nil {
		return nil, err
	}

	// create watcher
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}
	// don't close, as it runs forever
	// defer watcher.Close()

	addWatch := func(path string) error {
		if err := watcher.Add(certPath); err != nil {
			return err
		}

		// if this is a valid symlink, watch its target too
		if path, err := filepath.EvalSymlinks(certPath); err == nil && path != certPath {
			if err := watcher.Add(path); err != nil {
				return err
			}
		}

		return nil
	}

	go func() {
		for {
			select {
			case <-watcher.Events:
				if err := dcp.loadCertAndKey(); err != nil {
					errf("could not load cert and key: %v", err)
				} else {
					logf("loaded updated certificate")
				}

				// in case we're dealing with symlinks and the target changed,
				// make sure we continue to watch properly
				if err := addWatch(certPath); err != nil {
					errf("could not add watch: %v", err)
				}

			case err := <-watcher.Errors:
				errf("%v", err)
			}
		}
	}()

	// watch the first certificate file
	if err := addWatch(certPath); err != nil {
		return nil, err
	}

	return dcp, nil
}
1367036
func (c *Connect) DomainSaveImageGetXMLDesc(file string, flags DomainSaveImageXMLFlags) (string, error) {
	cfile := C.CString(file)
	defer C.free(unsafe.Pointer(cfile))

	var err C.virError
	ret := C.virDomainSaveImageGetXMLDescWrapper(c.ptr, cfile, C.uint(flags), &err)

	if ret == nil {
		return "", makeError(&err)
	}

	defer C.free(unsafe.Pointer(ret))

	return C.GoString(ret), nil
}