// ParseCpeURI parses cpe22uri and set to models.CpeBase
508653
func ParseCpeURI(uri string) (*models.CpeBase, error) {
	var wfn common.WellFormedName
	var err error
	if strings.HasPrefix(uri, "cpe:/") {
		val := strings.TrimPrefix(uri, "cpe:/")
		if strings.Contains(val, "/") {
			uri = "cpe:/" + strings.Replace(val, "/", `\/`, -1)
		}
		wfn, err = naming.UnbindURI(uri)
		if err != nil {
			return nil, err
		}
	} else {
		wfn, err = naming.UnbindFS(uri)
		if err != nil {
			return nil, err
		}
	}

	return &models.CpeBase{
		URI:             naming.BindToURI(wfn),
		FormattedString: naming.BindToFS(wfn),
		WellFormedName:  wfn.String(),
		CpeWFN: models.CpeWFN{
			Part:            fmt.Sprintf("%s", wfn.Get(common.AttributePart)),
			Vendor:          fmt.Sprintf("%s", wfn.Get(common.AttributeVendor)),
			Product:         fmt.Sprintf("%s", wfn.Get(common.AttributeProduct)),
			Version:         fmt.Sprintf("%s", wfn.Get(common.AttributeVersion)),
			Update:          fmt.Sprintf("%s", wfn.Get(common.AttributeUpdate)),
			Edition:         fmt.Sprintf("%s", wfn.Get(common.AttributeEdition)),
			Language:        fmt.Sprintf("%s", wfn.Get(common.AttributeLanguage)),
			SoftwareEdition: fmt.Sprintf("%s", wfn.Get(common.AttributeSwEdition)),
			TargetSW:        fmt.Sprintf("%s", wfn.Get(common.AttributeTargetSw)),
			TargetHW:        fmt.Sprintf("%s", wfn.Get(common.AttributeTargetHw)),
			Other:           fmt.Sprintf("%s", wfn.Get(common.AttributeOther)),
		},
	}, nil
}
339441
func ParseURI(uri string) (ConnConfig, error) {
	var cp ConnConfig

	url, err := url.Parse(uri)
	if err != nil {
		return cp, err
	}

	if url.User != nil {
		cp.User = url.User.Username()
		cp.Password, _ = url.User.Password()
	}

	parts := strings.SplitN(url.Host, ":", 2)
	cp.Host = parts[0]
	if len(parts) == 2 {
		p, err := strconv.ParseUint(parts[1], 10, 16)
		if err != nil {
			return cp, err
		}
		cp.Port = uint16(p)
	}
	cp.Database = strings.TrimLeft(url.Path, "/")

	if pgtimeout := url.Query().Get("connect_timeout"); pgtimeout != "" {
		timeout, err := strconv.ParseInt(pgtimeout, 10, 64)
		if err != nil {
			return cp, err
		}
		d := defaultDialer()
		d.Timeout = time.Duration(timeout) * time.Second
		cp.Dial = d.Dial
	}

	tlsArgs := configTLSArgs{
		sslCert:     url.Query().Get("sslcert"),
		sslKey:      url.Query().Get("sslkey"),
		sslMode:     url.Query().Get("sslmode"),
		sslRootCert: url.Query().Get("sslrootcert"),
	}
	err = configTLS(tlsArgs, &cp)
	if err != nil {
		return cp, err
	}

	ignoreKeys := map[string]struct{}{
		"connect_timeout": {},
		"sslcert":         {},
		"sslkey":          {},
		"sslmode":         {},
		"sslrootcert":     {},
	}

	cp.RuntimeParams = make(map[string]string)

	for k, v := range url.Query() {
		if _, ok := ignoreKeys[k]; ok {
			continue
		}

		if k == "host" {
			cp.Host = v[0]
			continue
		}

		cp.RuntimeParams[k] = v[0]
	}
	if cp.Password == "" {
		pgpass(&cp)
	}
	return cp, nil
}
1140152
func ParseHostSNI(rule string) ([]string, error) {
	parser, err := newTCPParser()
	if err != nil {
		return nil, err
	}

	parse, err := parser.Parse(rule)
	if err != nil {
		return nil, err
	}

	buildTree, ok := parse.(treeBuilder)
	if !ok {
		return nil, errors.New("cannot parse")
	}

	return lower(parseDomain(buildTree())), nil
}
1051542
func (tokenizer *Tokenizer) parseUri() (string, error) {
	start := tokenizer.scanner.Index()
	tokenizer.scanner.Advance()
	for tokenizer.CanRead() {
		if tokenizer.scanner.Char() == '>' {
			uri := tokenizer.scanner.Substring(start, tokenizer.scanner.Index()+1)
			return uri, nil
		}
		if !tokenizer.isUriChar() {
			return "", tokenizer.Error("Invalid character in URI")
		}
		tokenizer.scanner.Advance()
	}
	return "", tokenizer.Error("URI did not end with >")
}
801413
func ParseKubernetesAuthMethodConfig(raw map[string]interface{}) (*KubernetesAuthMethodConfig, error) {
	var config KubernetesAuthMethodConfig
	decodeConf := &mapstructure.DecoderConfig{
		Result:           &config,
		WeaklyTypedInput: true,
	}

	decoder, err := mapstructure.NewDecoder(decodeConf)
	if err != nil {
		return nil, err
	}

	if err := decoder.Decode(raw); err != nil {
		return nil, fmt.Errorf("error decoding config: %s", err)
	}

	return &config, nil
}
1235602
func parseCredentialHeader(credElement string, region string, stype serviceType) (ch credentialHeader, aec APIErrorCode) {
	creds := strings.SplitN(strings.TrimSpace(credElement), "=", 2)
	if len(creds) != 2 {
		return ch, ErrMissingFields
	}
	if creds[0] != "Credential" {
		return ch, ErrMissingCredTag
	}
	credElements := strings.Split(strings.TrimSpace(creds[1]), "/")
	if len(credElements) < 5 {
		return ch, ErrCredMalformed
	}
	accessKey := strings.Join(credElements[:len(credElements)-4], "/") // The access key may contain one or more `/`
	if !auth.IsAccessKeyValid(accessKey) {
		return ch, ErrInvalidAccessKeyID
	}
	// Save access key id.
	cred := credentialHeader{
		accessKey: accessKey,
	}
	credElements = credElements[len(credElements)-4:]
	var e error
	cred.scope.date, e = time.Parse(yyyymmdd, credElements[0])
	if e != nil {
		return ch, ErrMalformedCredentialDate
	}

	cred.scope.region = credElements[1]
	// Verify if region is valid.
	sRegion := cred.scope.region
	// Region is set to be empty, we use whatever was sent by the
	// request and proceed further. This is a work-around to address
	// an important problem for ListBuckets() getting signed with
	// different regions.
	if region == "" {
		region = sRegion
	}
	// Should validate region, only if region is set.
	if !isValidRegion(sRegion, region) {
		return ch, ErrAuthorizationHeaderMalformed

	}
	if credElements[2] != string(stype) {
		return ch, ErrInvalidService
	}
	cred.scope.service = credElements[2]
	if credElements[3] != "aws4_request" {
		return ch, ErrInvalidRequestVersion
	}
	cred.scope.request = credElements[3]
	return cred, ErrNone
}
12870
func ParseEUI64(input string) (eui EUI64, err error) {
	bytes, err := ParseHEX(input, 8)
	if err != nil {
		return
	}
	copy(eui[:], bytes)
	return
}
1113286
func ParseVolume(spec string) (types.ServiceVolumeConfig, error) {
	volume := types.ServiceVolumeConfig{}

	switch len(spec) {
	case 0:
		return volume, errors.New("invalid empty volume spec")
	case 1, 2:
		volume.Target = spec
		volume.Type = string(mount.TypeVolume)
		return volume, nil
	}

	buffer := []rune{}
	for _, char := range spec + string(endOfSpec) {
		switch {
		case isWindowsDrive(buffer, char):
			buffer = append(buffer, char)
		case char == ':' || char == endOfSpec:
			if err := populateFieldFromBuffer(char, buffer, &volume); err != nil {
				populateType(&volume)
				return volume, errors.Wrapf(err, "invalid spec: %s", spec)
			}
			buffer = []rune{}
		default:
			buffer = append(buffer, char)
		}
	}

	populateType(&volume)
	return volume, nil
}
1130943
func parseCSR(obj *certificates.CertificateSigningRequest) (*x509.CertificateRequest, error) {
	// extract PEM from request object
	block, _ := pem.Decode(obj.Spec.Request)
	if block == nil || block.Type != "CERTIFICATE REQUEST" {
		return nil, fmt.Errorf("PEM block type must be CERTIFICATE REQUEST")
	}
	return x509.ParseCertificateRequest(block.Bytes)
}
1363128
func ParseSigner(pemValue string) (crypto.Signer, error) {
	// The _ result below is not an error but the remaining PEM bytes.
	block, _ := pem.Decode([]byte(pemValue))
	if block == nil {
		return nil, fmt.Errorf("no PEM-encoded data found")
	}

	switch block.Type {
	case "EC PRIVATE KEY":
		return x509.ParseECPrivateKey(block.Bytes)

	case "RSA PRIVATE KEY":
		return x509.ParsePKCS1PrivateKey(block.Bytes)

	case "PRIVATE KEY":
		signer, err := x509.ParsePKCS8PrivateKey(block.Bytes)
		if err != nil {
			return nil, err
		}
		pk, ok := signer.(crypto.Signer)
		if !ok {
			return nil, fmt.Errorf("private key is not a valid format")
		}

		return pk, nil

	default:
		return nil, fmt.Errorf("unknown PEM block type for signing key: %s", block.Type)
	}
}
447174
func ParseCertificate(cert *x509.Certificate) *Certificate {
	c := &Certificate{
		RawPEM:             string(helpers.EncodeCertificatePEM(cert)),
		SignatureAlgorithm: helpers.SignatureString(cert.SignatureAlgorithm),
		NotBefore:          cert.NotBefore,
		NotAfter:           cert.NotAfter,
		Subject:            ParseName(cert.Subject),
		Issuer:             ParseName(cert.Issuer),
		SANs:               cert.DNSNames,
		AKI:                formatKeyID(cert.AuthorityKeyId),
		SKI:                formatKeyID(cert.SubjectKeyId),
		SerialNumber:       cert.SerialNumber.String(),
	}
	for _, ip := range cert.IPAddresses {
		c.SANs = append(c.SANs, ip.String())
	}
	return c
}
994177
func (p *Parser) parseOperator() (op Operator, err error) {
	tok, lit := p.consume(KeyAndOperator)
	switch tok {
	// DoesNotExistToken shouldn't be here because it's a unary operator, not a binary operator
	case InToken:
		op = InOperator
	case EqualsToken:
		op = EqualsOperator
	case DoubleEqualsToken:
		op = DoubleEqualsOperator
	case NotInToken:
		op = NotInOperator
	case NotEqualsToken:
		op = NotEqualsOperator
	default:
		return "", fmt.Errorf("found '%s', expected: '=', '!=', '==', 'in', notin'", lit)
	}
	return op, nil
}
873802
func parseHeap(b []byte) (p *Profile, err error) {
	s := bufio.NewScanner(bytes.NewBuffer(b))
	if !s.Scan() {
		if err := s.Err(); err != nil {
			return nil, err
		}
		return nil, errUnrecognized
	}
	p = &Profile{}

	sampling := ""
	hasAlloc := false

	line := s.Text()
	p.PeriodType = &ValueType{Type: "space", Unit: "bytes"}
	if header := heapHeaderRE.FindStringSubmatch(line); header != nil {
		sampling, p.Period, hasAlloc, err = parseHeapHeader(line)
		if err != nil {
			return nil, err
		}
	} else if header = growthHeaderRE.FindStringSubmatch(line); header != nil {
		p.Period = 1
	} else if header = fragmentationHeaderRE.FindStringSubmatch(line); header != nil {
		p.Period = 1
	} else {
		return nil, errUnrecognized
	}

	if hasAlloc {
		// Put alloc before inuse so that default pprof selection
		// will prefer inuse_space.
		p.SampleType = []*ValueType{
			{Type: "alloc_objects", Unit: "count"},
			{Type: "alloc_space", Unit: "bytes"},
			{Type: "inuse_objects", Unit: "count"},
			{Type: "inuse_space", Unit: "bytes"},
		}
	} else {
		p.SampleType = []*ValueType{
			{Type: "objects", Unit: "count"},
			{Type: "space", Unit: "bytes"},
		}
	}

	locs := make(map[uint64]*Location)
	for s.Scan() {
		line := strings.TrimSpace(s.Text())

		if isSpaceOrComment(line) {
			continue
		}

		if isMemoryMapSentinel(line) {
			break
		}

		value, blocksize, addrs, err := parseHeapSample(line, p.Period, sampling, hasAlloc)
		if err != nil {
			return nil, err
		}

		var sloc []*Location
		for _, addr := range addrs {
			// Addresses from stack traces point to the next instruction after
			// each call. Adjust by -1 to land somewhere on the actual call.
			addr--
			loc := locs[addr]
			if locs[addr] == nil {
				loc = &Location{
					Address: addr,
				}
				p.Location = append(p.Location, loc)
				locs[addr] = loc
			}
			sloc = append(sloc, loc)
		}

		p.Sample = append(p.Sample, &Sample{
			Value:    value,
			Location: sloc,
			NumLabel: map[string][]int64{"bytes": {blocksize}},
		})
	}
	if err := s.Err(); err != nil {
		return nil, err
	}
	if err := parseAdditionalSections(s, p); err != nil {
		return nil, err
	}
	return p, nil
}
46101
func ParseUrl(inUrl string) (*url.URL, error) {
	parsedUrl, err := url.Parse(inUrl)
	if err != nil {
		return nil, err
	}

	if parsedUrl.Host == "" || parsedUrl.Scheme == "" {
		return nil, fmt.Errorf("Empty Url is not allowed")
	}
	return parsedUrl, nil
}
621692
func ParseCSRPEM(csrPEM []byte) (*x509.CertificateRequest, error) {
	csrObject, err := helpers.ParseCSRPEM(csrPEM)
	if err != nil {
		return nil, err
	}

	return csrObject, nil
}
693812
func ParseCiphers(cipherStr string) ([]uint16, error) {
	suites := []uint16{}

	cipherStr = strings.TrimSpace(cipherStr)
	if cipherStr == "" {
		return []uint16{}, nil
	}
	ciphers := strings.Split(cipherStr, ",")

	cipherMap := map[string]uint16{
		"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305":    tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
		"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305":  tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
		"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256":   tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
		"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
		"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384":   tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
		"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384": tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
		"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256":   tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
		"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA":      tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
		"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256": tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
		"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA":    tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
		"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA":      tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
		"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA":    tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
		"TLS_RSA_WITH_AES_128_GCM_SHA256":         tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
		"TLS_RSA_WITH_AES_256_GCM_SHA384":         tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
		"TLS_RSA_WITH_AES_128_CBC_SHA256":         tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
		"TLS_RSA_WITH_AES_128_CBC_SHA":            tls.TLS_RSA_WITH_AES_128_CBC_SHA,
		"TLS_RSA_WITH_AES_256_CBC_SHA":            tls.TLS_RSA_WITH_AES_256_CBC_SHA,
		"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA":     tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
		"TLS_RSA_WITH_3DES_EDE_CBC_SHA":           tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
		"TLS_RSA_WITH_RC4_128_SHA":                tls.TLS_RSA_WITH_RC4_128_SHA,
		"TLS_ECDHE_RSA_WITH_RC4_128_SHA":          tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
		"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA":        tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
	}
	for _, cipher := range ciphers {
		if v, ok := cipherMap[cipher]; ok {
			suites = append(suites, v)
		} else {
			return suites, fmt.Errorf("unsupported cipher %q", cipher)
		}
	}

	return suites, nil
}
664845
func (r *RDBDriver) GetByCpeURI(uri string) ([]models.CveDetail, error) {
	cveIDs, err := r.GetCveIDsByCpeURI(uri)
	if err != nil {
		return nil, err
	}

	cveDetails, err := r.GetMulti(cveIDs)
	if err != nil {
		return nil, err
	}

	// Convert from map to array
	details := make([]models.CveDetail, len(cveDetails))
	i := 0
	for _, d := range cveDetails {
		details[i] = d
		i++
		log.Debugf("%s", d.CveID)
	}
	return details, nil
}