Ejemplo n.º 1
0
        private void FinalizeHandshake(HandshakeFrame handshakeFrame)
        {
            _extensionService.ServerConfirm(handshakeFrame);
            _connection.SetHandshakeCompleted();
            _state = ServerState.Ready;
            var extensionId = _extensionService.FindFirstExtensionId("batch-ack", "ack");

            if (extensionId != 0)
            {
                var name          = _extensionService.FindFirstExtensionNamed("batch-ack", "ack");
                var extProperties = handshakeFrame.GetExtension(name);
                var ackExtension  = (IAckExtension)_extensionService.Get(extensionId);
                _ackReceiver = ackExtension.CreateAckReceiver(_connection, extensionId, DeliverMessage, extProperties);
                _ackSender   = ackExtension.CreateAckSender(_connection, extensionId, extProperties);
            }


            extensionId = _extensionService.FindFirstExtensionId("json", "protobuf", "xml");
            if (extensionId != 0)
            {
                var payloadExtension = (IPayloadExtension)_extensionService.Get(extensionId);
                _payloadSerializer = payloadExtension.CreatePayloadSerializer();
            }


            if (HandshakeCompleted != null)
            {
                HandshakeCompleted();
            }
        }
Ejemplo n.º 2
0
        public void got_required_but_no_optional()
        {
            var buffer = new byte[]
            {
                3,                                          //major
                1,                                          //minor
                0,                                          //flags
                4,                                          //id length
                (byte)'d', (byte)'a', (byte)'y', (byte)'1', //id
                0, 4,                                       //required len (network byte order)
                (byte)'j', (byte)'s', (byte)'o', (byte)'n', //required,
                0, 0                                        //optional length
            };
            var offset = 0;
            var count  = buffer.Length;

            var sut    = new HandshakeFrame();
            var actual = sut.Read(buffer, ref offset, ref count);

            actual.Should().Be(true);
            sut.Flags.Should().Be(0);
            sut.Identity.Should().Be("day1");
            sut.RequiredExtensions[0].Name.Should().Be("json");
            sut.OptionalExtensions.Should().BeEmpty();
        }
Ejemplo n.º 3
0
        public void got_only_major_in_first_send()
        {
            var buffer = new byte[]
            {
                3,                                          //major
                1,                                          //minor
                0,                                          //flags
                4,                                          //id length
                (byte)'d', (byte)'a', (byte)'y', (byte)'1', //id
                0, 4,                                       //optional len (network byte order)
                (byte)'j', (byte)'s', (byte)'o', (byte)'1', //optional,
                0, 4,                                       //optional len (network byte order)
                (byte)'j', (byte)'s', (byte)'o', (byte)'n', //optional,
            };
            var offset = 0;
            var count  = 1;

            var sut     = new HandshakeFrame();
            var actual1 = sut.Read(buffer, ref offset, ref count);

            count = buffer.Length - 1;
            var actual2 = sut.Read(buffer, ref offset, ref count);

            actual1.Should().Be(false);
            actual2.Should().Be(true);
            sut.OptionalExtensions[0].Name.Should().Be("json");
        }
Ejemplo n.º 4
0
        public void got_half_optional_text_in_first_send()
        {
            int breakPoint = 17;
            var buffer     = new byte[]
            {
                3,                                          //major
                1,                                          //minor
                0,                                          //flags
                4,                                          //id length
                (byte)'d', (byte)'a', (byte)'y', (byte)'1', //id
                0, 4,                                       //optional len (network byte order)
                (byte)'j', (byte)'s', (byte)'o', (byte)'1', //optional,
                0, 4,                                       //optional len (network byte order)
                (byte)'j', (byte)'s', (byte)'o', (byte)'n', //optional,
            };
            var offset = 0;
            var count1 = breakPoint;
            var count2 = buffer.Length - breakPoint;

            var sut = new HandshakeFrame();

            sut.Read(buffer, ref offset, ref count1);
            sut.Read(buffer, ref breakPoint, ref count2);

            sut.OptionalExtensions[0].Name.Should().Be("json");
        }
