Пример #1
0
 /// <summary>
 ///     Deserialize an object.
 /// </summary>
 /// <param name="stream">Stream for reading.</param>
 /// <returns>Deserialized object.</returns>
 public object Deserialize(Stream stream)
 {
     using (var streamer = new TLStreamer(stream))
     {
         return(Deserialize(new TLSerializationContext(this, streamer)));
     }
 }
Пример #2
0
        /// <summary>
        ///     Deserialize an object from TL serialization context.
        /// </summary>
        /// <remarks>
        ///     Constructor number for the object is automatically determined by reading the first number from the streamer,
        ///     hence object within the context streamer must be serialized as boxed type.
        /// </remarks>
        /// <param name="context">TL serialization context.</param>
        /// <returns>Deserialized object.</returns>
        /// <exception cref="TLSerializerNotFoundException">When serializer not found.</exception>
        public static object Deserialize(TLSerializationContext context)
        {
            // Here streamer's position must point to a boxed TL type.
            TLStreamer streamer = context.Streamer;

            // Read a constructor number and restore the streamer position.
            streamer.PushPosition();
            uint constructorNumber = streamer.ReadUInt32();

            //Console.WriteLine("Retrived constructor number " + constructorNumber);
            streamer.PopPosition();

            ITLSerializer serializer = context.Rig.GetSerializerByConstructorNumber(constructorNumber);



            //Console.WriteLine("Got serializer for above constructor number" + serializer.SupportedType);



            if (serializer == null)
            {
                throw new TLSerializerNotFoundException(
                          string.Format("Constructor number: 0x{0:X8} is not supported by any registered serializer.", constructorNumber));
            }

            return(serializer.Read(context, TLSerializationMode.Boxed));
        }
Пример #3
0
 /// <summary>
 ///     Deserialize an object.
 /// </summary>
 /// <param name="stream">Stream for reading.</param>
 /// <param name="objType">Type of the object.</param>
 /// <param name="modeOverride">Serialization mode override.</param>
 /// <returns>Deserialized object.</returns>
 public object Deserialize(Stream stream, Type objType, TLSerializationMode?modeOverride = null)
 {
     using (var streamer = new TLStreamer(stream))
     {
         return(Deserialize(objType, new TLSerializationContext(this, streamer), modeOverride));
     }
 }
Пример #4
0
 /// <summary>
 ///     Deserialize an object.
 /// </summary>
 /// <param name="stream">Stream for reading.</param>
 /// <returns>Deserialized object.</returns>
 public object Deserialize(Stream stream)
 {
     using (var streamer = new TLStreamer(stream, true))
     {
         return(Deserialize(streamer));
     }
 }
Пример #5
0
        /// <summary>
        ///     Serializer an object.
        /// </summary>
        /// <param name="obj">The object to be serialized.</param>
        /// <param name="streamer">TL streamer for writing.</param>
        /// <param name="modeOverride">Serialization mode override.</param>
        /// <returns>Bytes written to the stream.</returns>
        public long Serialize(object obj, TLStreamer streamer, TLSerializationMode?modeOverride = null)
        {
            long initialPosition = streamer.Position;

            Serialize(obj, new TLSerializationContext(this, streamer), modeOverride);
            return(streamer.Position - initialPosition);
        }
Пример #6
0
 /// <summary>
 ///     Serializer an object.
 /// </summary>
 /// <param name="obj">The object to be serialized.</param>
 /// <param name="stream">Stream for writing.</param>
 /// <param name="modeOverride">Serialization mode override.</param>
 /// <returns>Bytes written to the stream.</returns>
 public long Serialize(object obj, Stream stream, TLSerializationMode?modeOverride = null)
 {
     using (var streamer = new TLStreamer(stream, true))
     {
         return(Serialize(obj, streamer, modeOverride));
     }
 }
