package mtproto

import (
	
	
	
	
	

	
	

	
	
	
	
)

// https://core.telegram.org/mtproto/description#message-identifier-msg-id
// A message is rejected over 300 seconds after it is created or 30 seconds
// before it is created (this is needed to protect from replay attacks).
const (
	maxPast   = time.Second * 300
	maxFuture = time.Second * 30
)

// errRejected is returned on invalid message that should not be processed.
var errRejected = errors.New("message rejected")

func ( time.Time,  int64) error {
	if  := checkMessageType();  != nil {
		return 
	}

	 := proto.MessageID().Time()
	if .Before() && .Sub() > maxPast {
		return errors.Wrap(errRejected, "created too far in past")
	}
	if .Sub() > maxFuture {
		return errors.Wrap(errRejected, "created too far in future")
	}

	return nil
}

// checkMessageType checks that message is from server.
func ( int64) error {
	switch  := proto.MessageID(); .Type() {
	case proto.MessageFromServer, proto.MessageServerResponse:
		return nil
	default:
		return errors.Wrapf(errRejected, "unexpected type %s", .Type())
	}
}

// serverNow returns the current server time, or local time if the connection
// has no ServerTime.
func ( *Conn) () time.Time {
	if .serverTime == nil {
		return .clock.Now()
	}
	return .serverTime.Now()
}

// observeServerTime updates the server time offset from the time encoded in
// a received msg_id.
func ( *Conn) ( int64) {
	if .serverTime == nil {
		return
	}
	if .serverTime.observe(proto.MessageID().Time()) {
		.log.Debug(context.Background(), "Server time offset updated",
			log.Duration("offset", .serverTime.Offset()),
		)
	}
}

func ( *Conn) ( *bin.Buffer) (*crypto.EncryptedMessageData, error) {
	 := .session()
	,  := .cipher.DecryptFromBuffer(.Key, )
	if  != nil {
		.traceEvent(WireEvent{Type: WireDecryptFailed, Err: })
		return nil, errors.Wrap(, "decrypt")
	}
	if .wire != nil {
		.traceMessage(WireIn, .Key, .Salt, .SessionID, .MessageID, .SeqNo, .Data())
	}

	// Validating message. This protects from replay attacks.
	if .SessionID != .ID {
		.traceRejected(.MessageID, "bad_session")
		return nil, errors.Wrapf(errRejected, "invalid session (got %d, expected %d)", .SessionID, .ID)
	}
	// Like TDLib (AuthData::check_packet), update the server time offset from
	// the msg_id first and only then check its time window, so that a skewed
	// local clock doesn't make every message, including the server's
	// bad_msg_notification about our msg_ids, look too old or too new.
	if  := checkMessageType(.MessageID);  != nil {
		.traceRejected(.MessageID, "bad_msg_id")
		return nil, errors.Wrapf(, "bad message id %d", .MessageID)
	}
	.observeServerTime(.MessageID)
	if  := checkMessageID(.serverNow(), .MessageID);  != nil {
		.traceRejected(.MessageID, "bad_msg_id")
		return nil, errors.Wrapf(, "bad message id %d", .MessageID)
	}
	if !.messageIDBuf.Consume(.MessageID) {
		.traceRejected(.MessageID, "bad_msg_id")
		return nil, errors.Wrapf(errRejected, "duplicate or too low message id %d", .MessageID)
	}

	return , nil
}

func ( *Conn) ( context.Context,  *bin.Buffer) error {
	,  := .decryptMessage()
	if errors.Is(, errRejected) {
		.log.Warn(, "Ignoring rejected message", log.Error())
		return nil
	}
	if  != nil {
		return errors.Wrap(, "consume message")
	}

	if  := .handleMessage(, .MessageID, &bin.Buffer{Buf: .Data()});  != nil {
		// Probably we can return here, but this will shutdown whole
		// connection which can be unexpected.
		.log.Warn(, "Error while handling message", log.Error())
		// Sending acknowledge even on error. Client should restore
		// from missing updates via explicit pts check and getDiff call.
	}

	if needAck(int(.SeqNo)) {
		if  := .enqueueAck(, .MessageID);  != nil {
			return 
		}
	}

	return nil
}

// needAck reports whether a message with the given seqno is content-related
// and must be acknowledged.
//
// https://core.telegram.org/mtproto/description#message-sequence-number-msg-seqno
func ( int) bool {
	return &0x01 != 0
}

