// resolveProxyToken attempts to resolve an ACL ID to a local proxy token.
// If a local proxy isn't found with that token, nil is returned.
189073
func (a *Agent) resolveProxyToken(id string) *local.ManagedProxy {
	for _, p := range a.State.Proxies() {
		if p.ProxyToken == id {
			return p
		}
	}

	return nil
}
915180
func (r *IpnsResolver) ResolveAsync(ctx context.Context, name string, options ...opts.ResolveOpt) <-chan Result {
	return resolveAsync(ctx, r, name, opts.ProcessOpts(options))
}
701355
func (s *PresenceService) UpsertProxy(server services.Server) error {
	return s.upsertServer(proxiesPrefix, server)
}
349628
func (pc *ProxyConfig) useProxy(addr string) bool {
	if len(addr) == 0 {
		return true
	}
	host, _, err := net.SplitHostPort(addr)
	if err != nil {
		return false
	}
	if host == "localhost" {
		return false
	}
	ip := net.ParseIP(host)
	if ip != nil && ip.IsLoopback() {
		return false
	}

	if pc.noProxy == "*" {
		return false
	}

	addr = strings.ToLower(strings.TrimSpace(addr))
	if hasPort(addr) {
		addr = addr[:strings.LastIndex(addr, ":")]
	}

	for _, p := range strings.Split(pc.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 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
		}
		if _, net, err := net.ParseCIDR(p); ip != nil && err == nil && net.Contains(ip) {
			return false
		}
	}
	return true
}
1312866
func resolveAddr(ctx context.Context, host, port string) (string, string, error) {
	resolver := net.DefaultResolver

	// Resolve the port number. This may translate service names
	// e.g. "postgresql" to a numeric value.
	portNumber, err := resolver.LookupPort(ctx, "tcp", port)
	if err != nil {
		return "", "", errors.Wrapf(err, "resolving up port: %v", port)
	}
	port = strconv.Itoa(portNumber)

	// Resolve the address.
	if host == "" || host == "localhost" {
		return host, port, nil
	}

	addr, err := lookupAddr(ctx, resolver, host)
	if err != nil {
		return "", "", errors.Wrap(err, "looking up address")
	}
	return addr, port, nil
}
53899
func (p *pruner) resolveISTagName(g genericgraph.Graph, referrer *corev1.ObjectReference, istagName string) (*imagegraph.ImageStreamTagNode, error) {
	name, tag, err := imageapi.ParseImageStreamTagName(istagName)
	if err != nil {
		if p.ignoreInvalidRefs {
			klog.Warningf("Failed to parse ImageStreamTag name %q: %v", istagName, err)
			return nil, nil
		}
		return nil, newErrBadReferenceTo("ImageStreamTag", istagName, referrer, err.Error())
	}
	node := g.Find(imagegraph.ImageStreamTagNodeName(makeISTag(referrer.Namespace, name, tag)))
	if istNode, ok := node.(*imagegraph.ImageStreamTagNode); ok {
		return istNode, nil
	}

	return nil, nil
}
192903
func (r *IpnsResolver) resolveOnceAsync(ctx context.Context, name string, options opts.ResolveOpts) <-chan onceResult {
	out := make(chan onceResult, 1)
	log.Debugf("RoutingResolver resolving %s", name)
	cancel := func() {}

	if options.DhtTimeout != 0 {
		// Resolution must complete within the timeout
		ctx, cancel = context.WithTimeout(ctx, options.DhtTimeout)
	}

	name = strings.TrimPrefix(name, "/ipns/")
	pid, err := peer.IDB58Decode(name)
	if err != nil {
		log.Debugf("RoutingResolver: could not convert public key hash %s to peer ID: %s\n", name, err)
		out <- onceResult{err: err}
		close(out)
		cancel()
		return out
	}

	// Name should be the hash of a public key retrievable from ipfs.
	// We retrieve the public key here to make certain that it's in the peer
	// store before calling GetValue() on the DHT - the DHT will call the
	// ipns validator, which in turn will get the public key from the peer
	// store to verify the record signature
	_, err = routing.GetPublicKey(r.routing, ctx, pid)
	if err != nil {
		log.Debugf("RoutingResolver: could not retrieve public key %s: %s\n", name, err)
		out <- onceResult{err: err}
		close(out)
		cancel()
		return out
	}

	// Use the routing system to get the name.
	// Note that the DHT will call the ipns validator when retrieving
	// the value, which in turn verifies the ipns record signature
	ipnsKey := ipns.RecordKey(pid)

	vals, err := r.routing.SearchValue(ctx, ipnsKey, dht.Quorum(int(options.DhtRecordCount)))
	if err != nil {
		log.Debugf("RoutingResolver: dht get for name %s failed: %s", name, err)
		out <- onceResult{err: err}
		close(out)
		cancel()
		return out
	}

	go func() {
		defer cancel()
		defer close(out)
		for {
			select {
			case val, ok := <-vals:
				if !ok {
					return
				}

				entry := new(pb.IpnsEntry)
				err = proto.Unmarshal(val, entry)
				if err != nil {
					log.Debugf("RoutingResolver: could not unmarshal value for name %s: %s", name, err)
					emitOnceResult(ctx, out, onceResult{err: err})
					return
				}

				var p path.Path
				// check for old style record:
				if valh, err := mh.Cast(entry.GetValue()); err == nil {
					// Its an old style multihash record
					log.Debugf("encountered CIDv0 ipns entry: %s", valh)
					p = path.FromCid(cid.NewCidV0(valh))
				} else {
					// Not a multihash, probably a new style record
					p, err = path.ParsePath(string(entry.GetValue()))
					if err != nil {
						emitOnceResult(ctx, out, onceResult{err: err})
						return
					}
				}

				ttl := DefaultResolverCacheTTL
				if entry.Ttl != nil {
					ttl = time.Duration(*entry.Ttl)
				}
				switch eol, err := ipns.GetEOL(entry); err {
				case ipns.ErrUnrecognizedValidity:
					// No EOL.
				case nil:
					ttEol := time.Until(eol)
					if ttEol < 0 {
						// It *was* valid when we first resolved it.
						ttl = 0
					} else if ttEol < ttl {
						ttl = ttEol
					}
				default:
					log.Errorf("encountered error when parsing EOL: %s", err)
					emitOnceResult(ctx, out, onceResult{err: err})
					return
				}

				emitOnceResult(ctx, out, onceResult{value: p, ttl: ttl})
			case <-ctx.Done():
				return
			}
		}
	}()

	return out
}
774003
func (b *block) resolveLocalUses() {
	unresolved := b.uses[:0]
	for _, use := range b.uses {
		if bind := lookupLocal(use); bind.scope == Local {
			use.id.Scope = uint8(bind.scope)
			use.id.Index = bind.index
		} else {
			unresolved = append(unresolved, use)
		}
	}
	b.uses = unresolved
}
1072180
func (g *graph) ResolveAll() []reflect.Value {
	var values []reflect.Value
	for _, def := range g.definitions {
		values = append(values, def.Resolve(g))
	}
	return values
}
993683
func (s *HTTPServer) AgentConnectProxyConfig(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Get the proxy ID. Note that this is the ID of a proxy's service instance.
	id := strings.TrimPrefix(req.URL.Path, "/v1/agent/connect/proxy/")

	// Maybe block
	var queryOpts structs.QueryOptions
	if parseWait(resp, req, &queryOpts) {
		// parseWait returns an error itself
		return nil, nil
	}

	// Parse the token - don't resolve a proxy token to a real token
	// that will be done with a call to verifyProxyToken later along with
	// other security relevant checks.
	var token string
	s.parseTokenWithoutResolvingProxyToken(req, &token)

	// Parse hash specially since it's only this endpoint that uses it currently.
	// Eventually this should happen in parseWait and end up in QueryOptions but I
	// didn't want to make very general changes right away.
	hash := req.URL.Query().Get("hash")

	return s.agentLocalBlockingQuery(resp, hash, &queryOpts,
		func(ws memdb.WatchSet) (string, interface{}, error) {
			// Retrieve the proxy specified
			proxy := s.agent.State.Proxy(id)
			if proxy == nil {
				resp.WriteHeader(http.StatusNotFound)
				fmt.Fprintf(resp, "unknown proxy service ID: %s", id)
				return "", nil, nil
			}

			// Lookup the target service as a convenience
			target := s.agent.State.Service(proxy.Proxy.TargetServiceID)
			if target == nil {
				// Not found since this endpoint is only useful for agent-managed proxies so
				// service missing means the service was deregistered racily with this call.
				resp.WriteHeader(http.StatusNotFound)
				fmt.Fprintf(resp, "unknown target service ID: %s", proxy.Proxy.TargetServiceID)
				return "", nil, nil
			}

			// Validate the ACL token - because this endpoint uses data local to a single
			// agent, this function is responsible for all enforcement regarding
			// protection of the configuration. verifyProxyToken will match the proxies
			// token to the correct service or in the case of being provide a real ACL
			// token it will ensure that the requester has ServiceWrite privileges
			// for this service.
			_, isProxyToken, err := s.agent.verifyProxyToken(token, target.Service, id)
			if err != nil {
				return "", nil, err
			}

			// Watch the proxy for changes
			ws.Add(proxy.WatchCh)

			hash, err := hashstructure.Hash(proxy.Proxy, nil)
			if err != nil {
				return "", nil, err
			}
			contentHash := fmt.Sprintf("%x", hash)

			// Set defaults
			config, err := s.agent.applyProxyConfigDefaults(proxy.Proxy)
			if err != nil {
				return "", nil, err
			}

			// Only merge in telemetry config from agent if the requested is
			// authorized with a proxy token. This prevents us leaking potentially
			// sensitive config like Circonus API token via a public endpoint. Proxy
			// tokens are only ever generated in-memory and passed via ENV to a child
			// proxy process so potential for abuse here seems small. This endpoint in
			// general is only useful for managed proxies now so it should _always_ be
			// true that auth is via a proxy token but inconvenient for testing if we
			// lock it down so strictly.
			if isProxyToken {
				// Add telemetry config. Copy the global config so we can customize the
				// prefix.
				telemetryCfg := s.agent.config.Telemetry
				telemetryCfg.MetricsPrefix = telemetryCfg.MetricsPrefix + ".proxy." + target.ID

				// First see if the user has specified telemetry
				if userRaw, ok := config["telemetry"]; ok {
					// User specified domething, see if it is compatible with agent
					// telemetry config:
					var uCfg lib.TelemetryConfig
					dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
						Result: &uCfg,
						// Make sure that if the user passes something that isn't just a
						// simple override of a valid TelemetryConfig that we fail so that we
						// don't clobber their custom config.
						ErrorUnused: true,
					})
					if err == nil {
						if err = dec.Decode(userRaw); err == nil {
							// It did decode! Merge any unspecified fields from agent config.
							uCfg.MergeDefaults(&telemetryCfg)
							config["telemetry"] = uCfg
						}
					}
					// Failed to decode, just keep user's config["telemetry"] verbatim
					// with no agent merge.
				} else {
					// Add agent telemetry config.
					config["telemetry"] = telemetryCfg
				}
			}

			reply := &api.ConnectProxyConfig{
				ProxyServiceID:    proxy.Proxy.ProxyService.ID,
				TargetServiceID:   target.ID,
				TargetServiceName: target.Service,
				ContentHash:       contentHash,
				ExecMode:          api.ProxyExecMode(proxy.Proxy.ExecMode.String()),
				Command:           proxy.Proxy.Command,
				Config:            config,
				Upstreams:         proxy.Proxy.Upstreams.ToAPI(),
			}
			return contentHash, reply, nil
		})
}
927533
func (s *Schema) ResolveRefs(loadExternal bool) {
	s.resolveSelfAndBelow(*s, *s, loadExternal)
}
1069011
func NewProxyConnection() *ProxyConnection {
	nonce, err := crypto.GenerateRandomBytes(16)
	if err != nil {
		return nil
	}

	return &ProxyConnection{
		state: ClientTokenSend,
		Auth: AuthInfo{
			LocalContext: nonce,
		},
	}
}
235302
func (s *Schema) ResolveURL(v string) (u *url.URL, err error) {
	if pdebug.Enabled {
		g := pdebug.IPrintf("START Schema.ResolveURL '%s'", v)
		defer func() {
			if err != nil {
				g.IRelease("END Schema.ResolveURL '%s': error %s", v, err)
			} else {
				g.IRelease("END Schema.ResolveURL '%s' -> '%s'", v, u)
			}
		}()
	}
	base := s.BaseURL()
	if pdebug.Enabled {
		pdebug.Printf("Using base URL '%s'", base)
	}
	u, err = base.Parse(v)
	if err != nil {
		return nil, err
	}
	return u, nil
}
375021
func (cc *ClientConn) waitForResolvedAddrs(ctx context.Context) error {
	// This is on the RPC path, so we use a fast path to avoid the
	// more-expensive "select" below after the resolver has returned once.
	if cc.firstResolveEvent.HasFired() {
		return nil
	}
	select {
	case <-cc.firstResolveEvent.Done():
		return nil
	case <-ctx.Done():
		return status.FromContextError(ctx.Err()).Err()
	case <-cc.ctx.Done():
		return ErrClientConnClosing
	}
}
884757
func resolveServiceIDs(c context.Context, urls []string, out *identityset.Set) error {
	// URL fetch calls below should be extra fast. If they get stuck, something is
	// horribly wrong, better to abort soon.
	c, abort := clock.WithTimeout(c, 5*time.Second)
	defer abort()

	type Result struct {
		URL string
		ID  identity.Identity
		Err error
	}

	ch := make(chan Result, len(urls))

	for _, url := range urls {
		go func(url string) {
			id, err := fetchLUCIServiceIdentity(c, url)
			ch <- Result{url, id, err}
		}(url)
	}

	for i := 0; i < len(urls); i++ {
		result := <-ch
		if result.Err != nil {
			if transient.Tag.In(result.Err) {
				return result.Err
			}
			return fmt.Errorf("could not resolve %q to service ID - %s", result.URL, result.Err)
		}
		out.AddIdentity(result.ID)
	}

	return nil
}
1347559
func (d *domainClient) ResolveNode(ctx context.Context, args *ResolveNodeArgs) (reply *ResolveNodeReply, err error) {
	reply = new(ResolveNodeReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "DOM.resolveNode", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "DOM.resolveNode", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "DOM", Op: "ResolveNode", Err: err}
	}
	return
}
471957
func ResolveUrl(url *url.URL) (*url.URL, error) {
	if url.Scheme == "file" || url.Scheme == "socket" || url.Scheme == "unix" {
		return utilUrl.Copy(url), nil
	}
	if len(url.Host) > 0 && url.Host[0] == '/' {
		return utilUrl.Copy(url), nil
	}
	if len(url.Host) >= 3 && url.Host[1] == ':' && url.Host[2] == '/' {
		return utilUrl.Copy(url), nil
	}

	mysqlNotation := regExpResolveUrl.FindAllString(url.Host, 1)
	if len(mysqlNotation) >= 1 {
		return utilUrl.Copy(url), nil
	}

	out := utilUrl.Copy(url)

	host, err := Resolve(url.Host)
	if err != nil {
		return nil, e.Forward(err)
	}
	out.Host = host
	return out, nil
}