// parseHandleLoose parses a TLF handle but leaves some of the canonicality
// checking to public routines like ParseHandle and ParseHandlePreferred.
549183
func parseHandleLoose(
	ctx context.Context, kbpki idutil.KBPKI, idGetter IDGetter,
	osg idutil.OfflineStatusGetter, name string, t tlf.Type) (
	*Handle, error) {
	writerNames, readerNames, extensionSuffix, err :=
		idutil.SplitAndNormalizeTLFName(name, t)
	if err != nil {
		return nil, err
	}

	var extensions []tlf.HandleExtension
	if len(extensionSuffix) != 0 {
		extensions, err = tlf.ParseHandleExtensionSuffix(extensionSuffix)
		if err != nil {
			return nil, err
		}
	}

	offline := keybase1.OfflineAvailability_NONE
	if osg != nil {
		normalizedName, _, err := idutil.NormalizeNamesInTLF(
			writerNames, readerNames, t, extensionSuffix)
		if err != nil {
			return nil, err
		}
		offline = osg.OfflineAvailabilityForPath(
			BuildCanonicalPathForTlfName(t, tlf.CanonicalName(normalizedName)))

		// Make sure we always pass the normalized name to the
		// service, so it can use its cache effectively.
		name = normalizedName
	}

	// First try resolving this full name as an implicit team.  If
	// that doesn't work, fall through to individual name resolution.
	var iteamHandle *Handle
	if doResolveImplicit(ctx, t) {
		rit := resolvableImplicitTeam{kbpki, name, t, offline}
		iteamHandle, err = makeHandleHelper(
			ctx, t, []resolvableUser{rit}, nil, nil, idGetter)
		if err == nil && iteamHandle.tlfID != tlf.NullID {
			// The iteam already has a TLF ID, let's use it.

			extensionList := tlf.HandleExtensionList(extensions)
			sort.Sort(extensionList)
			_, finalizedInfo := extensionList.Splat()

			if finalizedInfo == nil && idGetter != nil {
				// Implicit team chat migration might have set the ID to an
				// old folder that has since been reset.  Check with the
				// server to see if that has happened, and if so, don't use
				// that ID.  When we migrate existing TLFs to iteams, we can
				// probably override the sigchain link with a new one
				// containing the correct TLF ID.
				valid, err := idGetter.ValidateLatestHandleNotFinal(
					ctx, iteamHandle)
				if err != nil {
					return nil, err
				}
				if !valid {
					iteamHandle.tlfID = tlf.NullID
				}
			}

			if iteamHandle.tlfID != tlf.NullID {
				return iteamHandle, nil
			}
		}
		// This is not an implicit team, so continue on to check for a
		// normal team.  TODO: return non-nil errors immediately if they
		// don't simply indicate the implicit team doesn't exist yet
		// (i.e., when we start creating them by default).
	}

	// Before parsing the tlf handle (which results in identify
	// calls that cause tracker popups), first see if there's any
	// quick normalization of usernames we can do.  For example,
	// this avoids an identify in the case of "HEAD" which might
	// just be a shell trying to look for a git repo rather than a
	// real user lookup for "head" (KBFS-531).  Note that the name
	// might still contain assertions, which will result in
	// another alias in a subsequent lookup.
	// This also contains an offline check for canonicality and
	// whether a public folder has readers.
	changesCh := make(chan struct{}, 1)
	writers := make([]resolvableUser, len(writerNames))
	for i, w := range writerNames {
		if t == tlf.SingleTeam {
			w = "team:" + w
		}
		writers[i] = resolvableAssertionWithChangeReport{resolvableAssertion{
			kbpki, kbpki, idGetter, w, keybase1.UID(""), offline}, changesCh}
	}
	readers := make([]resolvableUser, len(readerNames))
	for i, r := range readerNames {
		readers[i] = resolvableAssertionWithChangeReport{resolvableAssertion{
			kbpki, kbpki, idGetter, r, keybase1.UID(""), offline}, changesCh}
	}

	h, err := makeHandleHelper(
		ctx, t, writers, readers, extensions, idGetter)
	if err != nil {
		return nil, err
	}

	if h.tlfID == tlf.NullID && iteamHandle != nil {
		// If the server hasn't provided a TLF ID for the regular
		// handle, switch over to using the i-team handle (which
		// currently must have a null TLF ID).  Before the caller
		// creates and uses the TLF, they must generate a TLF ID and
		// store it in the i-team's sigchain.
		return iteamHandle, nil
	}

	if t == tlf.Private {
		session, err := kbpki.GetCurrentSession(ctx)
		if err != nil {
			return nil, err
		}

		if !h.IsReader(session.UID) {
			return nil, NewReadAccessError(h, session.Name, h.GetCanonicalPath())
		}
	}

	canonicalName := string(h.GetCanonicalName())
	if extensionSuffix != "" {
		extensionList := tlf.HandleExtensionList(extensions)
		sort.Sort(extensionList)
		var canonExtensionString string
		// If this resolve is being done in a "quick" way that doesn't
		// check for implicit teams, we might not know if this handle
		// is backed by a team or not.  But (mostly for tests) we need
		// to make sure the suffix reflects the right format,
		// otherwise we'll get too many levels of non-canonical
		// redirects.  So if the user explicitly specified a "#1" in
		// their suffix, let's keep it there and assume the user knows
		// what they're doing.
		if h.IsBackedByTeam() || strings.Contains(extensionSuffix, "#1") {
			canonExtensionString = extensionList.SuffixForTeamHandle()
		} else {
			canonExtensionString = extensionList.Suffix()
		}
		_, _, currExtensionSuffix, _ :=
			idutil.SplitAndNormalizeTLFName(canonicalName, t)
		canonicalName = strings.Replace(
			canonicalName, tlf.HandleExtensionSep+currExtensionSuffix,
			canonExtensionString, 1)
		h.name = tlf.CanonicalName(canonicalName)
		if canonExtensionString != tlf.HandleExtensionSep+extensionSuffix {
			return nil, errors.WithStack(
				idutil.TlfNameNotCanonical{
					Name:      name,
					NameToTry: canonicalName,
				})
		}
	}

	select {
	case <-changesCh:
	default:
		// No changes were performed because of resolver.
		return h, nil
	}

	// Otherwise, identify before returning the canonical name.
	err = IdentifyHandle(ctx, kbpki, kbpki, osg, h)
	if err != nil {
		return nil, err
	}

	// In this case return both the handle and the error,
	// ParseHandlePreferred uses this to make the redirection
	// better.
	return h, errors.WithStack(idutil.TlfNameNotCanonical{
		Name:      name,
		NameToTry: canonicalName,
	})
}
113303
func (m *Method) PreHandle(handler Handler) *Method {
	m.preHandlers = append(m.preHandlers, handler)
	return m
}
867521
func (c *MutableTLSCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
	c.Lock()
	conn := tls.Server(rawConn, c.config)
	c.Unlock()
	if err := conn.Handshake(); err != nil {
		rawConn.Close()
		return nil, nil, err
	}

	return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil
}
450947
func CheckHandleOffline(
	ctx context.Context, name string, t tlf.Type) error {
	_, _, _, err := idutil.SplitAndNormalizeTLFName(name, t)
	return err
}
918446
func (h *contextualHandler) Handle(err error) {
	err = With(err, h.keyvals...)

	h.handler.Handle(err)
}
1366740
func (f *Folder) TlfHandleChange(ctx context.Context,
	newHandle *tlfhandle.Handle) {
	f.fs.log.CDebugf(ctx, "TlfHandleChange called on %q",
		canonicalNameIfNotNil(newHandle))
	// Handle in the background because we shouldn't lock during the
	// notification
	f.fs.queueNotification(func() {
		f.tlfHandleChangeInvalidate(context.Background(), newHandle)
	})
}
320028
func (l *LARS) wrapHandler(h Handler) HandlerFunc {

	switch h := h.(type) {
	case HandlerFunc:
		return h

	case func(Context):
		return h

	case http.Handler, http.HandlerFunc:
		return func(c Context) {

			ctx := c.BaseContext()

			if h.(http.Handler).ServeHTTP(ctx.response, ctx.request); ctx.response.status != http.StatusOK || ctx.response.committed {
				return
			}

			if ctx.index+1 < len(ctx.handlers) {
				c.Next()
			}
		}

	case func(http.ResponseWriter, *http.Request):
		return func(c Context) {

			ctx := c.BaseContext()

			if h(ctx.response, ctx.request); ctx.response.status != http.StatusOK || ctx.response.committed {
				return
			}

			if ctx.index+1 < len(ctx.handlers) {
				c.Next()
			}
		}

	case func(http.ResponseWriter, *http.Request, http.Handler):

		return func(c Context) {
			ctx := c.BaseContext()

			h(ctx.response, ctx.request, NativeChainHandler)
		}

	case func(http.Handler) http.Handler:

		hf := h(NativeChainHandler)

		return func(c Context) {
			ctx := c.BaseContext()

			hf.ServeHTTP(ctx.response, ctx.request)
		}

	default:
		if fn, ok := l.customHandlersFuncs[reflect.TypeOf(h)]; ok {
			return func(c Context) {
				fn(c, h)
			}
		}

		panic("unknown handler")
	}
}
219672
func (md *RootMetadataV2) TlfHandleExtensions() (
	extensions []tlf.HandleExtension) {
	if md.ConflictInfo != nil {
		extensions = append(extensions, *md.ConflictInfo)
	}
	if md.FinalizedInfo != nil {
		extensions = append(extensions, *md.FinalizedInfo)
	}
	return extensions
}
533986
func (l *RateLimiter) WrapHandle(h http.Handler) {
	l.TokenLimiter.Wrap(h)
}
1155738
func ParseLevel(lvl string) (logrus.Level, error) {
	if lvl == "trace" {
		return TraceLevel, nil
	}
	return logrus.ParseLevel(lvl)
}
750015
func NewManagedHandle(
	resourceLocation string,
	handle interface{},
	pool ResourcePool,
	options Options) ManagedHandle {

	h := &managedHandleImpl{
		location: resourceLocation,
		handle:   handle,
		pool:     pool,
		options:  options,
	}
	atomic.StoreInt32(&h.isActive, 1)

	return h
}
777377
func (t *ParseTree) Parse(p *Parser) (Statement, error) {
	for {
		tok, pos, lit := p.ScanIgnoreWhitespace()
		if subtree := t.Tokens[tok]; subtree != nil {
			t = subtree
			continue
		}

		if stmt := t.Handlers[tok]; stmt != nil {
			return stmt(p)
		}

		// There were no registered handlers. Return the valid tokens in the order they were added.
		return nil, newParseError(tokstr(tok, lit), t.Keys, pos)
	}
}
33114
func (l *Limiter) WrapHandle(h http.Handler) {
	l.rateLimiter.Wrap(h)
	l.ConnLimiter.Wrap(l.rateLimiter)
}
786641
func (s *HTTPServer) parse(resp http.ResponseWriter, req *http.Request, dc *string, b *structs.QueryOptions) bool {
	return s.parseInternal(resp, req, dc, b, true)
}
741105
func (e *TableScanExec) nextHandle() (handle int64, found bool, err error) {
	for {
		handle, found, err = e.t.Seek(e.ctx, e.seekHandle)
		if err != nil || !found {
			return 0, false, err
		}
		return handle, true, nil
	}
}
487538
func ParseLevel(lvl string) Level {
	switch {
	case strings.EqualFold(lvl, debugLevelStr):
		return DebugLevel
	case strings.EqualFold(lvl, infoLevelStr):
		return InfoLevel
	case strings.EqualFold(lvl, warnLevelStr),
		strings.EqualFold(lvl, warningLevelStr):
		return WarnLevel
	case strings.EqualFold(lvl, errorLevelStr):
		return ErrorLevel
	case strings.EqualFold(lvl, fatalLevelStr):
		return FatalLevel
	case strings.EqualFold(lvl, panicLevelStr):
		return PanicLevel
	}
	return UnknownLevel
}
1315910
func ParseHandlePreferredQuick(
	ctx context.Context, kbpki idutil.KBPKI, osg idutil.OfflineStatusGetter,
	name string, ty tlf.Type) (handle *Handle, err error) {
	// Override the KBPKI with one that doesn't try to resolve
	// implicit teams.
	kbpki = noImplicitTeamKBPKI{kbpki}
	return ParseHandlePreferred(ctx, kbpki, nil, osg, name, ty)
}