// enqueueAck enqueues message id for acknowledgement by ackLoop.
func ( *Conn) ( context.Context,  int64) error {
	// This can block if the ack loop is stuck (e.g. writing acks over a
	// half-open connection), which would stall message consumption. Trace
	// slow enqueues to surface it.
	 := .clock.Now()
	select {
	case <-.Done():
		return .Err()
	case .ackSendChan <- :
		if  := .clock.Now().Sub();  > slowWriteThreshold {
			.log.Warn(, "Slow ack enqueue (ack loop may be stalled)",
				log.Int64("msg_id", ),
				log.Duration("waited", ),
			)
		}
		return nil
	}
}

func ( *Conn) ( error) bool {
	// Checking for read timeout.
	var  *net.OpError
	if errors.As(, &) && .Timeout() {
		// We call SetReadDeadline so such error is expected.
		.log.Debug(context.Background(), "No updates")
		return true
	}
	return false
}

func ( *Conn) ( context.Context) error {
	if .session().ID == 0 {
		// The 404 error can also be caused by zero session id.
		// See https://github.com/gotd/td/issues/107
		//
		// We should recover from this in createAuthKey, but in general
		// this code branch should be unreachable.
		.log.Warn(, "BUG: zero session id found")
	}
	if .pfs {
		// In PFS mode 404 most likely means lost temporary key, so caller should
		// recreate transport and re-bind, not regenerate permanent key in-place.
		return errors.Wrap(ErrPFSReconnectRequired, "temporary auth key not found in pfs mode")
	}
	// The server dropped the key: e.g. the session was terminated or the
	// account deleted or banned. A new key is not authorized, so requests
	// that need authorization fail with AUTH_KEY_UNREGISTERED, which the
	// client reports as lost authorization.
	.log.Warn(, "Re-generating keys (server not found key that we provided), "+
		"authorization of this key is lost if it had one")
	if  := .createAuthKey();  != nil {
		return errors.Wrap(, "unable to create auth key")
	}
	.log.Info(, "Re-created auth keys")
	if .wire != nil {
		.traceKey(WireKeySet, .session().Key, false)
	}
	// Pending requests were notified by resetSession and are sent again
	// in the new session.
	return nil
}

func ( *Conn) ( context.Context) ( error) {
	 := .log.Named("read")
	.Debug(, "Read loop started")
	defer func() {
		 := 
		if  != nil {
			 = .With(log.NamedError("reason", ))
		}
		.Debug(, "Read loop done")
	}()

	var (
		// Last error encountered by consumeMessage.
		 atomic.Value
		// To wait all spawned goroutines
		 sync.WaitGroup
	)
	defer .Wait()

	for {
		// We've tried multiple ways to reduce allocations via reusing buffer,
		// but naive implementation induces high idle memory waste.
		//
		// Proper optimization will probably require total rework of bin.Buffer
		// with sharded (by payload size?) pool that can be used after message
		// size read (after readLen).
		//
		// Such optimization can introduce additional complexity overhead and
		// is probably not worth it.
		 := &bin.Buffer{}

		// Halting if consumeMessage encountered error.
		// Should be something critical with crypto.
		if ,  := .Load().(error);  &&  != nil {
			return errors.Wrap(, "halting")
		}

		if  := .conn.Recv(, );  != nil {
			select {
			case <-.Done():
				return .Err()
			default:
				if .noUpdates() {
					continue
				}
			}

			var  *codec.ProtocolErr
			if errors.As(, &) && .Code == codec.CodeAuthKeyNotFound {
				if  := .handleAuthKeyNotFound();  != nil {
					return errors.Wrap(, "auth key not found")
				}

				continue
			}

			select {
			case <-.Done():
				return errors.Wrap(.Err(), "read loop")
			default:
				return errors.Wrap(, "read")
			}
		}

		.Add(1)
		go func() {
			defer .Done()

			// Spawning goroutine per incoming message to utilize as much
			// resources as possible while keeping idle utilization low.
			//
			// The "worker" model was replaced by this due to idle utilization
			// overhead, especially on multi-CPU systems with multiple running
			// clients.
			if  := .consumeMessage(, );  != nil {
				.Error(, "Failed to process message", log.Error())
				.Store(errors.Wrap(, "consume"))
			}
		}()
	}
}