// findClosestSessions to match a given string with sessions trie tree.
514115
func findClosestSessions(session string) []string {
	sessionsTree := trie.NewTrie() // Allocate a new trie for sessions strings.
	for _, sid := range getSessionIDs() {
		sessionsTree.Insert(sid)
	}
	var closestSessions []string
	for _, value := range sessionsTree.PrefixMatch(session) {
		closestSessions = append(closestSessions, value.(string))
	}
	sort.Strings(closestSessions)
	return closestSessions
}
226124
func DjangoSessionsBySessionKey(db XODB, sessionKey string) ([]*DjangoSession, error) {
	var err error

	// sql query
	const sqlstr = `SELECT ` +
		`session_key, session_data, expire_date ` +
		`FROM public.django_session ` +
		`WHERE session_key = $1`

	// run query
	XOLog(sqlstr, sessionKey)
	q, err := db.Query(sqlstr, sessionKey)
	if err != nil {
		return nil, err
	}
	defer q.Close()

	// load results
	res := []*DjangoSession{}
	for q.Next() {
		ds := DjangoSession{
			_exists: true,
		}

		// scan
		err = q.Scan(&ds.SessionKey, &ds.SessionData, &ds.ExpireDate)
		if err != nil {
			return nil, err
		}

		res = append(res, &ds)
	}

	return res, nil
}
123795
func (handle *ContextHandle) OpenSession() (mPkcs11.SessionHandle, error) {

	handle.lock.RLock()
	defer handle.lock.RUnlock()

	var session mPkcs11.SessionHandle
	var err error
	for i := 0; i < handle.opts.openSessionRetry; i++ {
		session, err = handle.ctx.OpenSession(handle.slot, mPkcs11.CKF_SERIAL_SESSION|mPkcs11.CKF_RW_SESSION)
		if err != nil {
			logger.Warnf("OpenSession failed, retrying [%s]\n", err)
		} else {
			logger.Debug("OpenSession succeeded")
			break
		}
	}
	return session, err
}
9107
func (m SessionMock) Tables(keyspace string) ([]string, error) {
	var r = m.Called(keyspace)

	return r.Get(0).([]string), r.Error(1)
}
633310
func GetWebSessionSchemaWithExtensions(extension string) string {
	return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, fmt.Sprintf(WebSessionSpecV2Schema, extension), DefaultDefinitions)
}
194368
func (s *SessionRegistry) getParties(sess *session) []*party {
	var parties []*party

	if sess == nil {
		return parties
	}

	sess.Lock()
	defer sess.Unlock()

	for _, p := range sess.parties {
		parties = append(parties, p)
	}

	return parties
}
415778
func (e Endpoints) FindSessionByToken(ctx context.Context, token string) (*pb.Session, error) {
	req := &pb.FindSessionByTokenRequest{
		Token: token,
	}
	response, err := e.FindSessionByTokenEndpoint(ctx, req)
	if err != nil {
		return nil, err
	}
	res := response.(*pb.FindSessionByTokenReply)
	return res.Session, toError(res.Err)
}
1073660
func (_m *FacadeInterface) FindHostsInPool(ctx datastore.Context, poolID string) ([]host.Host, error) {
	ret := _m.Called(ctx, poolID)

	var r0 []host.Host
	if rf, ok := ret.Get(0).(func(datastore.Context, string) []host.Host); ok {
		r0 = rf(ctx, poolID)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]host.Host)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(datastore.Context, string) error); ok {
		r1 = rf(ctx, poolID)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
849102
func isSessionDirExists() bool {
	sessionDir, err := getSessionDir()
	fatalIf(err.Trace(), "Unable to determine session folder.")

	if _, e := os.Stat(sessionDir); e != nil {
		return false
	}
	return true
}
1270093
func (s *DbSession) FindAll(query Q, document Document) (interface{}, error) {
	fn := func(q *mgo.Query, result interface{}) error {
		return q.All(result)
	}
	return s.executeFindAll(query, document, fn)
}
1119352
func (db *TowerDB) QueryMatches(
	breachHints []wtdb.BreachHint) ([]wtdb.Match, error) {

	db.mu.Lock()
	defer db.mu.Unlock()

	var matches []wtdb.Match
	for _, hint := range breachHints {
		sessionsToUpdates, ok := db.blobs[hint]
		if !ok {
			continue
		}

		for id, update := range sessionsToUpdates {
			info, ok := db.sessions[id]
			if !ok {
				panic("session not found")
			}

			match := wtdb.Match{
				ID:            id,
				SeqNum:        update.SeqNum,
				Hint:          hint,
				EncryptedBlob: update.EncryptedBlob,
				SessionInfo:   info,
			}
			matches = append(matches, match)
		}
	}

	return matches, nil
}
1355632
func (t *TowerDB) QueryMatches(breachHints []BreachHint) ([]Match, error) {
	var matches []Match
	err := t.db.View(func(tx *bbolt.Tx) error {
		sessions := tx.Bucket(sessionsBkt)
		if sessions == nil {
			return ErrUninitializedDB
		}

		updates := tx.Bucket(updatesBkt)
		if updates == nil {
			return ErrUninitializedDB
		}

		// Iterate through the target breach hints, appending any
		// matching updates to the set of matches.
		for _, hint := range breachHints {
			// If a bucket does not exist for this hint, no matches
			// are known.
			updatesForHint := updates.Bucket(hint[:])
			if updatesForHint == nil {
				continue
			}

			// Otherwise, iterate through all (session id, update)
			// pairs, creating a Match for each.
			err := updatesForHint.ForEach(func(k, v []byte) error {
				// Load the session via the session id for this
				// update. The session info contains further
				// instructions for how to process the state
				// update.
				session, err := getSession(sessions, k)
				switch {
				case err == ErrSessionNotFound:
					log.Warnf("Missing session=%x for "+
						"matched state update hint=%x",
						k, hint)
					return nil

				case err != nil:
					return err
				}

				// Decode the state update containing the
				// encrypted blob.
				update := &SessionStateUpdate{}
				err = update.Decode(bytes.NewReader(v))
				if err != nil {
					return err
				}

				var id SessionID
				copy(id[:], k)

				// Construct the final match using the found
				// update and its session info.
				match := Match{
					ID:            id,
					SeqNum:        update.SeqNum,
					Hint:          hint,
					EncryptedBlob: update.EncryptedBlob,
					SessionInfo:   session,
				}

				matches = append(matches, match)

				return nil
			})
			if err != nil {
				return err
			}
		}

		return nil
	})
	if err != nil {
		return nil, err
	}

	return matches, nil
}
802103
func (p *Provider) GetSession(token string) (map[string]string, error) {
	sess := struct {
		Name       string `xml:"name"`
		Key        string `xml:"key"`
		Subscriber bool   `xml:"subscriber"`
	}{}

	err := p.request(true, map[string]string{"method": "auth.getSession", "token": token}, &sess)
	return map[string]string{"login": sess.Name, "token": sess.Key}, err
}
1139353
func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
	session := engine.NewSession()
	defer session.Close()
	return session.Find(beans, condiBeans...)
}
1229888
func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
	defer session.resetStatement()
	if session.IsAutoClose {
		defer session.Close()
	}

	sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
	if sliceValue.Kind() != reflect.Slice && sliceValue.Kind() != reflect.Map {
		return errors.New("needs a pointer to a slice or a map")
	}

	sliceElementType := sliceValue.Type().Elem()

	if session.Statement.RefTable == nil {
		if sliceElementType.Kind() == reflect.Ptr {
			if sliceElementType.Elem().Kind() == reflect.Struct {
				pv := reflect.New(sliceElementType.Elem())
				session.Statement.setRefValue(pv.Elem())
			} else {
				return errors.New("slice type")
			}
		} else if sliceElementType.Kind() == reflect.Struct {
			pv := reflect.New(sliceElementType)
			session.Statement.setRefValue(pv.Elem())
		} else {
			return errors.New("slice type")
		}
	}

	var table = session.Statement.RefTable

	var addedTableName = (len(session.Statement.JoinStr()) > 0)
	var autoCond builder.Cond
	if !session.Statement.noAutoCondition && len(condiBean) > 0 {
		var err error
		autoCond, err = session.Statement.buildConds(table, condiBean[0], true, true, false, true, addedTableName)
		if err != nil {
			panic(err)
		}
	} else {
		// !oinume! Add "<col> IS NULL" to WHERE whatever condiBean is given.
		// See https://github.com/coscms/xorm/issues/179
		if col := table.DeletedColumn(); col != nil && !session.Statement.unscoped { // tag "deleted" is enabled
			colName := session.Statement.colName(col, addedTableName)
			autoCond = builder.IsNull{colName}.Or(builder.Eq{colName: "0001-01-01 00:00:00"})
		}
	}

	var sqlStr string
	var args []interface{}
	if session.Statement.RawSQL == "" {
		if len(session.Statement.TableName()) <= 0 {
			return ErrTableNotFound
		}

		columnStr := session.Statement.genColumnStr()

		condSQL, condArgs, _ := builder.ToSQL(session.Statement.cond.And(autoCond), session.Engine.QuoteKey)

		args = append(session.Statement.joinArgs, condArgs...)
		sqlStr = session.Statement.genSelectSQL(columnStr, condSQL)
		// for mssql and use limit
		qs := strings.Count(sqlStr, "?")
		if len(args)*2 == qs {
			args = append(args, args...)
		}
	} else {
		sqlStr = session.Statement.RawSQL
		args = session.Statement.RawParams
	}

	var err error
	if session.Statement.JoinStr() == "" {
		if cacher := session.Engine.getCacher2(table); cacher != nil &&
			session.Statement.UseCache &&
			!session.Statement.IsDistinct &&
			!session.Statement.unscoped {
			err = session.cacheFind(sliceElementType, sqlStr, rowsSlicePtr, args...)
			if err != ErrCacheFailed {
				return err
			}
			err = nil // !nashtsai! reset err to nil for ErrCacheFailed
			session.Engine.logger.Warn("Cache Find Failed")
		}
	}

	if sliceValue.Kind() != reflect.Map {
		var rawRows *core.Rows

		session.queryPreprocess(&sqlStr, args...)
		if session.IsAutoCommit {
			_, rawRows, err = session.innerQuery(sqlStr, args...)
		} else {
			rawRows, err = session.Tx.Query(sqlStr, args...)
		}
		if err != nil {
			return err
		}
		defer rawRows.Close()

		fields, err := rawRows.Columns()
		if err != nil {
			return err
		}

		var newElemFunc func() reflect.Value
		if sliceElementType.Kind() == reflect.Ptr {
			newElemFunc = func() reflect.Value {
				return reflect.New(sliceElementType.Elem())
			}
		} else {
			newElemFunc = func() reflect.Value {
				return reflect.New(sliceElementType)
			}
		}

		var sliceValueSetFunc func(*reflect.Value)

		if sliceValue.Kind() == reflect.Slice {
			if sliceElementType.Kind() == reflect.Ptr {
				sliceValueSetFunc = func(newValue *reflect.Value) {
					sliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(newValue.Interface())))
				}
			} else {
				sliceValueSetFunc = func(newValue *reflect.Value) {
					sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(newValue.Interface()))))
				}
			}
		}

		var newValue = newElemFunc()
		dataStruct := rValue(newValue.Interface())
		if dataStruct.Kind() != reflect.Struct {
			return errors.New("Expected a pointer to a struct")
		}

		return session.rows2Beans(rawRows, fields, len(fields), session.Engine.autoMapType(dataStruct), newElemFunc, sliceValueSetFunc)
	}

	resultsSlice, err := session.query(sqlStr, args...)
	if err != nil {
		return err
	}

	keyType := sliceValue.Type().Key()

	for _, results := range resultsSlice {
		var newValue reflect.Value
		if sliceElementType.Kind() == reflect.Ptr {
			newValue = reflect.New(sliceElementType.Elem())
		} else {
			newValue = reflect.New(sliceElementType)
		}
		err := session.scanMapIntoStruct(newValue.Interface(), results)
		if err != nil {
			return err
		}
		var key interface{}
		// if there is only one pk, we can put the id as map key.
		if len(table.PrimaryKeys) == 1 {
			key, err = str2PK(string(results[table.PrimaryKeys[0]]), keyType)
			if err != nil {
				return err
			}
		} else {
			if keyType.Kind() != reflect.Slice {
				panic("don't support multiple primary key's map has non-slice key type")
			} else {
				var keys core.PK = make([]interface{}, 0, len(table.PrimaryKeys))
				for _, pk := range table.PrimaryKeys {
					skey, err := str2PK(string(results[pk]), keyType)
					if err != nil {
						return err
					}
					keys = append(keys, skey)
				}
				key = keys
			}
		}

		if sliceElementType.Kind() == reflect.Ptr {
			sliceValue.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(newValue.Interface()))
		} else {
			sliceValue.SetMapIndex(reflect.ValueOf(key), reflect.Indirect(reflect.ValueOf(newValue.Interface())))
		}
	}

	return nil
}
1024625
func NewSessionService() *SessionService {
	return &SessionService{
		FindSessionFn:   func(context.Context, string) (*platform.Session, error) { return nil, fmt.Errorf("mock session") },
		CreateSessionFn: func(context.Context, string) (*platform.Session, error) { return nil, fmt.Errorf("mock session") },
		ExpireSessionFn: func(context.Context, string) error { return fmt.Errorf("mock session") },
	}
}
365777
func (s *server) GetSession(namespace string, id ID) (*Session, error) {
	item, err := s.bk.Get(context.TODO(), activeKey(namespace, string(id)))
	if err != nil {
		if trace.IsNotFound(err) {
			return nil, trace.NotFound("session(%v, %v) is not found", namespace, id)
		}
		return nil, trace.Wrap(err)
	}
	var sess Session
	if err := json.Unmarshal(item.Value, &sess); err != nil {
		return nil, trace.Wrap(err)
	}
	return &sess, nil
}