// parseDstFromOOB takes oob data and returns the destination IP.
160109
func parseDstFromOOB(oob []byte) (*net.UDPAddr, error) {
	msgs, err := syscall.ParseSocketControlMessage(oob)
	if err != nil {
		return nil, fmt.Errorf("parsing socket control message: %s", err)
	}

	for _, msg := range msgs {
		if msg.Header.Level == unix.SOL_IP && msg.Header.Type == unix.IP_ORIGDSTADDR {
			pp := &syscall.RawSockaddrInet4{}
			// Address family is in native byte order
			family := *(*uint16)(unsafe.Pointer(&msg.Data[unsafe.Offsetof(pp.Family)]))
			if family != unix.AF_INET {
				return nil, fmt.Errorf("original destination is not IPv4.")
			}
			// Port is in big-endian byte order
			if err = binary.Read(bytes.NewReader(msg.Data), binary.BigEndian, pp); err != nil {
				return nil, fmt.Errorf("reading original destination address: %s", err)
			}
			laddr := &net.UDPAddr{
				IP:   net.IPv4(pp.Addr[0], pp.Addr[1], pp.Addr[2], pp.Addr[3]),
				Port: int(pp.Port),
			}
			return laddr, nil
		}
		if msg.Header.Level == unix.SOL_IPV6 && msg.Header.Type == unix.IPV6_ORIGDSTADDR {
			pp := &syscall.RawSockaddrInet6{}
			// Address family is in native byte order
			family := *(*uint16)(unsafe.Pointer(&msg.Data[unsafe.Offsetof(pp.Family)]))
			if family != unix.AF_INET6 {
				return nil, fmt.Errorf("original destination is not IPv6.")
			}
			// Scope ID is in native byte order
			scopeId := *(*uint32)(unsafe.Pointer(&msg.Data[unsafe.Offsetof(pp.Scope_id)]))
			// Rest of the data is big-endian (port)
			if err = binary.Read(bytes.NewReader(msg.Data), binary.BigEndian, pp); err != nil {
				return nil, fmt.Errorf("reading original destination address: %s", err)
			}
			laddr := &net.UDPAddr{
				IP:   net.IP(pp.Addr[:]),
				Port: int(pp.Port),
				Zone: strconv.Itoa(int(scopeId)),
			}
			return laddr, nil
		}
	}
	return nil, fmt.Errorf("No original destination found!")
}
177189
func ParseProtocol(s string) Protocol {
	switch strings.ToLower(s) {
	case "icmp":
		return ICMP
	case "udp":
		return UDP
	case "tcp":
		return TCP
	case "sctp":
		return SCTP
	default:
		return 0
	}
}
392530
func (n *RegisteredNexthop) DecodeFromBytes(data []byte) error {
	// Connected (1 byte)
	n.Connected = uint8(data[0])
	// Address Family (2 bytes)
	n.Family = binary.BigEndian.Uint16(data[1:3])
	// Note: Ignores Prefix Length (1 byte)
	addrByteLen := (int(data[3]) + 7) / 8
	// Prefix (variable)
	n.Prefix = ipFromFamily(uint8(n.Family), data[4:4+addrByteLen])

	return nil
}
570584
func ValidateIPFromString(ipaddr string, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}
	if net.ParseIP(ipaddr) == nil {
		allErrs = append(allErrs, field.Invalid(fldPath, ipaddr, "ip address is not valid"))
	}
	return allErrs
}
740062
func ParseIfAddrsTemplate(input string, ifAddrs sockaddr.IfAddrs, tmplIn *template.Template) (string, error) {
	// Create a template, add the function map, and parse the text.
	tmpl, err := tmplIn.Option("missingkey=error").
		Funcs(SourceFuncs).
		Funcs(SortFuncs).
		Funcs(FilterFuncs).
		Funcs(HelperFuncs).
		Parse(input)
	if err != nil {
		return "", errwrap.Wrapf(fmt.Sprintf("unable to parse template %+q: {{err}}", input), err)
	}

	var outWriter bytes.Buffer
	err = tmpl.Execute(&outWriter, ifAddrs)
	if err != nil {
		return "", errwrap.Wrapf(fmt.Sprintf("unable to execute sockaddr input %+q: {{err}}", input), err)
	}

	return outWriter.String(), nil
}
264147
func parseDefaultIfNameWindows(routeOut, ipconfigOut string) (string, error) {
	defaultIPAddr, err := parseDefaultIPAddrWindowsRoute(routeOut)
	if err != nil {
		return "", err
	}

	ifName, err := parseDefaultIfNameWindowsIPConfig(defaultIPAddr, ipconfigOut)
	if err != nil {
		return "", err
	}

	return ifName, nil
}
1012373
func (c *Client) parseNodeFrom(msg osc.Message, startIndex int) (Node, int, error) {
	argsConsumed := 0

	// We should have at least 2 arguments for nodes contained in the group.
	if numArgs := len(msg.Arguments); numArgs < 2 {
		return nil, 0, fmt.Errorf("expected 2 arguments for message, got %d", numArgs)
	}
	// get the id of the group this reply is for
	nodeID, err := msg.Arguments[startIndex].ReadInt32()
	if err != nil {
		return nil, 0, err
	}
	argsConsumed++

	numChildren, err := msg.Arguments[startIndex+1].ReadInt32()
	if err != nil {
		return nil, 0, err
	}
	argsConsumed++

	if numChildren < 0 {
		// Synth node.
		node, synthArgsConsumed, err := c.parseSynthNodeFrom(msg, nodeID, startIndex+argsConsumed)
		return node, argsConsumed + synthArgsConsumed, errors.Wrap(err, "parsing synth node")
	}
	g := &GroupNode{
		Children: make([]Node, numChildren),
		client:   c,
		id:       nodeID,
	}
	startIndex = startIndex + 2

	for i := 0; int32(i) < numChildren; i++ {
		node, childArgsConsumed, err := c.parseNodeFrom(msg, startIndex)
		if err != nil {
			return nil, 0, err
		}
		startIndex += childArgsConsumed
		argsConsumed += childArgsConsumed
		g.Children[i] = node
	}
	return g, argsConsumed, nil
}
1006495
func ParsedQuery(q ast.Body) func(r *Rego) {
	return func(r *Rego) {
		r.parsedQuery = q
	}
}
86722
func parseNFSOperationStats(s *bufio.Scanner) ([]NFSOperationStats, error) {
	const (
		// Number of expected fields in each per-operation statistics set
		numFields = 9
	)

	var ops []NFSOperationStats

	for s.Scan() {
		ss := strings.Fields(string(s.Bytes()))
		if len(ss) == 0 {
			// Must break when reading a blank line after per-operation stats to
			// enable top-level function to parse the next device entry
			break
		}

		if len(ss) != numFields {
			return nil, fmt.Errorf("invalid NFS per-operations stats: %v", ss)
		}

		// Skip string operation name for integers
		ns := make([]uint64, 0, numFields-1)
		for _, st := range ss[1:] {
			n, err := strconv.ParseUint(st, 10, 64)
			if err != nil {
				return nil, err
			}

			ns = append(ns, n)
		}

		ops = append(ops, NFSOperationStats{
			Operation:                   strings.TrimSuffix(ss[0], ":"),
			Requests:                    ns[0],
			Transmissions:               ns[1],
			MajorTimeouts:               ns[2],
			BytesSent:                   ns[3],
			BytesReceived:               ns[4],
			CumulativeQueueTime:         time.Duration(ns[5]) * time.Millisecond,
			CumulativeTotalResponseTime: time.Duration(ns[6]) * time.Millisecond,
			CumulativeTotalRequestTime:  time.Duration(ns[7]) * time.Millisecond,
		})
	}

	return ops, s.Err()
}
88254
func parseDefaultIfNameFromIPCmd(routeOut string) (string, error) {
	parsedLines := parseIfNameFromIPCmd(routeOut)
	for _, parsedLine := range parsedLines {
		if parsedLine[0] == "default" &&
			parsedLine[1] == "via" &&
			parsedLine[3] == "dev" {
			ifName := strings.TrimSpace(parsedLine[4])
			return ifName, nil
		}
	}

	return "", errors.New("No default interface found")
}
221317
func parseArgsDataString(stdin io.Reader, args []string) (map[string]string, error) {
	raw, err := parseArgsData(stdin, args)
	if err != nil {
		return nil, err
	}

	var result map[string]string
	if err := mapstructure.WeakDecode(raw, &result); err != nil {
		return nil, errors.Wrap(err, "failed to convert values to strings")
	}
	if result == nil {
		result = make(map[string]string)
	}
	return result, nil
}
959040
func Stob(s string) []byte {
	return *(*[]byte)(unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s))))
}
1170460
func ParseFlagsOp(item StoreItem) (op FlagsOp, silent bool, err error) {
	itemStr := string(item)
	silent = strings.HasSuffix(itemStr, silentOp)
	if silent {
		itemStr = strings.TrimSuffix(itemStr, silentOp)
	}
	op = FlagsOp(itemStr)

	if op != SetFlags && op != AddFlags && op != RemoveFlags {
		err = errors.New("Unsupported STORE operation")
	}
	return
}
1282739
func parseAddr(addr string) ([]net.IP, []string, error) {
	host, _, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, nil, err
	}
	var domains []string
	var ips []net.IP
	ip := net.ParseIP(host)
	if ip != nil {
		ips = []net.IP{ip}
	} else {
		domains = []string{host}
	}
	return ips, domains, nil
}
515628
func (p *parser) parseObj() (string, objType, string) {
	p.skipWhitespace()
	c := p.c()
	if c[0] == '"' || c[0] == '\'' {
		i := 1
	For:
		for ; i < len(c); i++ {
			switch c[i] {
			case '\\':
				i++
			case c[0]:
				break For
			}
		}
		p.i += i + 1

		s := "\"" + string(c[1:i]) + "\""
		json.Unmarshal([]byte(s), &s)
		lang := ""
		if c[i+1] == '@' {
			c = p.c()
			i := bytes.IndexAny(c, stopRunes)
			if c[i-1] == '.' {
				i--
			}
			p.i += i
			lang = string(c[1:i])
		} else if bytes.Equal(c[i+1:i+3], []byte("^^")) {
			// TODO(d4l3k): Implement RDF types.
		}
		return s, typeString, lang
	} else if bytes.HasPrefix(c, []byte("<")) {
		i := bytes.IndexRune(c, '>')
		p.i += i + 1
		url := string(c[1:i])
		if !strings.Contains(url, "://") {
			url = p.base + url
		}
		return url, typeIRI, ""
	} else if bytes.HasPrefix(c, []byte(".")) {
		p.i += 1
		return ".", typeEnd, ""
	} else if bytes.HasPrefix(c, []byte(";")) {
		p.i += 1
		return ";", typePred, ""
	} else if bytes.HasPrefix(c, []byte(",")) {
		p.i += 1
		return ",", typeObj, ""
	} else {
		i := bytes.IndexAny(c, stopRunes)
		if c[i-1] == '.' {
			i--
		}
		p.i += i
		obj := string(c[:i])
		psym := strings.IndexRune(obj, ':')
		if psym != -1 {
			if psym == len(obj)-1 {
				return obj, typePrefix, ""
			}
			prefix := obj[:psym+1]
			if expand, ok := p.prefix[prefix]; ok {
				return expand + obj[psym+1:], typeIRI, ""
			}
		}
		return obj, typeUnknown, ""
	}
}
443533
func StringToIPHookFunc() DecodeHookFunc {
	return func(
		f reflect.Type,
		t reflect.Type,
		data interface{}) (interface{}, error) {
		if f.Kind() != reflect.String {
			return data, nil
		}
		if t != reflect.TypeOf(net.IP{}) {
			return data, nil
		}

		// Convert it by parsing
		ip := net.ParseIP(data.(string))
		if ip == nil {
			return net.IP{}, fmt.Errorf("failed parsing ip %v", data)
		}

		return ip, nil
	}
}
371410
func IPPart(s string) string {
	if ip := net.ParseIP(s); ip != nil {
		// IP address without port
		return s
	}
	// Must be IP:port
	host, _, err := net.SplitHostPort(s)
	if err != nil {
		klog.Errorf("Error parsing '%s': %v", s, err)
		return ""
	}
	// Check if host string is a valid IP address
	if ip := net.ParseIP(host); ip != nil {
		return ip.String()
	} else {
		klog.Errorf("invalid IP part '%s'", host)
	}
	return ""
}