// ParseAddressSpec parses RFC 5322 Addr-Spec Specification
176255
func ParseAddressSpec(addrSpec string) (string, string, error) {
	rs := regexp.MustCompile(`^([^@]+)@([^@]+)$`).FindStringSubmatch(addrSpec)
	if len(rs) < 1 {
		return "", "", errors.New("RFC 5322 Address Spec not found.")
	}
	return rs[1], rs[2], nil
}
768478
func parseConnSpec(connStr string) connSpec {
	var out connSpec
	out.Options = map[string]string{}

	partMatcher := regexp.MustCompile(`((.*):\/\/)?(([^\/?:]*)(:([^\/?:@]*))?@)?([^\/?]*)(\/([^\?]*))?(\?(.*))?`)
	hostMatcher := regexp.MustCompile(`([^;\,\:]+)(:([0-9]*))?(;\,)?`)
	kvMatcher := regexp.MustCompile(`([^=]*)=([^&?]*)[&?]?`)
	parts := partMatcher.FindStringSubmatch(connStr)

	if parts[2] != "" {
		out.Scheme = parts[2]
	}

	if parts[7] != "" {
		hosts := hostMatcher.FindAllStringSubmatch(parts[7], -1)
		for _, hostInfo := range hosts {
			port := 0
			if hostInfo[3] != "" {
				port, _ = strconv.Atoi(hostInfo[3])
			}

			out.Hosts = append(out.Hosts, connSpecAddr{
				Host: hostInfo[1],
				Port: uint16(port),
			})
		}
	}

	if parts[9] != "" {
		out.Bucket = parts[9]
	}

	if parts[11] != "" {
		kvs := kvMatcher.FindAllStringSubmatch(parts[11], -1)
		for _, kvInfo := range kvs {
			out.Options[kvInfo[1]] = kvInfo[2]
		}
	}

	return out
}
353944
func (pf *PortForwarder) listenOnPortAndAddress(port *ForwardedPort, protocol string, address string) error {
	listener, err := pf.getListener(protocol, address, port)
	if err != nil {
		return err
	}
	pf.listeners = append(pf.listeners, listener)
	go pf.waitForConnection(listener, *port)
	return nil
}
856131
func ParseBuildAddress(address string) (id int64, project, bucket, builder string, number int, err error) {
	parts := strings.Split(address, "/")
	switch len(parts) {
	case 3:
		var numberStr string
		bucket, builder, numberStr = parts[0], parts[1], parts[2]
		project = ProjectFromBucket(bucket)
		number, err = strconv.Atoi(numberStr)
	case 1:
		id, err = strconv.ParseInt(parts[0], 10, 64)
	default:
		err = fmt.Errorf("unrecognized build address format %q", address)
	}
	return
}
506099
func (b IPv4) SetSourceAddress(addr tcpip.Address) {
	copy(b[srcAddr:srcAddr+IPv4AddressSize], addr)
}
991130
func ParseAdvertise(advertise string) (string, error) {
	var (
		iface *net.Interface
		addrs []net.Addr
		err   error
	)

	addr, port, err := net.SplitHostPort(advertise)

	if err != nil {
		return "", fmt.Errorf("invalid --cluster-advertise configuration: %s: %v", advertise, err)
	}

	ip := net.ParseIP(addr)
	// If it is a valid ip-address, use it as is
	if ip != nil {
		return advertise, nil
	}

	// If advertise is a valid interface name, get the valid IPv4 address and use it to advertise
	ifaceName := addr
	iface, err = net.InterfaceByName(ifaceName)
	if err != nil {
		return "", fmt.Errorf("invalid cluster advertise IP address or interface name (%s) : %v", advertise, err)
	}

	addrs, err = iface.Addrs()
	if err != nil {
		return "", fmt.Errorf("unable to get advertise IP address from interface (%s) : %v", advertise, err)
	}

	if len(addrs) == 0 {
		return "", fmt.Errorf("no available advertise IP address in interface (%s)", advertise)
	}

	addr = ""
	for _, a := range addrs {
		ip, _, err := net.ParseCIDR(a.String())
		if err != nil {
			return "", fmt.Errorf("error deriving advertise ip-address in interface (%s) : %v", advertise, err)
		}
		if ip.To4() == nil || ip.IsLoopback() {
			continue
		}
		addr = ip.String()
		break
	}
	if addr == "" {
		return "", fmt.Errorf("could not find a valid ip-address in interface %s", advertise)
	}

	addr = net.JoinHostPort(addr, port)
	return addr, nil
}
1069494
func ParseAddr(a string) (*NetAddr, error) {
	if a == "" {
		return nil, trace.BadParameter("missing parameter address")
	}
	if !strings.Contains(a, "://") {
		return &NetAddr{Addr: a, AddrNetwork: "tcp"}, nil
	}
	u, err := url.Parse(a)
	if err != nil {
		return nil, trace.BadParameter("failed to parse %q: %v", a, err)
	}
	switch u.Scheme {
	case "tcp":
		return &NetAddr{Addr: u.Host, AddrNetwork: u.Scheme, Path: u.Path}, nil
	case "unix":
		return &NetAddr{Addr: u.Path, AddrNetwork: u.Scheme}, nil
	case "http", "https":
		return &NetAddr{Addr: u.Host, AddrNetwork: u.Scheme, Path: u.Path}, nil
	default:
		return nil, trace.BadParameter("'%v': unsupported scheme: '%v'", a, u.Scheme)
	}
}
258754
func Convert_v1beta1_IngressSpec_To_networking_IngressSpec(in *v1beta1.IngressSpec, out *networking.IngressSpec, s conversion.Scope) error {
	return autoConvert_v1beta1_IngressSpec_To_networking_IngressSpec(in, out, s)
}
381735
func parseDC(url string) (string, bool, error) {
	isSamsung := false
	if strings.Contains(url, "samsung") {
		isSamsung = true
	}

	for _, pattern := range knownDCFormats {
		re := regexp.MustCompile(pattern)
		matches := re.FindStringSubmatch(url)
		if len(matches) > 1 {
			return matches[1], isSamsung, nil
		}
	}

	return "", isSamsung, fmt.Errorf("failed to parse datacenter from '%s'", url)
}
1313108
func ParseHostPort(hostport string) (string, string, error) {
	var host, port string
	var err error

	// try to split host and port
	if host, port, err = net.SplitHostPort(hostport); err != nil {
		// if SplitHostPort returns an error, the entire hostport is considered as host
		host = hostport
	}

	// if port is defined, parse and validate it
	if port != "" {
		if _, err := ParsePort(port); err != nil {
			return "", "", errors.Errorf("hostport %s: port %s must be a valid number between 1 and 65535, inclusive", hostport, port)
		}
	}

	// if host is a valid IP, returns it
	if ip := net.ParseIP(host); ip != nil {
		return host, port, nil
	}

	// if host is a validate RFC-1123 subdomain, returns it
	if errs := validation.IsDNS1123Subdomain(host); len(errs) == 0 {
		return host, port, nil
	}

	return "", "", errors.Errorf("hostport %s: host '%s' must be a valid IP address or a valid RFC-1123 DNS subdomain", hostport, host)
}
1293080
func AllocAddressHandler(w http.ResponseWriter, r *http.Request, vars map[string]string) (interface{}, error) {
	var allocReq AddressAllocRequest
	var epgCfg *mastercfg.EndpointGroupState
	var networkID string
	var epgName string

	// Get object from the request
	err := json.NewDecoder(r.Body).Decode(&allocReq)
	if err != nil {
		log.Errorf("Error decoding AllocAddressHandler. Err %v", err)
		return nil, err
	}

	log.Infof("Received AddressAllocRequest: %+v", allocReq)

	// Take a global lock for address allocation
	addrMutex.Lock()
	defer addrMutex.Unlock()

	// Get hold of the state driver
	stateDriver, err := utils.GetStateDriver()
	if err != nil {
		return nil, err
	}

	isIPv6 := netutils.IsIPv6(allocReq.AddressPool)

	// Determine the network id to use
	if allocReq.NetworkID != "" {
		networkID, epgName = getNwAndEpgFromAddrReq(allocReq.NetworkID)
	} else {
		// find the network from address pool
		subnetIP := strings.Split(allocReq.AddressPool, "/")[0]
		subnetLen := strings.Split(allocReq.AddressPool, "/")[1]
		tenant := ""
		if strings.Contains(subnetLen, ":") {
			tenant = strings.Split(subnetLen, ":")[1]
			subnetLen = strings.Split(subnetLen, ":")[0]
		}

		// find the network from networkID
		readNet := &mastercfg.CfgNetworkState{}
		readNet.StateDriver = stateDriver
		netList, err := readNet.ReadAll()
		if err != nil {
			if !strings.Contains(err.Error(), "key not found") {
				log.Errorf("error reading keys during host create. Error: %s", err)
				return nil, err
			}
		}

		for _, ncfg := range netList {
			nw := ncfg.(*mastercfg.CfgNetworkState)
			if isIPv6 && nw.IPv6Subnet == subnetIP && fmt.Sprintf("%d", nw.IPv6SubnetLen) == subnetLen {
				if tenant == "" || nw.Tenant == tenant {
					networkID = nw.ID
				}
			} else if nw.SubnetIP == subnetIP && fmt.Sprintf("%d", nw.SubnetLen) == subnetLen {
				if tenant == "" || nw.Tenant == tenant {
					networkID = nw.ID
				}
			}
		}
	}

	if len(epgName) > 0 {
		epgCfg = &mastercfg.EndpointGroupState{}
		epgCfg.StateDriver = stateDriver
		if err = epgCfg.Read(epgName); err != nil {
			log.Errorf("failed to read epg %s, %s", epgName, err)
			return nil, err
		}
		log.Infof("AddressAllocRequest for network: %s epg: %s", networkID, epgName)
	}

	if networkID == "" {
		if GetClusterMode() == core.SwarmMode {
			// If the network was created using docker command,
			// we get allocReq before the network is created. Here,
			// we return the first IP in the subnet as gateway IP.
			// Subsequent createNetwork request will come with
			// a subnet and gateway which will allocate the gateway IP
			var ipAddress string
			var subnetLen uint
			subnetIP := strings.Split(allocReq.AddressPool, "/")[0]
			subnetLen = func() uint {
				p, err := strconv.Atoi(strings.Split(allocReq.AddressPool, "/")[1])
				if err != nil {
					log.Errorf("error acquiring subnet len. Error: %s", err)
				}
				return uint(p)
			}()
			if isIPv6 {
				// Get first available IPv6 address
				ipAddress, err = netutils.GetSubnetIPv6(subnetIP, subnetLen, "")
				if err != nil {
					log.Errorf("error acquiring subnet ip. Error: %s", err)
					return "", err
				}
			} else {
				// Get first available IPv4 address
				subnetAddr := netutils.GetSubnetAddr(subnetIP, subnetLen)
				ipAddress, err = netutils.GetSubnetIP(subnetAddr, subnetLen, 32, 1)
				if err != nil {
					log.Errorf("error acquiring subnet ip. Error: %s", err)
					return "", err
				}
			}
			// Build the response
			aresp := AddressAllocResponse{
				NetworkID:   allocReq.NetworkID,
				IPv4Address: ipAddress + "/" + fmt.Sprintf("%d", subnetLen),
			}

			return aresp, nil
		}
		log.Errorf("Could not find the network for: %s", allocReq.NetworkID)
		return nil, errors.New("network not found")
	}

	// find the network from network id
	nwCfg := &mastercfg.CfgNetworkState{}
	nwCfg.StateDriver = stateDriver
	err = nwCfg.Read(networkID)
	if err != nil {
		log.Errorf("network %s is not operational", networkID)
		return nil, err
	}

	// Alloc addresses
	addr, err := networkAllocAddress(nwCfg, epgCfg, allocReq.PreferredIPv4Address, netutils.IsIPv6(allocReq.AddressPool))
	if err != nil {
		log.Errorf("Failed to allocate address. Err: %v", err)
		return nil, err
	}

	var subnetLen uint
	if isIPv6 {
		subnetLen = nwCfg.IPv6SubnetLen
	} else {
		subnetLen = nwCfg.SubnetLen
	}

	// Build the response
	aresp := AddressAllocResponse{
		NetworkID:   allocReq.NetworkID,
		IPv4Address: addr + "/" + fmt.Sprintf("%d", subnetLen),
	}

	return aresp, nil
}
274462
func AscIfAddress(p1Ptr, p2Ptr *IfAddr) int {
	return AscAddress(&p1Ptr.SockAddr, &p2Ptr.SockAddr)
}
1128526
func IsHexAddress(s string) bool {
	if hasHexPrefix(s) {
		s = s[2:]
	}
	return len(s) == 2*AddressLength && isHex(s)
}
382897
func parseIpfsAddr(addr string) ([]ipfsaddr.IPFSAddr, error) {
	mutiladdr, err := ma.NewMultiaddr(addr)
	if err != nil {
		return nil, err
	}
	if _, err := mutiladdr.ValueForProtocol(ma.P_IPFS); err == nil {
		iaddrs := make([]ipfsaddr.IPFSAddr, 1)
		iaddrs[0], err = ipfsaddr.ParseMultiaddr(mutiladdr)
		if err != nil {
			return nil, err
		}
		return iaddrs, nil
	}
	// resolve mutiladdr whose protocol is not ma.P_IPFS
	ctx, cancel := context.WithTimeout(context.Background(), resolveTimeout)
	addrs, err := madns.Resolve(ctx, mutiladdr)
	cancel()
	if len(addrs) == 0 {
		return nil, errors.New("fail to resolve the multiaddr:" + mutiladdr.String())
	}
	iaddrs := make([]ipfsaddr.IPFSAddr, len(addrs))
	for i, addr := range addrs {
		iaddrs[i], err = ipfsaddr.ParseMultiaddr(addr)
		if err != nil {
			return nil, err
		}
	}
	return iaddrs, nil
}
962828
func (dc *DriverCall) AppendSpec(spec *volume.Spec, host volume.VolumeHost, extraOptions map[string]string) error {
	optionsForDriver, err := NewOptionsForDriver(spec, host, extraOptions)
	if err != nil {
		return err
	}

	jsonBytes, err := json.Marshal(optionsForDriver)
	if err != nil {
		return fmt.Errorf("Failed to marshal spec, error: %s", err.Error())
	}

	dc.Append(string(jsonBytes))
	return nil
}
978058
func SockaddrToUDPAddr(sa Sockaddr) *net.UDPAddr {
	ip, zone := SockaddrToIPAndZone(sa)
	switch sa := sa.(type) {
	case *SockaddrInet4:
		return &net.UDPAddr{IP: ip, Port: sa.Port}
	case *SockaddrInet6:
		return &net.UDPAddr{IP: ip, Port: sa.Port, Zone: zone}
	}
	return nil
}
970940
func GetInterfaceIPAddress(_interface string) (string, error) {
	output, err := exec.Command("/sbin/ip", "-4", "-o", "addr").Output()
	if err != nil {
		return "", err
	}

	for _, line := range strings.Split(string(output), "\n") {
		fields := strings.Fields(line)
		if len(fields) < 4 {
			continue
		}

		if strings.HasPrefix(fields[1], _interface) {
			return strings.Split(fields[3], "/")[0], nil
		}
	}

	return "", fmt.Errorf("Unable to find ip for interface: %s", _interface)
}