package mtproto

import (
	
	

	
	

	
	
	
	
	
)

const maxBindTempAuthKeyAttempts = 3

// bindRetryDelay is the delay before bind attempt n+1 after
// ENCRYPTED_MESSAGE_INVALID: a fresh permanent key may not have reached all
// servers yet, so retries need time (1 s, 2 s, 4 s).
func ( int) time.Duration {
	return time.Second << ( - 1)
}

func ( *Conn) ( context.Context) error {
	var  error
	for  := 1;  <= maxBindTempAuthKeyAttempts; ++ {
		 := .bindTempAuthKeyAttempt()
		if  == nil {
			if .sessionState != nil {
				.sessionState.setLastBind(.clock.Now().Unix())
			}
			return nil
		}
		 = 

		if tgerr.Is(, tg.ErrEncryptedMessageInvalid) {
			if  := .handleBindEncryptedMessageInvalid(, );  != nil {
				return 
			}
			if  < maxBindTempAuthKeyAttempts {
				 := .clock.Timer(bindRetryDelay())
				select {
				case <-.Done():
					clock.StopTimer()
					return .Err()
				case <-.C():
				}
			}
			continue
		}
		if tgerr.Is(, "CONNECTION_NOT_INITED") {
			if  := .handleBindConnectionNotInited();  != nil {
				return 
			}
			// Retry same bind call on transient ordering/race conditions.
			continue
		}
		return 
	}

	return errors.Wrap(, "temporary auth key bind retry limit reached")
}

func ( *Conn) ( context.Context) error {
	 := .session()
	if .Key.Zero() {
		return errors.New("temporary key is zero")
	}
	if .PermKey.Zero() {
		return errors.New("permanent key is zero")
	}
	if .ID == 0 {
		return errors.New("temporary session id is zero")
	}

	.sessionMux.RLock()
	 := .tempKeyExpiry
	.sessionMux.RUnlock()
	if  == 0 {
		 = .clock.Now().Unix() + int64(.tempKeyTTL)
	}

	,  := crypto.RandInt64(.rand)
	if  != nil {
		return errors.Wrap(, "generate nonce")
	}
	 := &crypto.BindAuthKeyInner{
		Nonce:         ,
		TempAuthKeyID: .Key.IntID(),
		PermAuthKeyID: .PermKey.IntID(),
		TempSessionID: .ID,
		ExpiresAt:     int(),
	}

	// bindTempAuthKey is a content-related request and must consume normal
	// msg_id/seq_no progression to remain valid in current temp session.
	,  := .nextMsgSeq(true)

	,  := crypto.EncryptBindMessage(
		.rand,
		.PermKey,
		,
		,
	)
	if  != nil {
		return errors.Wrap(, "encrypt bind message")
	}

	 := &tg.AuthBindTempAuthKeyRequest{
		PermAuthKeyID:    .PermKey.IntID(),
		Nonce:            ,
		ExpiresAt:        int(),
		EncryptedMessage: ,
	}

	var  tg.BoolBox
	 := rpc.Request{
		MsgID:  ,
		SeqNo:  ,
		Input:  ,
		Output: &,
	}
	.log.Debug(, "Binding temporary auth key",
		log.Int64("temp_key_id", .Key.IntID()),
		log.Int64("perm_key_id", .PermKey.IntID()),
		log.Int64("temp_session_id", .ID),
		log.Int64("expires_at", ),
	)

	var  time.Time
	if .wire != nil {
		 = .traceRequestStart()
	}
	 = .rpc.Do(, )
	var  *badMessageError
	if  != nil && errors.As(, &) && .Code == codeIncorrectServerSalt {
		.storeSalt(.NewSalt)
		.salts.Reset()
		.traceResend(, "bad_server_salt")
		 = .rpc.Do(, )
	}
	if .wire != nil {
		.traceRequestDone(, , )
	}
	if  != nil {
		return errors.Wrap(, "invoke auth.bindTempAuthKey")
	}

	if ,  := .Bool.(*tg.BoolTrue); ! {
		return errors.New("temp auth key bind rejected")
	}
	.log.Info(, "Temporary auth key bound",
		log.Int64("temp_key_id", .Key.IntID()),
		log.Int64("perm_key_id", .PermKey.IntID()),
		log.Int64("expires_at", ),
	)
	return nil
}