Пример #7
0
 /// <summary>
 ///     Serializer an object.
 /// </summary>
 /// <param name="obj">The object to be serialized.</param>
 /// <param name="stream">Stream for writing.</param>
 /// <param name="modeOverride">Serialization mode override.</param>
 public void Serialize(object obj, Stream stream, TLSerializationMode?modeOverride = null)
 {
     using (var streamer = new TLStreamer(stream))
     {
         Serialize(obj, new TLSerializationContext(this, streamer), modeOverride);
     }
 }
Пример #8
0
 /// <summary>
 ///     Deserialize an object.
 /// </summary>
 /// <param name="stream">Stream for reading.</param>
 /// <param name="objType">Type of the object.</param>
 /// <param name="modeOverride">Serialization mode override.</param>
 /// <returns>Deserialized object.</returns>
 public object Deserialize(Stream stream, Type objType, TLSerializationMode?modeOverride = null)
 {
     using (var streamer = new TLStreamer(stream, true))
     {
         return(Deserialize(streamer, objType, modeOverride));
     }
 }
Пример #9
0
 internal TLSyncStreamer(TLStreamer streamer)
 {
     if (streamer == null)
     {
         throw new ArgumentNullException("streamer");
     }
     _streamer = streamer;
 }
Пример #10
0
        /// <summary>
        ///     Create syncronized wrapper around the <see cref="TLStreamer" />.
        /// </summary>
        /// <param name="streamer">TL streamer.</param>
        /// <returns>Syncronized wrapper.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static TLStreamer Syncronized([NotNull] TLStreamer streamer)
        {
            if (streamer == null)
            {
                throw new ArgumentNullException("streamer");
            }

            return(new TLSyncStreamer(streamer));
        }
Пример #11
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="TcpTransportPacket" /> class.
 /// </summary>
 /// <param name="number">Sequential packet number.</param>
 /// <param name="payload">Payload bytes.</param>
 public TcpTransportPacket(int number, byte[] payload)
 {
     Number = number;
     int length = payload.Length + PacketEmbracesLength;
     _data = new byte[length];
     using (var streamer = new TLStreamer(_data))
     {
         streamer.WriteInt32(length);
         streamer.WriteInt32(Number);
         streamer.Write(payload);
         Crc32 = ComputeCrc32();
         streamer.WriteUInt32(Crc32);
     }
 }
Пример #12
0
        /// <summary>
        ///     Deserialize an object from TL serialization context.
        /// </summary>
        /// <remarks>
        ///     Constructor number for the object is automatically determined by reading the first number from the streamer,
        ///     hence object within the context streamer must be serialized as boxed type.
        /// </remarks>
        /// <param name="context">TL serialization context.</param>
        /// <returns>Deserialized object.</returns>
        /// <exception cref="TLSerializerNotFoundException">When serializer not found.</exception>
        public static object Deserialize(TLSerializationContext context)
        {
            TLStreamer streamer = context.Streamer;

            // Read a constructor number.
            uint          constructorNumber = streamer.ReadUInt32();
            ITLSerializer serializer        = context.Rig.GetSerializerByConstructorNumber(constructorNumber);

            if (serializer == null)
            {
                throw new TLSerializerNotFoundException(string.Format("Constructor number: 0x{0:X8} is not supported by any registered serializer.", constructorNumber));
            }

            // Bare because construction number has already been read.
            return(serializer.Read(context, TLSerializationMode.Bare));
        }
Пример #13
0
 /// <summary>
 ///     Deserialize an object.
 /// </summary>
 /// <typeparam name="T">Type of the object.</typeparam>
 /// <param name="streamer">TL streamer for reading.</param>
 /// <param name="modeOverride">Serialization mode override.</param>
 /// <returns>Deserialized object.</returns>
 public T Deserialize <T>(TLStreamer streamer, TLSerializationMode?modeOverride = null)
 {
     return((T)Deserialize(streamer, typeof(T), modeOverride));
 }
Пример #14
0
 /// <summary>
 ///     Deserialize an object.
 /// </summary>
 /// <param name="streamer">TL streamer for reading.</param>
 /// <returns>Deserialized object.</returns>
 public object Deserialize(TLStreamer streamer)
 {
     return(Deserialize(new TLSerializationContext(this, streamer)));
 }
