// Session --------------------------------------------------------------------
// NewSession is called by session stores to create a new session instance.
427570
func NewSession(store Store, name string) *Session {
	return &Session{
		Values:  make(map[interface{}]interface{}),
		store:   store,
		name:    name,
		Options: new(Options),
	}
}
1131431
func NewSessionWithLevel(level aws.LogLevelType, logger *logrus.Logger) *session.Session {
	awsConfig := &aws.Config{
		CredentialsChainVerboseErrors: aws.Bool(true),
	}
	return NewSessionWithConfigLevel(awsConfig, level, logger)
}
980239
func NewSessionVars() *SessionVars {
	return &SessionVars{
		Users:         make(map[string]string),
		Systems:       make(map[string]string),
		TxnCtx:        &TransactionContext{},
		StrictSQLMode: true,
		Status:        mysql.ServerStatusAutocommit,
		StmtCtx:       new(StatementContext),
	}
}
941247
func newSession(c *connection, es proton.Session, setting ...SessionOption) *session {
	s := &session{
		connection: c,
		pSession:   es,
	}
	s.endpoint.init(es.String())
	for _, set := range setting {
		set(s)
	}
	c.handler.sessions[s.pSession] = s
	s.pSession.SetIncomingCapacity(s.incomingCapacity)
	s.pSession.SetOutgoingWindow(s.outgoingWindow)
	s.pSession.Open()
	return s
}
1220600
func NewSession(name, addr, keyfile string) Session {
	return &samSession{
		name:       name,
		addr:       addr,
		minversion: "3.0",
		maxversion: "3.0",
		keys:       NewKeyfile(keyfile),
	}
}
927888
func (s *Semaphore) createSession() (string, error) {
	session := s.c.Session()
	se := &SessionEntry{
		Name:     s.opts.SessionName,
		TTL:      s.opts.SessionTTL,
		Behavior: SessionBehaviorDelete,
	}
	id, _, err := session.Create(se, nil)
	if err != nil {
		return "", err
	}
	return id, nil
}
753867
func (l *Lock) createSession() (string, error) {
	session := l.c.Session()
	se := l.opts.SessionOpts
	if se == nil {
		se = &SessionEntry{
			Name: l.opts.SessionName,
			TTL:  l.opts.SessionTTL,
		}
	}
	id, _, err := session.Create(se, nil)
	if err != nil {
		return "", err
	}
	return id, 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") },
	}
}
258541
func NewSessionRecord() *SessionRecord {
	ss := &protobuf.SessionStructure{}
	record := &SessionRecord{sessionState: &sessionState{ss},
		Fresh: true,
	}
	return record
}
316508
func NewSession(qs graph.QuadStore, lang string) Session {
	if l := languages[lang]; l.Session != nil {
		return l.Session(qs)
	}
	return nil
}
1050248
func newSession(ch Channel, reqs <-chan *Request) (*Session, error) {
	s := &Session{
		ch: ch,
	}
	s.exitStatus = make(chan error, 1)
	go func() {
		s.exitStatus <- s.wait(reqs)
	}()

	return s, nil
}
59278
func NewSessionHandler(xp rpc.Transporter, g *libkb.GlobalContext) *SessionHandler {
	return &SessionHandler{
		BaseHandler:  NewBaseHandler(g, xp),
		Contextified: libkb.NewContextified(g),
	}
}
712692
func (t *Tokbox) NewSession(location string, mm MediaMode, ctx ...context.Context) (*Session, error) {
	params := url.Values{}

	if len(location) > 0 {
		params.Add("location", location)
	}

	params.Add("p2p.preference", string(mm))

	var endpoint string
	if t.BetaUrl == "" {
		endpoint = apiHost
	} else {
		endpoint = t.BetaUrl
	}
	req, err := http.NewRequest("POST", endpoint+apiSession, strings.NewReader(params.Encode()))
	if err != nil {
		return nil, err
	}

	//Create jwt token
	jwt, err := t.jwtToken()
	if err != nil {
		return nil, err
	}

	req.Header.Add("Accept", "application/json")
	req.Header.Add("X-OPENTOK-AUTH", jwt)

	if len(ctx) == 0 {
		ctx = append(ctx, nil)
	}
	res, err := client(ctx[0]).Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		return nil, fmt.Errorf("Tokbox returns error code: %v", res.StatusCode)
	}

	var s []Session
	if err = json.NewDecoder(res.Body).Decode(&s); err != nil {
		return nil, err
	}

	if len(s) < 1 {
		return nil, fmt.Errorf("Tokbox did not return a session")
	}

	o := s[0]
	o.T = t
	return &o, nil
}
1066053
func newSession(id rsession.ID, r *SessionRegistry, ctx *ServerContext) (*session, error) {
	serverSessions.Inc()
	rsess := rsession.Session{
		ID: id,
		TerminalParams: rsession.TerminalParams{
			W: teleport.DefaultTerminalWidth,
			H: teleport.DefaultTerminalHeight,
		},
		Login:      ctx.Identity.Login,
		Created:    time.Now().UTC(),
		LastActive: time.Now().UTC(),
		ServerID:   ctx.srv.ID(),
		Namespace:  r.srv.GetNamespace(),
	}
	term := ctx.GetTerm()
	if term != nil {
		winsize, err := term.GetWinSize()
		if err != nil {
			return nil, trace.Wrap(err)
		}
		rsess.TerminalParams.W = int(winsize.Width)
		rsess.TerminalParams.H = int(winsize.Height)
	}

	// get the session server where session information lives. if the recording
	// proxy is being used and this is a node, then a discard session server will
	// be returned here.
	sessionServer := r.srv.GetSessionServer()

	err := sessionServer.CreateSession(rsess)
	if err != nil {
		if trace.IsAlreadyExists(err) {
			// if session already exists, make sure they are compatible
			// Login matches existing login
			existing, err := sessionServer.GetSession(r.srv.GetNamespace(), id)
			if err != nil {
				return nil, trace.Wrap(err)
			}
			if existing.Login != rsess.Login {
				return nil, trace.AccessDenied(
					"can't switch users from %v to %v for session %v",
					rsess.Login, existing.Login, id)
			}
		}
		// return nil, trace.Wrap(err)
		// No need to abort. Perhaps the auth server is down?
		// Log the error and continue:
		r.log.Errorf("Failed to create new session: %v.", err)
	}

	sess := &session{
		log: logrus.WithFields(logrus.Fields{
			trace.Component: teleport.Component(teleport.ComponentSession, r.srv.Component()),
		}),
		id:        id,
		registry:  r,
		parties:   make(map[rsession.ID]*party),
		writer:    newMultiWriter(),
		login:     ctx.Identity.Login,
		closeC:    make(chan bool),
		lingerTTL: defaults.SessionIdlePeriod,
	}
	return sess, nil
}
1238846
func NewSessionWithConfig(awsConfig *aws.Config, logger *logrus.Logger) *session.Session {
	return NewSessionWithConfigLevel(awsConfig, aws.LogDebugWithRequestErrors, logger)
}
654767
func NewSessionState(pluginArgsMsg string, plugin Plugin, meta *PluginMeta) (*SessionState, error, int) {
	pluginArg := &Arg{}
	err := json.Unmarshal([]byte(pluginArgsMsg), pluginArg)
	if err != nil {
		return nil, err, 2
	}

	// If no port was provided we let the OS select a port for us.
	// This is safe as address is returned in the Response and keep
	// alive prevents unattended plugins.
	if pluginArg.listenPort == "" {
		pluginArg.listenPort = "0"
	}

	// If no PingTimeoutDuration was provided we need to set it
	if pluginArg.PingTimeoutDuration == 0 {
		pluginArg.PingTimeoutDuration = PingTimeoutDurationDefault
	}

	// Generate random token for this session
	rb := make([]byte, 32)
	rand.Read(rb)
	rs := base64.URLEncoding.EncodeToString(rb)

	logger := &log.Logger{
		Out:       os.Stderr,
		Formatter: &simpleFormatter{},
		Hooks:     make(log.LevelHooks),
		Level:     pluginArg.LogLevel,
	}

	var enc encoding.Encoder
	switch meta.RPCType {
	case NativeRPC:
		enc = encoding.NewGobEncoder()
	case GRPC:
		enc = encoding.NewGobEncoder()
		//TODO(CDR): re-think once content-types is settled
	}
	ss := &SessionState{
		Arg:     pluginArg,
		Encoder: enc,

		plugin:   plugin,
		token:    rs,
		killChan: make(chan int),
		logger:   logger,
	}

	if !meta.Unsecure {
		key, err := rsa.GenerateKey(rand.Reader, 2048)
		if err != nil {
			return nil, err, 2
		}
		encrypt := encrypter.New(nil, key)
		enc.SetEncrypter(encrypt)
		ss.Encrypter = encrypt
		ss.privateKey = key
	}
	return ss, nil, 0
}
306837
func (s *Event) SetSession(v *Session) *Event {
	s.Session = v
	return s
}