// Fallback defines the http.Handler that the CircuitBreaker should route
// requests to when it prevents a request from taking its normal path.
555540
func Fallback(h http.Handler) CircuitBreakerOption {
	return func(c *CircuitBreaker) error {
		c.fallback = h
		return nil
	}
}
622863
func (p *Processor) Callback(w http.ResponseWriter, r *http.Request) {
	p.RLock()
	defer p.RUnlock()

	// Validate the JWT token through the handler.
	token, originURL, status, err := p.userTokenHandler.Callback(r)
	if err != nil {
		http.Error(w, fmt.Sprintf("Invalid code %s:", err), http.StatusInternalServerError)
		return
	}

	cookie := &http.Cookie{
		Name:     "X-APORETO-AUTH",
		Value:    token,
		HttpOnly: true,
		Secure:   true,
		Path:     "/",
	}

	http.SetCookie(w, cookie)

	// We transmit the information in the return payload for applications
	// that choose to use it directly without a cookie.
	data, err := json.MarshalIndent(cookie, " ", " ")
	if err != nil {
		http.Error(w, "Bad data", http.StatusInternalServerError)
		return
	}

	// We redirect here to the original URL that the application attempted
	// to access.
	w.Header().Add("Location", originURL)
	http.Error(w, string(data), status)
}
1288580
func (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) {
	// range for retry counts that we store is [0,13]
	if responseCode > maxResponseCode || serverIsOverloadedSet.Has(responseCode) {
		b.Backoff.Next(b.baseUrlKey(actualUrl), b.Backoff.Clock.Now())
		return
	} else if responseCode >= 300 || err != nil {
		klog.V(4).Infof("Client is returning errors: code %v, error %v", responseCode, err)
	}

	//If we got this far, there is no backoff required for this URL anymore.
	b.Backoff.Reset(b.baseUrlKey(actualUrl))
}
679340
func (m *AuthMethod) callbackHandler(ctx *router.Context) {
	c, rw, r := ctx.Context, ctx.Writer, ctx.Request

	// This code path is hit when user clicks "Deny" on consent page.
	q := r.URL.Query()
	errorMsg := q.Get("error")
	if errorMsg != "" {
		replyError(c, rw, errors.New("login error"), "OpenID login error: %s", errorMsg)
		return
	}

	// Validate inputs.
	code := q.Get("code")
	if code == "" {
		replyError(c, rw, errors.New("login error"), "Missing 'code' parameter")
		return
	}
	stateTok := q.Get("state")
	if stateTok == "" {
		replyError(c, rw, errors.New("login error"), "Missing 'state' parameter")
		return
	}
	state, err := validateStateToken(c, stateTok)
	if err != nil {
		replyError(c, rw, err, "Failed to validate 'state' token")
		return
	}

	// Revalidate "dest_url". It was already validate in loginHandler when
	// generating state token, but just in case.
	dest, err := normalizeURL(state["dest_url"])
	if err != nil {
		replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err)
		return
	}

	// Callback URI is hardcoded in OAuth2 client config and must always point
	// to default version on GAE. Yet we want to support logging to non-default
	// versions that have different hostnames. Do some redirect dance here to pass
	// control to required version if necessary (so that it can set cookie on
	// non-default version domain). Same handler with same params, just with
	// different hostname. For most common case of signing in into default version
	// this code path is not triggered.
	if state["host_url"] != r.Host {
		// There's no Scheme in r.URL. Append one, otherwise url.String() returns
		// relative (broken) URL. And replace the hostname with desired one.
		url := *r.URL
		if m.Insecure {
			url.Scheme = "http"
		} else {
			url.Scheme = "https"
		}
		url.Host = state["host_url"]
		logging.Warningf(c, "Redirecting to callback URI on another host %q", url.Host)
		http.Redirect(rw, r, url.String(), http.StatusFound)
		return
	}

	// Use authorization code to grab user profile.
	cfg, err := fetchCachedSettings(c)
	if err != nil {
		replyError(c, rw, err, "Can't load OpenID settings - %s", err)
		return
	}
	uid, user, err := handleAuthorizationCode(c, cfg, code)
	if err != nil {
		replyError(c, rw, err, "Error when fetching user profile - %s", err)
		return
	}

	// Grab previous session from the cookie to close it once new one is created.
	prevSid, err := decodeSessionCookie(c, r)
	if err != nil {
		replyError(c, rw, err, "Error when decoding session cookie - %s", err)
		return
	}

	// Create session in the session store.
	expTime := clock.Now(c).Add(sessionCookieToken.Expiration)
	sid, err := m.SessionStore.OpenSession(c, uid, user, expTime)
	if err != nil {
		replyError(c, rw, err, "Error when creating the session - %s", err)
		return
	}
	(logging.Fields{"sid": sid}).Infof(c, "Opened a new session")

	// Kill previous session now that new one is successfully created.
	if prevSid != "" {
		(logging.Fields{"sid": prevSid}).Infof(c, "Closing the previous session")
		if err = m.SessionStore.CloseSession(c, prevSid); err != nil {
			replyError(c, rw, err, "Error when closing the session - %s", err)
			return
		}
	}

	// Set the cookies.
	cookie, err := makeSessionCookie(c, sid, !m.Insecure)
	if err != nil {
		replyError(c, rw, err, "Can't make session cookie - %s", err)
		return
	}
	http.SetCookie(rw, cookie)
	m.removeIncompatibleCookies(rw, r)

	// Redirect to the final destination page.
	logging.Infof(c, "Redirecting to %s", dest)
	http.Redirect(rw, r, dest, http.StatusFound)
}
1246605
func (c *client) URL(key string, fallback *url.URL) *url.URL {
	if v := c.Getenv(key); v != "" {
		u, err := url.Parse(v)
		if err != nil {
			return fallback
		}

		return u
	}

	return fallback
}
1041406
func go_callback(queueId C.int, data *C.uchar, length C.int, idx uint32, vc* VerdictContainerC) {
	xdata := C.GoBytes(unsafe.Pointer(data), length)

	var packet gopacket.Packet
	if xdata[0] & 0xf0 == ipv4version {
		packet = gopacket.NewPacket(xdata, layers.LayerTypeIPv4, gopacket.DecodeOptions{Lazy: true, NoCopy: true})
	} else {
		packet = gopacket.NewPacket(xdata, layers.LayerTypeIPv6, gopacket.DecodeOptions{Lazy: true, NoCopy: true})
	}

	p := NFPacket{
		verdictChannel: make(chan VerdictContainer),
		Packet: packet,
	}

	theTabeLock.RLock()
	cb, ok := theTable[idx]
	theTabeLock.RUnlock()
	if !ok {
		fmt.Fprintf(os.Stderr, "Dropping, unexpectedly due to bad idx=%d\n", idx)
		(*vc).verdict = C.uint(NF_DROP)
		(*vc).data = nil
		(*vc).length = 0
	}
	select {
		case *cb <- p:
			select {
				case v := <-p.verdictChannel:
					if v.Packet == nil {
						(*vc).verdict = C.uint(v.Verdict)
						(*vc).data = nil
						(*vc).length = 0
					} else {
						(*vc).verdict = C.uint(v.Verdict)
						(*vc).data = (*C.uchar)(unsafe.Pointer(&v.Packet[0]))
						(*vc).length = C.uint(len(v.Packet))
					}
			}

		default:
			fmt.Fprintf(os.Stderr, "Dropping, unexpectedly due to no recv, idx=%d\n", idx)
			(*vc).verdict = C.uint(NF_DROP)
			(*vc).data = nil
			(*vc).length = 0
	}
}
724347
func DefaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
	mult := math.Pow(2, float64(attemptNum)) * float64(min)
	sleep := time.Duration(mult)
	if float64(sleep) != mult || sleep > max {
		sleep = max
	}
	return sleep
}
487275
func (q *query) Rollback(ctx context.Context, request *querypb.RollbackRequest) (response *querypb.RollbackResponse, err error) {
	defer q.server.HandlePanic(&err)
	ctx = callerid.NewContext(callinfo.GRPCCallInfo(ctx),
		request.EffectiveCallerId,
		request.ImmediateCallerId,
	)
	if err := q.server.Rollback(ctx, request.Target, request.TransactionId); err != nil {
		return nil, vterrors.ToGRPC(err)
	}

	return &querypb.RollbackResponse{}, nil
}
393275
func disconnectCallback(n *Node) em.DisconnectCallbackFunc {
	return func() {
		n.Online = false
		n.logger.Info("status", "down")

		if n.disconnectCh != nil {
			n.disconnectCh <- true
		}
	}
}
221500
func (q *Queue) PushBack(v interface{}) {
	q.lazyInit()
	q.lazyGrow()
	q.rep[q.back] = v
	q.back = q.inc(q.back)
	q.length++
}
910727
func (cc *ClientConn) fallbackToDefaultServiceConfig(sc string) bool {
	if cc.dopts.disableServiceConfig {
		return true
	}
	// The logic below is temporary, will be removed once we change the resolver.State ServiceConfig field type.
	// Right now, we assume that empty service config string means resolver does not return a config.
	if sc == "" {
		return true
	}
	// TODO: the logic below is temporary. Once we finish the logic to validate service config
	// in resolver, we will replace the logic below.
	_, err := parseServiceConfig(sc)
	return err != nil
}
540593
func createCircuitBreakerOptions(expression string) cbreaker.CircuitBreakerOption {
	return cbreaker.Fallback(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		tracing.SetErrorWithEvent(req, "blocked by circuit-breaker (%q)", expression)
		rw.WriteHeader(http.StatusServiceUnavailable)

		if _, err := rw.Write([]byte(http.StatusText(http.StatusServiceUnavailable))); err != nil {
			log.FromContext(req.Context()).Error(err)
		}
	}))
}
704562
func (d *DefaultMetricCollector) FallbackSuccesses() *rolling.Number {
	d.mutex.RLock()
	defer d.mutex.RUnlock()
	return d.fallbackSuccesses
}
851124
func URL(key string, fallback *url.URL) *url.URL {
	return DefaultClient.URL(key, fallback)
}
754749
func (l *PacketIntervalList) PushBack(v PacketInterval) *PacketIntervalElement {
	l.lazyInit()
	return l.insertValue(v, l.root.prev)
}
972547
func (a Authorizer) goBack(rw http.ResponseWriter, req *http.Request) {
	redirectSession, _ := a.cookiejar.Get(req, "redirects")
	defer redirectSession.Save(req, rw)
	redirectSession.Flashes()
	redirectSession.AddFlash(req.URL.Path)
}
1225455
func FallthroughDetector(hndl Handler) Detector {
	return Detector{
		Needed:  0,
		Test:    func([]byte) bool { return true },
		Handler: hndl,
	}
}