Пример #15
0
        public IMessage DecodeEncryptedMessage(byte[] messageBytes, byte[] authKey, Sender sender, out UInt64 salt, out UInt64 sessionId)
        {
            Argument.IsNotNull(() => authKey);
            Argument.IsNotNull(() => messageBytes);

            ulong providedAuthKeyId = ComputeAuthKeyId(authKey);

            var encryptedData = new byte[messageBytes.Length - EncryptedOuterHeaderLength];

            Int128 msgKey;

            using (var streamer = new TLStreamer(messageBytes))
            {
                // Reading header.
                ulong authKeyId = streamer.ReadUInt64();
                if (authKeyId != providedAuthKeyId)
                {
                    throw new InvalidAuthKey(string.Format("Message encrypted with auth key with id={0}, but auth key provided for decryption with id={1}.", authKeyId,
                        providedAuthKeyId));
                }
                msgKey = streamer.ReadInt128();

                // Reading encrypted data.
                streamer.Read(encryptedData, 0, encryptedData.Length);
            }

            // Decrypting.
            byte[] aesKey, aesIV;
            ComputeAesKeyAndIV(authKey, msgKey, out aesKey, out aesIV, sender);
            byte[] innerDataWithPadding = _encryptionServices.Aes256IgeDecrypt(encryptedData, aesKey, aesIV);

            Int32 msgDataLength;
            UInt64 msgId;
            UInt32 seqno;
            Object body;

            using (var streamer = new TLStreamer(innerDataWithPadding))
            {
                salt = streamer.ReadUInt64();
                sessionId = streamer.ReadUInt64();
                msgId = streamer.ReadUInt64();
                seqno = streamer.ReadUInt32();
                msgDataLength = streamer.ReadInt32();
                body = _tlRig.Deserialize(streamer);
            }

            int innerDataLength = EncryptedInnerHeaderLength + msgDataLength;

            // When an encrypted message is received, it must be checked that
            // msg_key is in fact equal to the 128 lower-order bits
            // of the SHA1 hash of the previously encrypted portion.
            Int128 expectedMsgKey = ComputeMsgKey(new ArraySegment<byte>(innerDataWithPadding, 0, innerDataLength));
            if (msgKey != expectedMsgKey)
            {
                throw new InvalidMessageException(string.Format("Expected message key to be {0}, but actual is {1}.", expectedMsgKey, msgKey));
            }

            return new Message(msgId, seqno, body);
        }
Пример #16
0
        private ReqDHParamsArgs CreateReqDhParamsArgs(ResPQ resPQ, out PQInnerData pqInnerData)
        {
            Int256 pq = resPQ.Pq.ToInt256(asLittleEndian: false);
            Int256 p, q;
            pq.GetPrimeMultipliers(out p, out q);

            Int256 newNonce = _nonceGenerator.GetNonce(32).ToInt256();
            pqInnerData = new PQInnerData
            {
                Pq = resPQ.Pq,
                P = p.ToBytes(false, true),
                Q = q.ToBytes(false, true),
                Nonce = resPQ.Nonce,
                ServerNonce = resPQ.ServerNonce,
                NewNonce = newNonce
            };

            byte[] data = _tlRig.Serialize(pqInnerData);
            byte[] dataHash = ComputeSHA1(data);

            Debug.Assert((dataHash.Length + data.Length) <= 255);

            // data_with_hash := SHA1(data) + data + (any random bytes); such that the length equal 255 bytes;
            var dataWithHash = new byte[255];
            using (var streamer = new TLStreamer(dataWithHash))
            {
                streamer.Write(dataHash);
                streamer.Write(data);
                streamer.WriteRandomDataTillEnd();
            }

            PublicKey publicKey = _keyChain.GetFirst(resPQ.ServerPublicKeyFingerprints);
            if (publicKey == null)
            {
                throw new PublicKeyNotFoundException(resPQ.ServerPublicKeyFingerprints);
            }

            byte[] encryptedData = _encryptionServices.RSAEncrypt(dataWithHash, publicKey);

            var reqDhParamsArgs = new ReqDHParamsArgs
            {
                Nonce = pqInnerData.Nonce,
                ServerNonce = pqInnerData.ServerNonce,
                P = pqInnerData.P,
                Q = pqInnerData.Q,
                PublicKeyFingerprint = publicKey.Fingerprint,
                EncryptedData = encryptedData
            };

            return reqDhParamsArgs;
        }