Ejemplo n.º 5
0
        public void frame_Should_be_able_to_parse_multiple_incoming_buffers_if_reseted_in_between()
        {
            var bufferManager = new BufferManager(8192, 1);
            var context       = new WriterContext(bufferManager);
            var buffer        = bufferManager.Dequeue();

            bufferManager.Enqueue(buffer);
            var sut = new HandshakeFrame();

            sut.Identity           = "Client";
            sut.OptionalExtensions = new[] { new HandshakeExtension("json"), new HandshakeExtension("ack") };
            sut.RequiredExtensions = new[] { new HandshakeExtension("dotnet") };
            sut.VersionMajor       = 1;
            sut.Write(context);
            sut.ResetWrite(context);

            var offset = buffer.Offset;
            var len    = context.GetPackets()[0].Count;

            sut.Read(buffer.Array, ref offset, ref len);
            sut.ResetRead();
            offset = buffer.Offset;
            len    = context.GetPackets()[0].Count;
            sut.Read(buffer.Array, ref offset, ref len);

            len.Should().Be(0);
        }
Ejemplo n.º 6
0
        public void frame_with_extension_properties_can_be_codec()
        {
            var bufferManager = new BufferManager(8192, 1);
            var context       = new WriterContext(bufferManager);
            var buffer        = bufferManager.Dequeue();

            bufferManager.Enqueue(buffer);
            var sut = new HandshakeFrame();

            sut.Identity           = "Client";
            sut.OptionalExtensions = new[] { new HandshakeExtension("json", new Dictionary <string, string> {
                    { "Key", "Value" }
                }), new HandshakeExtension("ack") };
            sut.RequiredExtensions = new[] { new HandshakeExtension("dotnet") };
            sut.VersionMajor       = 1;
            sut.Write(context);
            sut.ResetWrite(context);

            var offset       = buffer.Offset;
            var receiveFrame = new HandshakeFrame();
            var len          = context.GetPackets()[0].Count;

            receiveFrame.Read(buffer.Array, ref offset, ref len);

            receiveFrame.OptionalExtensions[0].Properties["Key"].Should().Be("Value");
        }
