Skip to content

Commit 018f535

Browse files
committed
Fix "wrong timestamp" issues when first msgId is too much in the past
1 parent 3304ba4 commit 018f535

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/Client.cs

+8-2
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ public partial class Client : IDisposable
7676
private CancellationTokenSource _cts;
7777
private int _reactorReconnects = 0;
7878
private const string ConnectionShutDown = "Could not read payload length : Connection shut down";
79+
private const long Ticks5Secs = 5 * TimeSpan.TicksPerSecond;
7980
private readonly SemaphoreSlim _parallelTransfers = new(10); // max parallel part uploads/downloads
8081
private readonly SHA256 _sha256 = SHA256.Create();
8182
private readonly SHA256 _sha256Recv = SHA256.Create();
@@ -440,7 +441,12 @@ internal IObject ReadFrame(byte[] data, int dataLen)
440441
if (_lastRecvMsgId == 0) // resync ServerTicksOffset on first message
441442
_dcSession.ServerTicksOffset = (msgId >> 32) * 10000000 - utcNow.Ticks + 621355968000000000L;
442443
var msgStamp = MsgIdToStamp(_lastRecvMsgId = msgId);
443-
444+
long deltaTicks = (msgStamp - utcNow).Ticks;
445+
if (deltaTicks is > 0)
446+
if (deltaTicks < Ticks5Secs) // resync if next message is less than 5 seconds in the future
447+
_dcSession.ServerTicksOffset += deltaTicks;
448+
else if (_dcSession.ServerTicksOffset < -Ticks5Secs && deltaTicks + _dcSession.ServerTicksOffset < 0)
449+
_dcSession.ServerTicksOffset += deltaTicks;
444450
if (serverSalt != _dcSession.Salt && serverSalt != _dcSession.OldSalt && serverSalt != _dcSession.Salts?.Values.ElementAtOrDefault(1))
445451
{
446452
Helpers.Log(3, $"{_dcSession.DcID}>Server salt has changed: {_dcSession.Salt:X} -> {serverSalt:X}");
@@ -453,7 +459,7 @@ internal IObject ReadFrame(byte[] data, int dataLen)
453459
if ((seqno & 1) != 0) lock (_msgsToAck) _msgsToAck.Add(msgId);
454460

455461
var ctorNb = reader.ReadUInt32();
456-
if (ctorNb != Layer.BadMsgCtor && (msgStamp - utcNow).Ticks / TimeSpan.TicksPerSecond is > 30 or < -300)
462+
if (ctorNb != Layer.BadMsgCtor && deltaTicks / TimeSpan.TicksPerSecond is > 30 or < -300)
457463
{ // msg_id values that belong over 30 seconds in the future or over 300 seconds in the past are to be ignored.
458464
Helpers.Log(1, $"{_dcSession.DcID}>Ignoring 0x{ctorNb:X8} because of wrong timestamp {msgStamp:u} - {utcNow:u} Δ={new TimeSpan(_dcSession.ServerTicksOffset):c}");
459465
return null;

0 commit comments

Comments
 (0)