Пример #17
0
        private void InitAndCheckConsistency()
        {
            int length = _data.Length;
            using (var streamer = new TLStreamer(_data))
            {
                int expectedLength = streamer.ReadInt32();
                if (length != expectedLength)
                {
                    throw new TransportException(string.Format("Invalid packet length. Expected: {0}, actual: {1}.", expectedLength, length));
                }
                Number = streamer.ReadInt32();
                streamer.Seek(-4, SeekOrigin.End);
                Crc32 = streamer.ReadUInt32();
            }

            uint actualCrc32 = ComputeCrc32();
            if (Crc32 != actualCrc32)
            {
                throw new TransportException(string.Format("Invalid packet CRC32. Expected: {0}, actual: {1}.", actualCrc32, Crc32));
            }
        }
Пример #18
0
        public IMessage DecodePlainMessage(byte[] messageBytes)
        {
            using (var streamer = new TLStreamer(messageBytes))
            {
                long authKey = streamer.ReadInt64();
                if (authKey != 0)
                {
                    throw new InvalidMessageException("Auth key must always be zero for a plain message.");
                }

                ulong msgId = streamer.ReadUInt64();
                int bodyLength = streamer.ReadInt32();
                if (bodyLength > streamer.BytesTillEnd)
                {
                    throw new InvalidMessageException("Wrong message body length.");
                }
                object body = _tlRig.Deserialize(streamer);
                return new Message(msgId, 0, body);
            }
        }
Пример #19
0
        public byte[] EncodeEncryptedMessage(IMessage message, byte[] authKey, ulong salt, ulong sessionId, Sender sender)
        {
            Argument.IsNotNull(() => authKey);
            Argument.IsNotNull(() => message);

            ulong authKeyId = ComputeAuthKeyId(authKey);
            byte[] serBody = _tlRig.Serialize(message.Body, TLSerializationMode.Boxed);

            int serBodyLength = serBody.Length;
            int innerDataLength = EncryptedInnerHeaderLength + serBodyLength;
            int mod = innerDataLength%Alignment;
            int paddingLength = mod > 0 ? Alignment - mod : 0;
            _randomGenerator.FillWithRandom(_alignmentBuffer);
            int innerDataWithPaddingLength = innerDataLength + paddingLength;

            int length = EncryptedOuterHeaderLength + innerDataWithPaddingLength;

            // Writing inner data.
            var innerDataWithPadding = new byte[innerDataWithPaddingLength];
            using (var streamer = new TLStreamer(innerDataWithPadding))
            {
                streamer.WriteUInt64(salt);
                streamer.WriteUInt64(sessionId);
                streamer.WriteUInt64(message.MsgId);
                streamer.WriteUInt32(message.Seqno);
                streamer.WriteInt32(serBodyLength);
                streamer.Write(serBody);
                streamer.Write(_alignmentBuffer, 0, paddingLength);
            }

            Int128 msgKey = ComputeMsgKey(new ArraySegment<byte>(innerDataWithPadding, 0, innerDataLength));

            // Encrypting.
            byte[] aesKey, aesIV;
            ComputeAesKeyAndIV(authKey, msgKey, out aesKey, out aesIV, sender);
            byte[] encryptedData = _encryptionServices.Aes256IgeEncrypt(innerDataWithPadding, aesKey, aesIV);

            Debug.Assert(encryptedData.Length == innerDataWithPaddingLength, "Wrong encrypted data length.");

            var messageBytes = new byte[length];
            using (var streamer = new TLStreamer(messageBytes))
            {
                // Writing header.
                streamer.WriteUInt64(authKeyId);
                streamer.WriteInt128(msgKey);

                // Writing encrypted data.
                streamer.Write(encryptedData, 0, innerDataWithPaddingLength);
            }
            return messageBytes;
        }