Ejemplo n.º 7
0
        public void send_a_frame()
        {
            var service        = Substitute.For <IExtensionService>();
            var mgr            = new BufferManager(100, 10);
            var isDisconnected = false;

            using (var helper = new ClientServerHelper()) // wrap for cleanup
            {
                var sut = new SharpMessaging.Connection.Connection("adam", service, true, mgr);
                sut.Disconnected += (o, error) => isDisconnected = true;
                sut.Assign(helper.Server);
                sut.Send(new HandshakeFrame()
                {
                    Identity = "A"
                });
                Thread.Sleep(100);

                byte[] buffer    = new byte[65535];
                var    bytesRead = helper.Client.Receive(buffer, SocketFlags.None);
                var    frame     = new HandshakeFrame();
                var    offset    = 0;
                int    len       = bytesRead;
                frame.Read(buffer, ref offset, ref len);
                frame.Identity.Should().Be("A");
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Final step at server side.
        /// </summary>
        /// <param name="clientFrame">Extensions that the client selected for this connection.</param>
        public void ServerConfirm(HandshakeFrame clientFrame)
        {
            var all = clientFrame.RequiredExtensions.Union(clientFrame.OptionalExtensions)
                      .Distinct()
                      .Select(x => x.Name);

            _chosenExtensions = _registry.GetAll(all);
        }
Ejemplo n.º 9
0
        private void NegotiateHandshake(HandshakeFrame handshakeFrame)
        {
            ClientName = handshakeFrame.Identity;
            var frame = _extensionService.ServerNegotiate(handshakeFrame, ServerName);

            _state = ServerState.WaitingOnFinalHandshake;
            _connection.Send(frame);
        }
Ejemplo n.º 10
0
 public HandshakeFrameReceivedEventArgs(HandshakeFrame handshake)
 {
     if (handshake == null)
     {
         throw new ArgumentNullException("handshake");
     }
     Handshake = handshake;
 }
Ejemplo n.º 11
0
        /// <summary>
        ///     Final step client side.
        /// </summary>
        /// <param name="serverFrame"></param>
        /// <param name="clientName"></param>
        /// <returns></returns>
        public HandshakeFrame ClientConfirmExtensions(HandshakeFrame serverFrame, string clientName)
        {
            var extensions = _registry.GetRequiredForHandshake().ToList();
            var required   = new List <HandshakeExtension>(extensions);

            foreach (var extension in serverFrame.RequiredExtensions)
            {
                if (!extensions.Contains(extension))
                {
                    extensions.Add(extension);
                }
                if (!required.Contains(extension))
                {
                    required.Add(extension);
                }
            }
            //do not use optional extensions.
            // currently only use them to expose all extensions to the remote end point.

            //foreach (var extension in _registry.GetOptionalForHandshake())
            //{
            //    if (!extensions.Contains(extension))
            //        extensions.Add(extension);
            //}
            //foreach (var extension in serverFrame.OptionalExtensions)
            //{
            //    if (!extensions.Contains(extension) && _registry.Exists(extension.Name))
            //        extensions.Add(extension);
            //}

            //var optional = _registry.GetOptionalForHandshake().Union(serverFrame.OptionalExtensions).Distinct();


            _chosenExtensions = _registry.GetAll(extensions.Select(x => x.Name));

            var negotiatedRequired = new List <HandshakeExtension>();

            foreach (var handshakeExtension in required)
            {
                var serverExtension =
                    serverFrame.RequiredExtensions.FirstOrDefault(x => x.IsSameExtension(handshakeExtension));
                var clientExtension =
                    _registry.Get(handshakeExtension.Name);

                var extension = clientExtension.Negotiate(serverExtension);
                negotiatedRequired.Add(extension);
            }


            return(new HandshakeFrame
            {
                Identity = clientName,
                VersionMajor = SharpMessagingServer.Major,
                VersionMinor = SharpMessagingServer.Minor,
                OptionalExtensions = new HandshakeExtension[0],
                RequiredExtensions = required.ToArray()
            });
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Final step client side.
        /// </summary>
        /// <param name="serverFrame"></param>
        /// <param name="clientName"></param>
        /// <returns></returns>
        public HandshakeFrame ClientConfirmExtensions(HandshakeFrame serverFrame, string clientName)
        {
            var extensions = _registry.GetRequiredForHandshake().ToList();
            var required = new List<HandshakeExtension>(extensions);
            foreach (var extension in serverFrame.RequiredExtensions)
            {
                if (!extensions.Contains(extension))
                    extensions.Add(extension);
                if (!required.Contains(extension))
                    required.Add(extension);
            }
            //do not use optional extensions.
            // currently only use them to expose all extensions to the remote end point.

            //foreach (var extension in _registry.GetOptionalForHandshake())
            //{
            //    if (!extensions.Contains(extension))
            //        extensions.Add(extension);
            //}
            //foreach (var extension in serverFrame.OptionalExtensions)
            //{
            //    if (!extensions.Contains(extension) && _registry.Exists(extension.Name))
            //        extensions.Add(extension);
            //}

            //var optional = _registry.GetOptionalForHandshake().Union(serverFrame.OptionalExtensions).Distinct();

            _chosenExtensions = _registry.GetAll(extensions.Select(x => x.Name));

            var negotiatedRequired = new List<HandshakeExtension>();
            foreach (var handshakeExtension in required)
            {
                var serverExtension =
                    serverFrame.RequiredExtensions.FirstOrDefault(x => x.IsSameExtension(handshakeExtension));
                var clientExtension =
                    _registry.Get(handshakeExtension.Name);

                var extension = clientExtension.Negotiate(serverExtension);
                negotiatedRequired.Add(extension);
            }

            return new HandshakeFrame
            {
                Identity = clientName,
                VersionMajor = SharpMessagingServer.Major,
                VersionMinor = SharpMessagingServer.Minor,
                OptionalExtensions = new HandshakeExtension[0],
                RequiredExtensions = required.ToArray()
            };
        }
Ejemplo n.º 13
0
        /// <summary>
        ///     First step at server side
        /// </summary>
        /// <param name="clientFrame"></param>
        /// <param name="serverName"></param>
        /// <returns></returns>
        public IFrame ServerNegotiate(HandshakeFrame clientFrame, string serverName)
        {
            var ourRequired = _registry.GetRequiredForHandshake();
            var missingExtensionsThatTheClientRequire =
                clientFrame.RequiredExtensions.Except(_registry.GetAllForHandshake(), new ExtensionNameComparer())
                .ToList();

            if (missingExtensionsThatTheClientRequire.Any())
            {
                return
                    (new ErrorFrame("Server to not support the following extensions: " +
                                    string.Join(", ", missingExtensionsThatTheClientRequire)));
            }

            var missingExtensionsThatTheServerRequire =
                ourRequired.Except(clientFrame.RequiredExtensions.Union(clientFrame.OptionalExtensions),
                                   new ExtensionNameComparer()).ToList();

            if (missingExtensionsThatTheServerRequire.Any())
            {
                return
                    (new ErrorFrame("Server requires the following extensions: " +
                                    string.Join(", ", missingExtensionsThatTheServerRequire)));
            }


            var required       = ourRequired.Union(clientFrame.RequiredExtensions).Distinct().ToList();
            var chosenOptional =
                _registry.GetOptionalForHandshake()
                .Union(clientFrame.OptionalExtensions)
                .Distinct()
                .Except(required, new ExtensionNameComparer());

            return(new HandshakeFrame
            {
                Identity = serverName,
                VersionMajor = SharpMessagingServer.Major,
                VersionMinor = SharpMessagingServer.Minor,
                OptionalExtensions = chosenOptional.ToArray(),
                RequiredExtensions = required.ToArray()
            });
        }
Ejemplo n.º 14
0
 private async void HandleMessage(PipeFrame frame)
 {
     Console.ForegroundColor = ConsoleColor.Gray;
     if (frame.Opcode == Opcode.Handshake)
     {
         //Respond with handshake
         Console.WriteLine("Sending handshake response");
         HandshakeFrame handshakeFrame = JsonConvert.DeserializeObject <HandshakeFrame>(frame.Message);
         SetAppId?.Invoke(null, handshakeFrame.client_id);
         Ready.Data ready = new Ready.Data()
         {
             Config = new Ready.Config()
             {
                 APIendpoint = "//discordapp.com/api",
                 CdnHost     = "cdn.discordapp.com",
                 Environment = "production"
             },
             User = new Ready.User()
             {
                 Avatar        = "123",
                 Bot           = false,
                 Discriminator = "8813",
                 Id            = "123",
                 Username      = "******"
             },
             Version = 1
         };
         SendFrame(Command.Dispatch, ServerEvent.Ready, ready);
     }
     else if (frame.Opcode == Opcode.Frame)
     {
         var frameMessage = JsonConvert.DeserializeObject <FrameMessage>(frame.Message);
         MessageReceived?.Invoke(null, frameMessage.Args.Activity);
     }
     Console.ForegroundColor = ConsoleColor.White;
 }
Ejemplo n.º 15
0
        /// <summary>
        ///     First step at server side
        /// </summary>
        /// <param name="clientFrame"></param>
        /// <param name="serverName"></param>
        /// <returns></returns>
        public IFrame ServerNegotiate(HandshakeFrame clientFrame, string serverName)
        {
            var ourRequired = _registry.GetRequiredForHandshake();
            var missingExtensionsThatTheClientRequire =
                clientFrame.RequiredExtensions.Except(_registry.GetAllForHandshake(), new ExtensionNameComparer())
                    .ToList();
            if (missingExtensionsThatTheClientRequire.Any())
            {
                return
                    new ErrorFrame("Server to not support the following extensions: " +
                                   string.Join(", ", missingExtensionsThatTheClientRequire));
            }

            var missingExtensionsThatTheServerRequire =
                ourRequired.Except(clientFrame.RequiredExtensions.Union(clientFrame.OptionalExtensions),
                    new ExtensionNameComparer()).ToList();
            if (missingExtensionsThatTheServerRequire.Any())
            {
                return
                    new ErrorFrame("Server requires the following extensions: " +
                                   string.Join(", ", missingExtensionsThatTheServerRequire));
            }

            var required = ourRequired.Union(clientFrame.RequiredExtensions).Distinct().ToList();
            var chosenOptional =
                _registry.GetOptionalForHandshake()
                    .Union(clientFrame.OptionalExtensions)
                    .Distinct()
                    .Except(required, new ExtensionNameComparer());

            return new HandshakeFrame
            {
                Identity = serverName,
                VersionMajor = SharpMessagingServer.Major,
                VersionMinor = SharpMessagingServer.Minor,
                OptionalExtensions = chosenOptional.ToArray(),
                RequiredExtensions = required.ToArray()
            };
        }
Ejemplo n.º 16
0
 /// <summary>
 ///     Final step at server side.
 /// </summary>
 /// <param name="clientFrame">Extensions that the client selected for this connection.</param>
 public void ServerConfirm(HandshakeFrame clientFrame)
 {
     var all = clientFrame.RequiredExtensions.Union(clientFrame.OptionalExtensions)
         .Distinct()
         .Select(x => x.Name);
     _chosenExtensions = _registry.GetAll(all);
 }