// handleBindEncryptedMessageInvalid decides what to do when
// auth.bindTempAuthKey returns ENCRYPTED_MESSAGE_INVALID: retry the bind
// (nil), reconnect, or drop the permanent key (ErrPFSDropKeysRequired).
//
// The PFS docs say to drop both keys when the permanent key is older than
// 60 seconds, but that loses the authorization on a false positive. Like
// TDLib (Session::on_bind_result), the permanent key is immune when it is
// younger than 60 seconds (not yet propagated), or older than a day and was
// bound successfully within the last day. Otherwise it is checked with a
// request encrypted with it (checkPermKey) and dropped only if the server
// does not know it.
func ( *Conn) ( context.Context,  int) error {
	 := .clock.Now().Unix()
	.sessionMux.RLock()
	 := .permKeyCreatedAt
	.sessionMux.RUnlock()
	var  int64
	if .sessionState != nil {
		 = .sessionState.lastBind()
	}
	 :=  - 
	 :=  != 0 &&
		( < 60 || ( > 86400 &&  > -86400))
	if  {
		if  >= maxBindTempAuthKeyAttempts {
			.log.Warn(, "auth.bindTempAuthKey returned ENCRYPTED_MESSAGE_INVALID after retries, reconnecting without dropping the permanent key",
				log.Int("attempt", ),
				log.Int64("perm_key_age", ),
			)
			return errors.Wrap(ErrPFSReconnectRequired, "temporary key bind failed with ENCRYPTED_MESSAGE_INVALID")
		}
		.log.Warn(, "auth.bindTempAuthKey returned ENCRYPTED_MESSAGE_INVALID, retrying bind",
			log.Int("attempt", ),
			log.Int64("perm_key_age", ),
		)
		return nil
	}

	 := .permKeyCheck
	if  == nil {
		 = .checkPermKey
	}
	,  := ()
	if  != nil {
		.log.Warn(, "Permanent key check failed, reconnecting without dropping the key", log.Error())
		return errors.Wrap(ErrPFSReconnectRequired, "permanent key check failed")
	}
	if ! {
		if  >= maxBindTempAuthKeyAttempts {
			return errors.Wrap(ErrPFSReconnectRequired, "temporary key bind failed with ENCRYPTED_MESSAGE_INVALID, permanent key is valid")
		}
		.log.Warn(, "auth.bindTempAuthKey returned ENCRYPTED_MESSAGE_INVALID, permanent key is valid, retrying bind",
			log.Int("attempt", ),
		)
		return nil
	}
	.log.Warn(, "Server does not know the permanent key, dropping PFS keys",
		log.Int("attempt", ),
	)
	.dropPFSKeys()
	return errors.Wrap(ErrPFSDropKeysRequired, "permanent key is unknown to the server")
}

// checkPermKey reports whether the server does not know the permanent key:
// it sends help.getNearestDc encrypted with the permanent key (without PFS)
// on a separate connection. The server answers -404 for an unknown key, which
// makes that connection generate a new key.
func ( *Conn) ( context.Context) ( bool,  error) {
	.sessionMux.RLock()
	 := .permKey
	.sessionMux.RUnlock()
	if .Zero() {
		return true, nil
	}
	if .dialer == nil {
		return false, errors.New("no dialer")
	}
	 := New(.dialer, Options{
		DC:              .dcID,
		PublicKeys:      .rsaPublicKeys,
		Random:          .rand,
		Logger:          .log.Named("perm_key_check").Logger(),
		Clock:           .clock,
		Key:             ,
		ExchangeTimeout: .exchangeTimeout,
		DialTimeout:     .dialTimeout,
	})
	,  := context.WithTimeout(, 30*time.Second)
	defer ()
	 := .Run(, func( context.Context) error {
		var  tg.NearestDC
		 := .Invoke(, &tg.HelpGetNearestDCRequest{}, &)
		if ,  := tgerr.As();  {
			// Any RPC answer means the request was decrypted.
			return nil
		}
		return 
	})
	if .session().Key.ID != .ID {
		// -404: the probe had to generate a new key.
		return true, nil
	}
	if  != nil {
		return false, 
	}
	return false, nil
}

func ( *Conn) ( int) error {
	if  < maxBindTempAuthKeyAttempts {
		// In practice this can happen while server-side state is catching up;
		// avoid aggressive key reset and retry bind first.
		.log.Warn(context.Background(), "auth.bindTempAuthKey returned CONNECTION_NOT_INITED, retrying bind",
			log.Int("attempt", ),
		)
		return nil
	}
	// After retries, reconnect whole transport/session and run full init path.
	.log.Warn(context.Background(), "auth.bindTempAuthKey returned CONNECTION_NOT_INITED after retries, reconnecting without dropping keys",
		log.Int("attempt", ),
	)
	return errors.New("auth.bindTempAuthKey failed with CONNECTION_NOT_INITED after retries")
}

func ( *Conn) () {
	.sessionMux.Lock()
	.authKey = crypto.AuthKey{}
	.permKey = crypto.AuthKey{}
	.permKeyCreatedAt = 0
	.salt = 0
	.sessionID = 0
	.tempKeyExpiry = 0
	.sessionMux.Unlock()
}