Пример #20
0
 private Int128 ComputeNewNonceHash(Int256 newNonce, byte num, byte[] authKeyAuxHash)
 {
     var arr = new byte[33 + authKeyAuxHash.Length];
     using (var streamer = new TLStreamer(arr))
     {
         streamer.WriteInt256(newNonce);
         streamer.WriteByte(num);
         streamer.Write(authKeyAuxHash);
     }
     byte[] hash = ComputeSHA1(arr);
     Int128 result = hash.ToInt128(HashLength - 16);
     return result;
 }
Пример #21
0
        private ServerDHInnerData DecryptServerDHInnerData(byte[] encryptedAnswer, byte[] tmpAesKey, byte[] tmpAesIV)
        {
            /* encrypted_answer := AES256_ige_encrypt (answer_with_hash, tmp_aes_key, tmp_aes_iv);
             * here, tmp_aes_key is a 256-bit key, and tmp_aes_iv is a 256-bit initialization vector.
             * The same as in all the other instances that use AES encryption,
             * the encrypted data is padded with random bytes to a length divisible by 16 immediately prior to encryption.
             */

            // Decrypting.
            byte[] answerWithHash = _encryptionServices.Aes256IgeDecrypt(encryptedAnswer, tmpAesKey, tmpAesIV);
            if ((answerWithHash.Length%16) != 0)
            {
                throw new InvalidResponseException("Decrypted ServerDHInnerData with hash has invalid length.");
            }

            var answerHash = new byte[HashLength];
            ServerDHInnerData serverDHInnerData;
            using (var streamer = new TLStreamer(answerWithHash))
            {
                streamer.Read(answerHash, 0, answerHash.Length);
                serverDHInnerData = _tlRig.Deserialize<ServerDHInnerData>(streamer);
            }

            // Checking the hash.
            byte[] serverDHInnerDataBytes = _tlRig.Serialize(serverDHInnerData);
            byte[] serverDHInnerDataBytesHash = ComputeSHA1(serverDHInnerDataBytes);
            if (!serverDHInnerDataBytesHash.SequenceEqual(answerHash))
            {
                throw new InvalidResponseException("Decrypted ServerDHInnerData hash is invalid.");
            }

            return serverDHInnerData;
        }
Пример #22
0
 /// <summary>
 ///     Deserialize an object.
 /// </summary>
 /// <param name="streamer">TL streamer for reading.</param>
 /// <param name="objType">Type of the object.</param>
 /// <param name="modeOverride">Serialization mode override.</param>
 /// <returns>Deserialized object.</returns>
 public object Deserialize(TLStreamer streamer, Type objType, TLSerializationMode?modeOverride = null)
 {
     return(Deserialize(objType, new TLSerializationContext(this, streamer), modeOverride));
 }
Пример #23
0
        public byte[] EncodePlainMessage(IMessage message)
        {
            byte[] serBody = _tlRig.Serialize(message.Body, TLSerializationMode.Boxed);

            int length = PlainHeaderLength + serBody.Length;
            var messageBytes = new byte[length];

            using (var streamer = new TLStreamer(messageBytes))
            {
                // Writing header.
                streamer.WriteInt64(0); // Plain unencrypted message must always have zero auth key id.
                streamer.WriteUInt64(message.MsgId); // MsgId.
                streamer.WriteInt32(serBody.Length); // Length.

                // Writing data.
                streamer.Write(serBody);
            }

            return messageBytes;
        }
