package mtproto

import (
	

	
	

	
)

// Session represents connection state.
type Session struct {
	ID   int64
	Key  crypto.AuthKey
	Salt int64
	// PermKey is non-zero only in PFS mode and is used for bindTempAuthKey.
	PermKey crypto.AuthKey
	// KeyCreatedAt is the creation time of the permanent key (Key, or PermKey
	// in PFS mode), Unix seconds; zero if unknown.
	KeyCreatedAt int64
}

// Session returns current connection session info.
func ( *Conn) () Session {
	.updateSalt()

	.sessionMux.RLock()
	defer .sessionMux.RUnlock()
	return Session{
		Key:          .authKey,
		Salt:         .salt,
		ID:           .sessionID,
		PermKey:      .permKey,
		KeyCreatedAt: .permKeyCreatedAt,
	}
}

// newSessionID sets session id to random value.
func ( *Conn) () error {
	,  := crypto.RandInt64(.rand)
	if  != nil {
		return 
	}

	.sessionMux.Lock()
	 := .sessionID
	.sessionID = 
	.sessionMux.Unlock()

	.traceSession(, )
	return nil
}

// reuseSession continues the server session saved in sessionState for key,
// if any.
func ( *Conn) ( context.Context,  crypto.AuthKey) bool {
	if .sessionState == nil || .pfs {
		return false
	}
	, ,  := .sessionState.load(.ID)
	if ! {
		return false
	}
	.sessionMux.Lock()
	 := .sessionID
	.sessionID = 
	.sessionMux.Unlock()
	.reqMux.Lock()
	.sentContentMessages = 
	.reqMux.Unlock()
	.sessionContinued = true
	.log.Debug(, "Continuing session", log.Int32("content_messages", ))
	.traceSession(, )
	return true
}

// releaseSessionState saves the session of this connection for the next one.
func ( *Conn) () {
	 := .session()
	.reqMux.Lock()
	 := .sentContentMessages
	.reqMux.Unlock()
	 := .ID
	if .pfs || .Key.Zero() {
		// PFS: the temporary key and its session end with the connection.
		 = 0
	}
	select {
	case <-.sessionFailed.Ready():
		// The next connection starts a new session.
		 = 0
	default:
	}
	.sessionState.release(.Key.ID, , )
}

// errSessionFailed stops Run when the server session can't be used any more,
// see failSession.
var errSessionFailed = errors.New("server session failed")

// failSession ends the server session after bad_msg_notification "msg_id
// too high": msg_ids already sent in it were ahead of the server time, and
// ids must keep increasing within a session, so corrected ids can only be
// used in a new one. The message id generator is reset to the corrected
// time and the connection is replaced by one in a new session; pending
// requests are sent again there. This is what TDLib does
// (SessionConnection: "Session will be closed", a new Session with new
// AuthData follows).
func ( *Conn) () {
	if ,  := .messageID.(interface{ () });  {
		.()
	}
	.sessionFailed.Signal()
}

// errSessionReset is reported to requests that were pending in a session
// that is gone, so they are sent again with new msg_id and seqno.
var errSessionReset = errors.New("session reset")

// currentSessionID returns current session id.
func ( *Conn) () int64 {
	.sessionMux.RLock()
	defer .sessionMux.RUnlock()
	return .sessionID
}

// resetSession clears the state bound to the previous session after the
// auth key and session were replaced in place: the new session starts with
// seqno 0, an empty received msg_id buffer and no cached future salts, and
// pending requests are sent again in it. Pending acks are dropped by ackLoop.
//
// This matches tdesktop (SessionPrivate::changeSessionId on a key change,
// followed by resendAll).
//
// Must be called with exchangeLock held for writing, so nothing is sent
// with the old msg_id and seqno in the new session.
func ( *Conn) () {
	.reqMux.Lock()
	.sentContentMessages = 0
	// Message ids are monotonic: everything allocated before this boundary
	// belongs to the old session and is refused by write.
	.sessionStartMsgID.Store(.newMessageID())
	.reqMux.Unlock()

	if ,  := .messageIDBuf.(interface{ () });  {
		.()
	}
	.salts.Reset()
	if .rpc != nil {
		.rpc.NotifyErrorAll(errSessionReset)
	}
}