From 79ad0fc21ef58025e630dfcc3b4a8f0646b6b794 Mon Sep 17 00:00:00 2001 From: "Andres G. Aragoneses" Date: Wed, 14 Oct 2020 20:48:43 +0200 Subject: [PATCH] Core: make MtProtoSender.GenerateSequence() thread-safe Even if you're not supposed to use multiple threads with TLSharp, it might be worth it to try to make this sequence increment in a thread-safe way. Race conditions are always bad even if you know you are not supposed to use something in a certain way... @Laituex was having a ErrCode=32 'msg_seqno too low' problem and this is the first thing we looked at (even if he swore that he was not using different threads to access the telegram network). (Backported from https://github.com/sochix/TLSharp/commit/881bdd27a5058dab088365ef95cd1d5d72ad2faa ) # Conflicts: # src/TgSharp.Core/Session.cs --- src/TgSharp.Core/Network/MtProtoSender.cs | 4 +++- src/TgSharp.Core/Session.cs | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/TgSharp.Core/Network/MtProtoSender.cs b/src/TgSharp.Core/Network/MtProtoSender.cs index b1699ce..04295a2 100644 --- a/src/TgSharp.Core/Network/MtProtoSender.cs +++ b/src/TgSharp.Core/Network/MtProtoSender.cs @@ -37,7 +37,9 @@ namespace TgSharp.Core.Network private int GenerateSequence(bool confirmed) { - return confirmed ? session.Sequence++ * 2 + 1 : session.Sequence * 2; + lock (session.Lock) { + return confirmed ? session.Sequence++ * 2 + 1 : session.Sequence * 2; + } } public async Task Send(TLMethod request, CancellationToken token = default(CancellationToken)) diff --git a/src/TgSharp.Core/Session.cs b/src/TgSharp.Core/Session.cs index 93db017..c20cdd5 100644 --- a/src/TgSharp.Core/Session.cs +++ b/src/TgSharp.Core/Session.cs @@ -52,6 +52,8 @@ namespace TgSharp.Core public class Session { + internal object Lock = new object (); + public int Sequence { get; set; } #if CI // see the same CI-wrapped assignment in .FromBytes(), but this one will become useful