Пример #24
0
        private async Task ProcessReceivedDataAsync(ArraySegment<byte> buffer)
        {
            try
            {
                int bytesRead = 0;
                while (bytesRead < buffer.Count)
                {
                    int startIndex = buffer.Offset + bytesRead;
                    int bytesToRead = buffer.Count - bytesRead;

                    if (_nextPacketBytesCountLeft == 0)
                    {
                        int tempLengthBytesToRead = PacketLengthBytesCount - _tempLengthBufferFill;
                        tempLengthBytesToRead = (bytesToRead < tempLengthBytesToRead) ? bytesToRead : tempLengthBytesToRead;
                        Buffer.BlockCopy(buffer.Array, startIndex, _tempLengthBuffer, _tempLengthBufferFill, tempLengthBytesToRead);

                        _tempLengthBufferFill += tempLengthBytesToRead;
                        if (_tempLengthBufferFill < PacketLengthBytesCount)
                        {
                            break;
                        }

                        startIndex += tempLengthBytesToRead;
                        bytesToRead -= tempLengthBytesToRead;

                        _tempLengthBufferFill = 0;
                        _nextPacketBytesCountLeft = _tempLengthBuffer.ToInt32();

                        if (_nextPacketDataBuffer == null || _nextPacketDataBuffer.Length < _nextPacketBytesCountLeft || _nextPacketStreamer == null)
                        {
                            _nextPacketDataBuffer = new byte[_nextPacketBytesCountLeft];
                            _nextPacketStreamer = new TLStreamer(_nextPacketDataBuffer);
                        }

                        // Writing packet length.
                        _nextPacketStreamer.Write(_tempLengthBuffer);
                        _nextPacketBytesCountLeft -= PacketLengthBytesCount;
                        bytesRead += PacketLengthBytesCount;
                    }

                    bytesToRead = bytesToRead > _nextPacketBytesCountLeft ? _nextPacketBytesCountLeft : bytesToRead;

                    _nextPacketStreamer.Write(buffer.Array, startIndex, bytesToRead);

                    bytesRead += bytesToRead;
                    _nextPacketBytesCountLeft -= bytesToRead;

                    if (_nextPacketBytesCountLeft > 0)
                    {
                        break;
                    }

                    var packet = new TcpTransportPacket(_nextPacketDataBuffer, 0, (int) _nextPacketStreamer.Position);

                    await ProcessReceivedPacket(packet);

                    _nextPacketBytesCountLeft = 0;
                    _nextPacketStreamer.Position = 0;
                }
            }
            catch (Exception)
            {
                if (_nextPacketStreamer != null)
                {
                    _nextPacketStreamer.Dispose();
                    _nextPacketStreamer = null;
                }
                _nextPacketDataBuffer = null;
                _nextPacketBytesCountLeft = 0;

                throw;
            }
        }
Пример #25
0
 private byte[] PrependHashAndAlign(byte[] data, int alignment)
 {
     int dataLength = data.Length;
     byte[] dataHash = ComputeSHA1(data);
     int length = HashLength + dataLength;
     int mod = length%alignment;
     length += mod > 0 ? alignment - mod : 0;
     var dataWithHash = new byte[length];
     using (var streamer = new TLStreamer(dataWithHash))
     {
         streamer.Write(dataHash);
         streamer.Write(data);
         streamer.WriteRandomDataTillEnd();
     }
     return dataWithHash;
 }
