// Detect if an error is "bind: address already in use"
//
// Originally from https://stackoverflow.com/a/52152912/164234
175814
func isErrorAddressAlreadyInUse(err error) bool {
	errOpError, ok := err.(*net.OpError)
	if !ok {
		return false
	}
	errSyscallError, ok := errOpError.Err.(*os.SyscallError)
	if !ok {
		return false
	}
	errErrno, ok := errSyscallError.Err.(syscall.Errno)
	if !ok {
		return false
	}
	if errErrno == syscall.EADDRINUSE {
		return true
	}
	const WSAEADDRINUSE = 10048
	if runtime.GOOS == "windows" && errErrno == WSAEADDRINUSE {
		return true
	}
	return false
}
1128526
func IsHexAddress(s string) bool {
	if hasHexPrefix(s) {
		s = s[2:]
	}
	return len(s) == 2*AddressLength && isHex(s)
}
447355
func lookupLocal(use use) binding {
	for env := use.env; env != nil; env = env.parent {
		if bind, ok := env.bindings[use.id.Name]; ok {
			if bind.scope == Free {
				// shouldn't exist till later
				log.Fatalf("%s: internal error: %s, %d", use.id.NamePos, use.id.Name, bind)
			}
			return bind // found
		}
		if env.function != nil {
			break
		}
	}
	return binding{} // not found in this function
}
1073859
func EnsureHTTPS(address string) string {
	if strings.HasPrefix(address, "https://") {
		return address
	}
	if strings.HasPrefix(address, "http://") {
		addr := strings.Replace(address, "http://", "https://", 1)
		logger.Debugf("LXD requires https://, using: %s", addr)
		return addr
	}
	return "https://" + address
}
1331639
func isValidAddress(addr string, errPrefix string) error {
	parsedIP := net.ParseIP(addr)
	if parsedIP == nil {
		_, err := net.LookupHost(addr)
		if err != nil {
			errString := fmt.Sprintf("%s Address '%s' is not a valid address/hostname", errPrefix, addr)
			return errors.New(errString)
		}
	}
	return nil
}
874898
func (s *Server) UseAlert(a alerts.FilterDeleter) {
	s.netServer.useAlert(a)
	s.udsServer.useAlert(a)
}
975694
func (ipv6 IPv6Addr) ContainsAddress(x IPv6Address) bool {
	xAddr := IPv6Addr{
		Address: x,
		Mask:    ipv6HostMask,
	}

	{
		xIPv6 := xAddr.FirstUsable().(IPv6Addr)
		yIPv6 := ipv6.FirstUsable().(IPv6Addr)
		if xIPv6.CmpAddress(yIPv6) >= 1 {
			return false
		}
	}

	{
		xIPv6 := xAddr.LastUsable().(IPv6Addr)
		yIPv6 := ipv6.LastUsable().(IPv6Addr)
		if xIPv6.CmpAddress(yIPv6) <= -1 {
			return false
		}
	}
	return true
}
84830
func (c *linkAddrCache) checkLinkRequest(k tcpip.FullAddress, attempt int) bool {
	c.mu.Lock()
	defer c.mu.Unlock()

	entry, ok := c.cache[k]
	if !ok {
		// Entry was evicted from the cache.
		return true
	}

	switch s := entry.state(); s {
	case ready, failed, expired:
		// Entry was made ready by resolver or failed. Either way we're done.
		return true
	case incomplete:
		if attempt+1 >= c.resolutionAttempts {
			// Max number of retries reached, mark entry as failed.
			entry.changeState(failed)
			return true
		}
		// No response yet, need to send another ARP request.
		return false
	default:
		panic(fmt.Sprintf("invalid cache entry state: %s", s))
	}
}
933025
func GetAddress() Addresser {
	mu.Lock()
	defer mu.Unlock()

	if address == nil {
		address = &Address{}
	}
	return address
}
1261111
func (h *emptyHandle) EnsureAddressBind(address, devName string) (exist bool, err error) {
	return false, fmt.Errorf("netlink not supported for this platform")
}
1317870
func (broker *Broker) Bind(endpoint string) (err error) {
	err = broker.socket.Bind(endpoint)
	if err != nil {
		log.Println("E: MDP broker/0.2.0 failed to bind at", endpoint)
		return
	}
	log.Println("I: MDP broker/0.2.0 is active at", endpoint)
	return
}
467750
func fetchAddressUsed(ns walletdb.ReadBucket, scope *KeyScope,
	addressID []byte) bool {

	scopedBucket, err := fetchReadScopeBucket(ns, scope)
	if err != nil {
		return false
	}

	bucket := scopedBucket.NestedReadBucket(usedAddrBucketName)

	addrHash := sha256.Sum256(addressID)
	return bucket.Get(addrHash[:]) != nil
}
1357241
func (s *Socket) Bind(endpoint string) (err error) {
	cstr := C.CString(endpoint)
	defer C.free(unsafe.Pointer(cstr))
	r := C.zmq_bind(s.sock, cstr)
	if r == -1 {
		err = zmqerr()
	}
	return
}
1149130
func (re *JSRE) Bind(name string, v interface{}) error {
	return re.Set(name, v)
}
122192
func (a *AddrManager) GetAddress() *KnownAddress {
	// Protect concurrent access.
	a.mtx.Lock()
	defer a.mtx.Unlock()

	if a.numAddresses() == 0 {
		return nil
	}

	// Use a 50% chance for choosing between tried and new table entries.
	if a.nTried > 0 && (a.nNew == 0 || a.rand.Intn(2) == 0) {
		// Tried entry.
		large := 1 << 30
		factor := 1.0
		for {
			// pick a random bucket.
			bucket := a.rand.Intn(len(a.addrTried))
			if a.addrTried[bucket].Len() == 0 {
				continue
			}

			// Pick a random entry in the list
			e := a.addrTried[bucket].Front()
			for i :=
				a.rand.Int63n(int64(a.addrTried[bucket].Len())); i > 0; i-- {
				e = e.Next()
			}
			ka := e.Value.(*KnownAddress)
			randval := a.rand.Intn(large)
			if float64(randval) < (factor * ka.chance() * float64(large)) {
				log.Tracef("Selected %v from tried bucket",
					NetAddressKey(ka.na))
				return ka
			}
			factor *= 1.2
		}
	} else {
		// new node.
		// XXX use a closure/function to avoid repeating this.
		large := 1 << 30
		factor := 1.0
		for {
			// Pick a random bucket.
			bucket := a.rand.Intn(len(a.addrNew))
			if len(a.addrNew[bucket]) == 0 {
				continue
			}
			// Then, a random entry in it.
			var ka *KnownAddress
			nth := a.rand.Intn(len(a.addrNew[bucket]))
			for _, value := range a.addrNew[bucket] {
				if nth == 0 {
					ka = value
				}
				nth--
			}
			randval := a.rand.Intn(large)
			if float64(randval) < (factor * ka.chance() * float64(large)) {
				log.Tracef("Selected %v from new bucket",
					NetAddressKey(ka.na))
				return ka
			}
			factor *= 1.2
		}
	}
}
1326793
func useProxy(addr string) bool {
	if len(addr) == 0 {
		return true
	}
	var noProxy string
	for _, env := range []string{teleport.NoProxy, strings.ToLower(teleport.NoProxy)} {
		noProxy = os.Getenv(env)
		if noProxy != "" {
			break
		}
	}

	if noProxy == "" {
		return true
	}
	if noProxy == "*" {
		return false
	}

	addr = strings.ToLower(strings.TrimSpace(addr))
	if hasPort(addr) {
		addr = addr[:strings.LastIndex(addr, ":")]
	}
	for _, p := range strings.Split(noProxy, ",") {
		p = strings.ToLower(strings.TrimSpace(p))
		if len(p) == 0 {
			continue
		}
		if hasPort(p) {
			p = p[:strings.LastIndex(p, ":")]
		}
		if addr == p {
			return false
		}
		if len(p) == 0 {
			// There is no host part, likely the entry is malformed; ignore.
			continue
		}
		if p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:]) {
			// no_proxy ".foo.com" matches "bar.foo.com" or "foo.com"
			return false
		}
		if p[0] != '.' && strings.HasSuffix(addr, p) && addr[len(addr)-len(p)-1] == '.' {
			// no_proxy "foo.com" matches "bar.foo.com"
			return false
		}
	}
	return true
}
703547
func (api *API) IsAddressUsed(address Hash) (bool, error) {
	var err1, err2 error
	var states []bool
	var txs Hashes
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		states, err1 = api.WereAddressesSpentFrom(address)
	}()
	go func() {
		defer wg.Done()
		txs, err2 = api.FindTransactions(FindTransactionsQuery{Addresses: Hashes{address}})
	}()
	wg.Wait()

	if err := firstNonNilErr(err1, err2); err != nil {
		return false, err
	}

	if states[0] || len(txs) > 0 {
		return true, nil
	}
	return false, nil
}