// Evaluate cachability based on an HTTP request, and parts of the response.
776280
func UsingRequestResponse(req *http.Request,
	statusCode int,
	respHeaders http.Header,
	privateCache bool) ([]Reason, time.Time, error) {
	reasons, time, _, _, err := UsingRequestResponseWithObject(req, statusCode, respHeaders, privateCache)
	return reasons, time, err
}
292373
func Cache(src, cache FS) FS {
	return &cachedFS{
		src:   src,
		cache: cache,
	}
}
436273
func (p *WebPage) EvaluateAsync(script string, delay time.Duration) error {
	return p.ref.process.doJSON("POST", "/webpage/EvaluateAsync", map[string]interface{}{"ref": p.ref.id, "script": script, "delay": int(delay / time.Millisecond)}, nil)
}
1316423
func (cache *Cache) get(proposalHash []byte) (*proposalInfo, error) {
	var hash ProposalHash
	copy(hash[:], proposalHash)
	cache.RLock()
	propInfo := cache.proposals[hash]
	cache.RUnlock()
	if propInfo == nil {
		cache.Lock()
		defer cache.Unlock()
		propInfo = cache.proposals[hash]
		if propInfo == nil {
			prop, err := cache.backend.GetProposal(proposalHash)
			if err != nil {
				return nil, err
			}
			propInfo = &proposalInfo{
				ballot: prop,
			}
			cache.proposals[hash] = propInfo
		}
	}
	return propInfo, nil
}
1195432
func (q *IntentionQueryRequest) CacheInfo() cache.RequestInfo {
	// We only support caching Match queries, so if Match isn't set,
	// then return an empty info object which will cause a pass-through
	// (and likely fail).
	if q.Match == nil {
		return cache.RequestInfo{}
	}

	info := cache.RequestInfo{
		Token:      q.Token,
		Datacenter: q.Datacenter,
		MinIndex:   q.MinQueryIndex,
		Timeout:    q.MaxQueryTime,
	}

	// Calculate the cache key via just hashing the Match struct. This
	// has been configured so things like ordering of entries has no
	// effect (via struct tags).
	v, err := hashstructure.Hash(q.Match, nil)
	if err == nil {
		// If there is an error, we don't set the key. A blank key forces
		// no cache for this request so the request is forwarded directly
		// to the server.
		info.Key = strconv.FormatUint(v, 16)
	}

	return info
}
15966
func (s *sigHead) cache() (err error) {
	if !s.clean {
		s.Protected, err = s.protected.Base64()
		if err != nil {
			return err
		}
		s.Unprotected, err = s.unprotected.Base64()
		if err != nil {
			return err
		}
	}
	s.clean = true
	return nil
}
817876
func (c *Context) ServiceCache(key string, res interface{}) (exists bool) {
	return c.getCacheVal("service", key, res)
}
415305
func (f *httpFetcher) Hash(u *url.URL, a *asc) (string, error) {
	ensureLogger(f.Debug)
	urlStr := u.String()

	if !f.NoCache && f.Rem != nil {
		if useCached(f.Rem.DownloadTime, f.Rem.CacheMaxAge) {
			diag.Printf("image for %s isn't expired, not fetching.", urlStr)
			return f.Rem.BlobKey, nil
		}
	}

	diag.Printf("fetching image from %s", urlStr)

	aciFile, cd, err := f.fetchURL(u, a, eTag(f.Rem))
	if err != nil {
		return "", err
	}
	defer aciFile.Close()

	if key := maybeUseCached(f.Rem, cd); key != "" {
		// TODO(krnowak): that does not update the store with
		// the new CacheMaxAge and Download Time, so it will
		// query the server every time after initial
		// CacheMaxAge is exceeded
		return key, nil
	}
	key, err := f.S.WriteACI(aciFile, imagestore.ACIFetchInfo{
		Latest: false,
	})
	if err != nil {
		return "", err
	}

	// TODO(krnowak): What's the point of the second parameter?
	// The SigURL field in imagestore.Remote seems to be completely
	// unused.
	newRem := imagestore.NewRemote(urlStr, a.Location)
	newRem.BlobKey = key
	newRem.DownloadTime = time.Now()
	if cd != nil {
		newRem.ETag = cd.ETag
		newRem.CacheMaxAge = cd.MaxAge
	}
	err = f.S.WriteRemote(newRem)
	if err != nil {
		return "", err
	}

	return key, nil
}
391093
func (r *Request) Do(method string) *Response {
	r.URL.RawQuery = r.Query.Encode()
	r.Method = method

	cacher := r.Cacher
	cacheBehavior := r.cacherBehavior()
	if cacheBehavior != useCache {
		cacher = noOpCacher
	}

	cached, cachedErr := cacher.Get(r.Request)
	if cachedErr == nil {
		if cached.IsFresh() {
			return cached.Decode(r)
		} else {
			cached.SetupRequest(r.Request)
		}
	}

	httpres, err := r.Client.Do(r.Request)
	if err != nil {
		return ResponseError(err)
	}

	if cachedErr == nil && cacheBehavior == useCache && httpres.StatusCode == 304 {
		cacher.UpdateCache(r.Request, httpres)
		return cached.Decode(r)
	}

	mtype, err := mediaType(httpres)
	if err != nil {
		httpres.Body.Close()
		return ResponseError(err)
	}

	res := &Response{
		MediaType:  mtype,
		BodyClosed: false,
		Response:   httpres,
		Cacher:     cacher,
		isApiError: UseApiError(httpres.StatusCode),
	}

	if !res.AnyError() {
		if cacheBehavior == resetCache {
			r.Cacher.Reset(r.Request)
		} else if cacheBehavior == clearCache {
			r.Cacher.Clear(r.Request)
		} else {
			cacher.Set(r.Request, res)
		}
	}

	return res
}
1275935
func evaluateDigest(params map[string]string, method string, us UserStore, nonces NonceStore, logger *log.Logger) (int, string, bool) {
	user, userOk := params["username"]
	realm, realmOk := params["realm"]
	nonce, nonceOk := params["nonce"]
	response, responseOk := params["response"]
	cnonce, cnonceOk := params["cnonce"]
	qop, qopOk := params["qop"]
	uri, uriOk := params["uri"]
	nc, ncOk := params["nc"]

	if !(userOk && realmOk && nonceOk && responseOk && uriOk) {
		if logger != nil {
			logger.Printf("required param omitted")
		}
		return http.StatusUnauthorized, "", false
	}

	storedUserRealmPassHash, ok, err := us.Lookup(user, realm)

	if !ok {
		if logger != nil {
			logger.Printf("no such user %v in realm %v", user, realm)
		}
		return http.StatusUnauthorized, "", false
	}
	if err != nil {
		if logger != nil {
			logger.Printf("no user")
		}
		return http.StatusInternalServerError, fmt.Sprintf("Unable to lookup user: %s", err.Error()), false
	}

	n, ok, err := nonces.Lookup(nonce)
	if !ok {
		if logger != nil {
			logger.Printf("no such nonce: %#v not in %#v", nonce, nonces)
		}
		return http.StatusUnauthorized, "", true
	}
	if err != nil {
		return http.StatusInternalServerError, fmt.Sprintf("Error processing nonce: %s", err.Error()), false
	}

	// compute A1
	ha1 := ""

	algorithm, algorithmOk := params["algorithm"]
	if !algorithmOk || algorithm == "MD5" {
		ha1 = storedUserRealmPassHash
	} else if algorithm == "MD5-sess" {
		if !cnonceOk {
			return http.StatusBadRequest, "MD5-sess digest without cnonce", false
		}
		v := md5.Sum([]byte(storedUserRealmPassHash + ":" + nonce + ":" + cnonce))
		ha1 = hex.EncodeToString(v[:])
		// we could store ha1 under nonce+cnonce I suppose, that seems to be the intent
		// of the RFC.
	} else {
		return http.StatusNotImplemented, fmt.Sprintf("Unsupported digest algorithm: %s", algorithm), false
	}

	if len(ha1) != 2*md5.Size {
		return http.StatusInternalServerError, fmt.Sprintf("Invalid digest HA1: len=%d", len(ha1)), false
	}

	// compute A2
	ha2 := ""

	if !qopOk || qop == "auth" {
		h := md5.Sum([]byte(method + ":" + uri))
		ha2 = hex.EncodeToString(h[:])
	} else if qop == "auth-int" {
		// Will need to read body, undo transfer encoding, and stick it back in to Request. Ick.
		// I should also point out that libcurl doesn't support auth-int, so validating is going to be rough. Opera
		// is rumored to be the only major browser to support auth-int, according to the internet in 2014
		return http.StatusNotImplemented, fmt.Sprintf("Unsupported digest qop: %s", qop), false
	} else {
		return http.StatusNotImplemented, fmt.Sprintf("Unsupported digest qop: %s", qop), false
	}

	if len(ha2) != 2*md5.Size {
		return http.StatusInternalServerError, fmt.Sprintf("Invalid digest HA2: len=%d", len(ha2)), false
	}

	calculatedResponse := ""

	if !qopOk {
		mm := md5.New()
		mm.Write([]byte(ha1))
		mm.Write([]byte(":" + nonce + ":"))
		mm.Write([]byte(ha2))
		calculatedResponse = hex.EncodeToString(mm.Sum([]byte{}))
	} else if qop == "auth" || qop == "auth-int" {
		if !ncOk {
			return http.StatusBadRequest, "Digest auth or auth-int is missing nc", false
		}
		ncVal, err := strconv.ParseUint(nc, 16, 32)
		if err != nil {
			return http.StatusBadRequest, "Invalid digest nc", false
		}
		if !n.AcceptCounter(uint(ncVal)) {
			return http.StatusUnauthorized, "Digest nc was not valid", true
		}

		r := ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2
		rr := md5.Sum([]byte(r))
		calculatedResponse = hex.EncodeToString(rr[:])
	} else {
		return http.StatusNotImplemented, fmt.Sprintf("Unsupported digest qop: %s", qop), false
	}
	if len(calculatedResponse) != 2*md5.Size {
		return http.StatusInternalServerError, fmt.Sprintf("Miscalculated digest response: %#v", calculatedResponse), false
	}

	n.Next()

	// resist timing attacks, at least here. At this one line.
	if subtle.ConstantTimeCompare([]byte(response), []byte(calculatedResponse)) == 1 {
		return http.StatusOK, "", false
	}

	return http.StatusUnauthorized, "", false
}
334986
func Version(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "text/plain")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
	w.Write([]byte("6"))
}
346617
func (d *Decoder) Evaluate() (err error) {
	defer func() {
		if r := recover(); r != nil {
			switch x := r.(type) {
			case string:
				err = errors.New(x)
			case error:
				err = x
			default:
				err = fmt.Errorf("unexpected error: %v, %T", r, r)
			}
		}
	}()

	d.evaluateProperties(d.vars, false)
	d.evaluateProperties(d.mss.Map(), true)
	for _, b := range d.mss.root.blocks {
		d.evaluateBlock(b)
	}
	return err
}
1334476
func (c *Cache) Get(key string) (resp []byte, ok bool) {
	item, err := memcache.Get(c.Context, cacheKey(key))
	if err != nil {
		if err != memcache.ErrCacheMiss {
			c.Context.Errorf("error getting cached response: %v", err)
		}
		return nil, false
	}
	return item.Value, true
}
208715
func (m *BinDataAsset) Evaluate(data interface{}) (*MemoryAsset, error) {
	if !m.IsTemplate() {
		return nil, errors.Errorf("the asset %s is not a template", m.AssetName)

	}

	var buf bytes.Buffer
	if err := m.template.Execute(&buf, data); err != nil {
		return nil, err
	}

	return NewMemoryAsset(buf.Bytes(), m.GetTargetDir(), m.GetTargetName(), m.GetPermissions()), nil
}
297242
func (r AndRule) Evaluate(headers, query, payload *map[string]interface{}, body *[]byte, remoteAddr string) (bool, error) {
	res := true

	for _, v := range r {
		rv, err := v.Evaluate(headers, query, payload, body, remoteAddr)
		if err != nil {
			return false, err
		}

		res = res && rv
		if !res {
			return res, nil
		}
	}

	return res, nil
}
363244
func (w *Worker) dequeueEvaluation(timeout time.Duration) (
	eval *structs.Evaluation, token string, waitIndex uint64, shutdown bool) {
	// Setup the request
	req := structs.EvalDequeueRequest{
		Schedulers:       w.srv.config.EnabledSchedulers,
		Timeout:          timeout,
		SchedulerVersion: scheduler.SchedulerVersion,
		WriteRequest: structs.WriteRequest{
			Region: w.srv.config.Region,
		},
	}
	var resp structs.EvalDequeueResponse

REQ:
	// Check if we are paused
	w.checkPaused()

	// Make a blocking RPC
	start := time.Now()
	err := w.srv.RPC("Eval.Dequeue", &req, &resp)
	metrics.MeasureSince([]string{"nomad", "worker", "dequeue_eval"}, start)
	if err != nil {
		if time.Since(w.start) > dequeueErrGrace && !w.srv.IsShutdown() {
			w.logger.Error("failed to dequeue evaluation", "error", err)
		}

		// Adjust the backoff based on the error. If it is a scheduler version
		// mismatch we increase the baseline.
		base, limit := backoffBaselineFast, backoffLimitSlow
		if strings.Contains(err.Error(), "calling scheduler version") {
			base = backoffSchedulerVersionMismatch
			limit = backoffSchedulerVersionMismatch
		}

		if w.backoffErr(base, limit) {
			return nil, "", 0, true
		}
		goto REQ
	}
	w.backoffReset()

	// Check if we got a response
	if resp.Eval != nil {
		w.logger.Debug("dequeued evaluation", "eval_id", resp.Eval.ID)
		return resp.Eval, resp.Token, resp.GetWaitIndex(), false
	}

	// Check for potential shutdown
	if w.srv.IsShutdown() {
		return nil, "", 0, true
	}
	goto REQ
}
1194727
func (p *WebPage) EvaluateJavaScript(script string) (interface{}, error) {
	var resp struct {
		ReturnValue interface{} `json:"returnValue"`
	}
	if err := p.ref.process.doJSON("POST", "/webpage/EvaluateJavaScript", map[string]interface{}{"ref": p.ref.id, "script": script}, &resp); err != nil {
		return nil, err
	}
	return resp.ReturnValue, nil
}