Пример #26
0
        public async void DoCommand(string[] args)
        {
            var command = args[0].ToLower();

            switch (command)
            {
				case "decrypt":
				{
					try
					{
						var bytes = Convert.FromBase64String("+MW7Btpz31b0gt9WN5d5vAEAAAAVxLUcCwAAAMzG2AUAAAAAAQAAAA4xNDkuMTU0LjE3NS41MAC7AQAAzMbYBQEAAAABAAAAJzIwMDE6MGIyODpmMjNkOmYwMDE6MDAwMDowMDAwOjAwMDA6MDAwYbsBAADMxtgFAAAAAAIAAAAOMTQ5LjE1NC4xNjcuNTEAuwEAAMzG2AUBAAAAAgAAACcyMDAxOjA2N2M6MDRlODpmMDAyOjAwMDA6MDAwMDowMDAwOjAwMGG7AQAAzMbYBQAAAAADAAAADzE0OS4xNTQuMTc1LjEwMLsBAADMxtgFAQAAAAMAAAAnMjAwMTowYjI4OmYyM2Q6ZjAwMzowMDAwOjAwMDA6MDAwMDowMDBhuwEAAMzG2AUAAAAABAAAAA4xNDkuMTU0LjE2Ny45MQC7AQAAzMbYBQEAAAAEAAAAJzIwMDE6MDY3YzowNGU4OmYwMDQ6MDAwMDowMDAwOjAwMDA6MDAwYbsBAADMxtgFAgAAAAQAAAAPMTQ5LjE1NC4xNjUuMTIwuwEAAMzG2AUAAAAABQAAAA05MS4xMDguNTYuMTgwAAC7AQAAzMbYBQEAAAAFAAAAJzIwMDE6MGIyODpmMjNmOmYwMDU6MDAwMDowMDAwOjAwMDA6MDAwYbsBAADIAAAA6AMAAGQAAADA1AEAiBMAADB1AADgkwQAMHUAANwFAAAKAAAAYOoAAAIAAADIAAAAFcS1HAAAAAA=");
						TLRig.Default.PrepareSerializersForAllTLObjectsInAssembly(typeof (IMTProtoAsyncMethods).Assembly);
						using (var streamer = new TLStreamer(bytes))
						{
							var newResult = TLRig.Default.Deserialize(streamer);
							int hi = 5;
						}
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex);
					}
				}
				break;


                case "setup":
                    {
                        DebugPrint("Fetching nearest DC...");
                        var telegramSettings = new TelegramSettings();
                        var authInfo = await FetchNewAuthentication(DefaultTransportConfig);
                        using (var client = new TelegramClient(DefaultTransportConfig, 
                            new ConnectionConfig(authInfo.AuthKey, authInfo.Salt), AppInfo))
                        {
                            await client.Connect();
                            var nearestDcId = (NearestDc)await(client.Methods.HelpGetNearestDcAsync(new HelpGetNearestDcArgs{}));
                            var config = (Config)await(client.Methods.HelpGetConfigAsync(new HelpGetConfigArgs{ }));
                            var dcOption = config.DcOptions.OfType<DcOption>().FirstOrDefault(x => x.Id == nearestDcId.NearestDcProperty);
                            telegramSettings.NearestDcId = nearestDcId.NearestDcProperty;
                            telegramSettings.NearestDcIp = dcOption.IpAddress;
                            telegramSettings.NearestDcPort = (int)dcOption.Port;
                        }
                        DebugPrint("Generating authentication on nearest DC...");
                        var authInfo2 = await FetchNewAuthentication(
                            new TcpClientTransportConfig(telegramSettings.NearestDcIp, telegramSettings.NearestDcPort));
                        telegramSettings.AuthKey = authInfo2.AuthKey;
                        telegramSettings.Salt = authInfo2.Salt;
                        SettingsManager.Save(this, telegramSettings);
                        DebugPrint("Great! Ready for the service to start.");
                    }
                    break;
                case "sendcode":
                    {
                        var number = args[1];
                        var transportConfig = 
                            new TcpClientTransportConfig(_settings.NearestDcIp, _settings.NearestDcPort);
                        using (var client = new TelegramClient(transportConfig, 
                            new ConnectionConfig(_settings.AuthKey, _settings.Salt), AppInfo))
                        {
                            await client.Connect();
                            var result = await client.Methods.AuthSendCodeAsync(new AuthSendCodeArgs
                            {
                                PhoneNumber = number,
                                ApiId = AppInfo.ApiId,
                                ApiHash = "f8f2562579817ddcec76a8aae4cd86f6",
                            });
                            DebugPrint(ObjectDumper.Dump(result));
                        }
                    }
                    break;
                case "signin":
                    {
                        var number = args[1];
                        var hash = args[2];
                        var code = args[3];
                        var transportConfig = 
                            new TcpClientTransportConfig(_settings.NearestDcIp, _settings.NearestDcPort);
                        using (var client = new TelegramClient(transportConfig, 
                            new ConnectionConfig(_settings.AuthKey, _settings.Salt), AppInfo))
                        {
                            await client.Connect();
                            var result = (AuthAuthorization)await client.Methods.AuthSignInAsync(new AuthSignInArgs
                            {
                                PhoneNumber = number,
                                PhoneCodeHash = hash,
                                PhoneCode = code,
                            });
                            DebugPrint(ObjectDumper.Dump(result));
                        }
                    }
                    break;
                case "signup":
                    {
                        var number = args[1];
                        var hash = args[2];
                        var code = args[3];
                        var firstName = args[4];
                        var lastName = args[5];
                        var transportConfig = 
                            new TcpClientTransportConfig(_settings.NearestDcIp, _settings.NearestDcPort);
                        using (var client = new TelegramClient(transportConfig, 
                            new ConnectionConfig(_settings.AuthKey, _settings.Salt), AppInfo))
                        {
                            await client.Connect();
                            var result = (AuthAuthorization)await client.Methods.AuthSignUpAsync(new AuthSignUpArgs
                            {
                                PhoneNumber = number,
                                PhoneCodeHash = hash,
                                PhoneCode = code,
                                FirstName = firstName,
                                LastName = lastName,
                            });
                            DebugPrint(ObjectDumper.Dump(result));
                        }
                    }
                    break;
                case "getcontacts":
                    {
                        var result = await _fullClient.Methods.ContactsGetContactsAsync(new ContactsGetContactsArgs
                        {
                            Hash = string.Empty
                        });
                        DebugPrint(ObjectDumper.Dump(result));
                    }
                    break;
//                case "sendhello":
//                    {
//                        var contacts = (ContactsContacts)await _fullClient.Methods.ContactsGetContactsAsync(new ContactsGetContactsArgs
//                        {
//                            Hash = string.Empty
//                        });
//                        var counter = 0;
//                        Console.WriteLine("Pick a contact:");
//                        foreach (var icontact in contacts.Users)
//                        {
//                            var contact = icontact as UserContact;
//                            if (contact == null)
//                                continue;
//                            Console.WriteLine(counter++ + ") " + contact.FirstName + " " + contact.LastName);
//                        }
//                        var choice = int.Parse(Console.ReadLine());
//                        var chosenContact = (UserContact)contacts.Users[choice];
//                        var result = await _fullClient.Methods.MessagesSendMessageAsync(new MessagesSendMessageArgs
//                        {
//                            Peer = new InputPeerContact
//                            {
//                                UserId = chosenContact.Id,
//                            },
//                            Message = "Hello from Disa!",
//                            RandomId = (ulong)Time.GetNowUnixTimestamp(),
//                        });
//                        Console.WriteLine(ObjectDumper.Dump(result));
//                    }
//                    break;
            }

        }
Пример #27
0
 internal TLSyncStreamer(TLStreamer streamer)
 {
     if (streamer == null)
     {
         throw new ArgumentNullException("streamer");
     }
     _streamer = streamer;
 }
Пример #28
0
        protected virtual void Dispose(bool isDisposing)
        {
            if (_isDisposed)
            {
                return;
            }
            _isDisposed = true;

            if (!isDisposing)
            {
                return;
            }

            if (_connectionCancellationTokenSource != null)
            {
                _connectionCancellationTokenSource.Cancel();
                _connectionCancellationTokenSource = null;
            }
            if (_receiverTask != null)
            {
                if (!_receiverTask.IsCompleted)
                {
                    _receiverTask.Wait(1000);
                }
                if (_receiverTask.IsCompleted)
                {
                    _receiverTask.Dispose();
                }
                else
                {
                    Log.Warning("Receiver task did not completed on transport disposing.");
                }
                _receiverTask = null;
            }
            if (_nextPacketStreamer != null)
            {
                _nextPacketStreamer.Dispose();
                _nextPacketStreamer = null;
            }
            if (_in != null)
            {
                _in.OnCompleted();
                _in.Dispose();
                _in = null;
            }
            if (_socket != null)
            {
                try
                {
                    _socket.Shutdown(SocketShutdown.Both);
                    _socket.Disconnect(false);
                    _socket.Close();
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
                finally
                {
                    _socket = null;
                }
            }
        }
Пример #29
0
 public void Dispose()
 {
     if (_nonceStream != null)
     {
         _nonceStream.Dispose();
         _nonceStream = null;
     }
 }