Ejemplo n.º 1
0
        private SmartGlassClient(
            Device device,
            ConnectResponseMessage connectResponse,
            CryptoContext cryptoContext)
        {
            Device                   = device;
            _messageTransport        = new MessageTransport(device.Address.ToString(), cryptoContext);
            _sessionMessageTransport = new SessionMessageTransport(
                _messageTransport,
                new SessionInfo()
            {
                ParticipantId = connectResponse.ParticipantId
            });

            _sessionMessageTransport.MessageReceived += (s, e) =>
            {
                var consoleStatusMessage = e.Message as ConsoleStatusMessage;
                if (consoleStatusMessage != null)
                {
                    CurrentConsoleStatus = new ConsoleStatus()
                    {
                        Configuration = consoleStatusMessage.Configuration,
                        ActiveTitles  = consoleStatusMessage.ActiveTitles
                    };

                    ConsoleStatusChanged?.Invoke(this, new ConsoleStatusChangedEventArgs(
                                                     CurrentConsoleStatus
                                                     ));
                }
            };

            _sessionMessageTransport.SendAsync(new LocalJoinMessage()).Wait();
            OpenChannels().Wait();
            _sessionMessageTransport.StartHeartbeat();
        }
Ejemplo n.º 2
0
        private SmartGlassClient(
            Device device,
            ConnectResponseMessage connectResponse,
            CryptoContext cryptoContext)
        {
            _messageTransport        = new MessageTransport(device.Address.ToString(), cryptoContext);
            _sessionMessageTransport = new SessionMessageTransport(
                _messageTransport,
                new SessionInfo()
            {
                ParticipantId = connectResponse.ParticipantId
            });

            _sessionMessageTransport.MessageReceived += (s, e) =>
            {
                var consoleStatusMessage = e.Message as ConsoleStatusMessage;
                if (consoleStatusMessage != null)
                {
                    ConsoleStatusChanged?.Invoke(this, new ConsoleStatusChangedEventArgs(
                                                     new ConsoleStatus()
                    {
                        Configuration = consoleStatusMessage.Configuration,
                        ActiveTitles  = consoleStatusMessage.ActiveTitles
                    }
                                                     ));
                }
            };

            _sessionMessageTransport.SendAsync(new LocalJoinMessage());

            _inputChannel = new DisposableAsyncLazy <InputChannel>(async() =>
            {
                return(new InputChannel(await StartChannelAsync(ServiceType.SystemInput)));
            });
        }
Ejemplo n.º 3
0
        private bool ConnectCallback(IAsyncResult ar)
        {
            UdpTrackerAsyncState trackerState = (UdpTrackerAsyncState)ar;

            try
            {
                UdpTrackerMessage msg = Receive(trackerState, trackerState.Data);
                if (msg == null)
                {
                    return(false);//bad transaction id
                }
                ConnectResponseMessage rsp = msg as ConnectResponseMessage;
                if (rsp == null)
                {
                    //is there a possibility to have a message which is not error message or connect rsp but udp msg
                    FailureMessage = ((ErrorMessage)msg).Error;
                    return(false);//error message
                }
                connectionId = rsp.ConnectionId;
                hasConnected = true;
                amConnecting = false;
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        /// <summary>
        /// CAUTION: YOU MUST <see langword="await"/> <see cref="_InitTask"/> BEFORE USING THIS OBJECT!
        /// </summary>
        /// <param name="device"></param>
        /// <param name="connectResponse"></param>
        /// <param name="cryptoContext"></param>
        private SmartGlassClient(
            Device device,
            ConnectResponseMessage connectResponse,
            CryptoContext cryptoContext)
        {
            _messageTransport        = new MessageTransport(device.Address.ToString(), cryptoContext);
            _sessionMessageTransport = new SessionMessageTransport(
                _messageTransport,
                new SessionInfo()
            {
                ParticipantId = connectResponse.ParticipantId
            });
            _sessionMessageTransport.ProtocolTimeoutOccured += (_, e) => ProtocolTimeoutOccured?.Invoke(this, e);
            _sessionMessageTransport.MessageReceived        += (s, e) =>
            {
                if (e.Message is ConsoleStatusMessage consoleStatusMessage)
                {
                    CurrentConsoleStatus = new ConsoleStatus()
                    {
                        Configuration = consoleStatusMessage.Configuration,
                        ActiveTitles  = consoleStatusMessage.ActiveTitles
                    };

                    ConsoleStatusChanged?.Invoke(this, new ConsoleStatusChangedEventArgs(
                                                     CurrentConsoleStatus
                                                     ));
                }
            };

            _InitTask = InitializeAsync();
        }
        /// <summary>
        /// CAUTION: YOU MUST <see langword="await"/> <see cref="_InitTask"/> BEFORE USING THIS OBJECT!
        /// </summary>
        /// <param name="device"></param>
        /// <param name="connectResponse"></param>
        /// <param name="cryptoContext"></param>
        private SmartGlassClient(
            Device device,
            ConnectResponseMessage connectResponse,
            CryptoContext cryptoContext, bool connectedAuthenticated)
        {
            this.connectedAuthenticated = connectedAuthenticated;
            _messageTransport           = new MessageTransport(device.Address.ToString(), cryptoContext);
            _sessionMessageTransport    = new SessionMessageTransport(
                _messageTransport,
                new SessionInfo()
            {
                ParticipantId = connectResponse.ParticipantId
            });

            _sessionMessageTransport.MessageReceived += (s, e) =>
            {
                var consoleStatusMessage = e.Message as ConsoleStatusMessage;
                if (consoleStatusMessage != null)
                {
                    CurrentConsoleStatus = new ConsoleStatus()
                    {
                        Configuration = consoleStatusMessage.Configuration,
                        ActiveTitles  = consoleStatusMessage.ActiveTitles
                    };

                    ConsoleStatusChanged?.Invoke(this, new ConsoleStatusChangedEventArgs(
                                                     CurrentConsoleStatus
                                                     ));
                }
            };

            _InitTask = InitializeAsync();
        }
Ejemplo n.º 6
0
        protected virtual void ReceiveConnect(ConnectMessage connectMessage)
        {
            UdpTrackerMessage m = new ConnectResponseMessage(connectMessage.TransactionId, CreateConnectionID());

            byte[] data = m.Encode();
            listener.Send(data, data.Length, endpoint);
        }
Ejemplo n.º 7
0
        public void Execute(Server server, TcpClient client, IMessage message)
        {
            ConnectMessage connectMessage = message as ConnectMessage;

            // @TODO Benutzer authentifizieren

            bool authenticated = true;

            if (server.HasPassword())
            {
                authenticated = server.CheckPassword(connectMessage.ServerPassword);
            }

            if (authenticated)
            {
                server.AddClient(client);
                Console.WriteLine("Client connected.");
            }

            ConnectResponseMessage connectResponseMessage = new ConnectResponseMessage();

            connectResponseMessage.Success = authenticated;
            string json = JsonSerializer.Serialize(connectResponseMessage);

            byte[] msg = System.Text.Encoding.UTF8.GetBytes(json);
            client.GetStream().Write(msg, 0, msg.Length);
        }
Ejemplo n.º 8
0
        public static UdpTrackerMessage DecodeMessage(byte[] buffer, int offset, int count, MessageType type)
        {
            UdpTrackerMessage m = null;
            int action          = type == MessageType.Request ? ReadInt(buffer, offset + 8) : ReadInt(buffer, offset);

            switch (action)
            {
            case 0:
                if (type == MessageType.Request)
                {
                    m = new ConnectMessage();
                }
                else
                {
                    m = new ConnectResponseMessage();
                }
                break;

            case 1:
                if (type == MessageType.Request)
                {
                    m = new AnnounceMessage();
                }
                else
                {
                    m = new AnnounceResponseMessage();
                }
                break;

            case 2:
                if (type == MessageType.Request)
                {
                    m = new ScrapeMessage();
                }
                else
                {
                    m = new ScrapeResponseMessage();
                }
                break;

            case 3:
                m = new ErrorMessage();
                break;

            default:
                throw new ProtocolException(string.Format("Invalid udp message received: {0}", buffer[offset]));
            }

            try
            {
                m.Decode(buffer, offset, count);
            }
            catch
            {
                m = new ErrorMessage(0, "Couldn't decode the tracker response");
            }
            return(m);
        }
Ejemplo n.º 9
0
        public void Execute(Server server, TcpClient client, IMessage message)
        {
            var connectMessage = message as ConnectMessage;

            bool authenticatedServerPassword = true;

            if (server.HasPassword())
            {
                authenticatedServerPassword = server.CheckPassword(connectMessage.ServerPassword);
            }

            var  user = server.GetUsers().Find(u => u.Username == connectMessage.Username && u.Password == connectMessage.Password);
            bool authenticatedUser = (user != null);

            bool authenticated          = authenticatedServerPassword && authenticatedUser;
            var  connectResponseMessage = new ConnectResponseMessage();

            if (authenticated)
            {
                string sessionId = Guid.NewGuid().ToString();
                user.SessionIds.Add(sessionId);
                connectResponseMessage.SessionId = sessionId;
                server.AddClient(client);
                Console.WriteLine("Client connected.");

                if (user.SessionIds.Count == 1)
                {
                    // Send user count to all clients (broadcast)
                    UserCountMessage userCountMessage = new UserCountMessage
                    {
                        UserCount       = server.GetUsers().Count,
                        UserOnlineCount = server.GetUsers().Count(u => u.SessionIds.Count > 0),
                        UserNames       = server.GetOnlineUserNames()
                    };

                    string userCountMessageJson  = JsonSerializer.Serialize(userCountMessage);
                    byte[] userCountMessageBytes = System.Text.Encoding.UTF8.GetBytes(userCountMessageJson);

                    foreach (TcpClient remoteClient in server.GetClients())
                    {
                        remoteClient.GetStream().Write(userCountMessageBytes, 0, userCountMessageBytes.Length);
                    }
                }
            }

            connectResponseMessage.Success = authenticated;

            string json = JsonSerializer.Serialize(connectResponseMessage);

            byte[] msg = System.Text.Encoding.UTF8.GetBytes(json);
            client.GetStream().Write(msg, 0, msg.Length);
        }
Ejemplo n.º 10
0
        public void Execute(TcpClient client, IMessage message)
        {
            ConnectResponseMessage connectResponseMessage = message as ConnectResponseMessage;

            if (connectResponseMessage.Success)
            {
                Console.WriteLine("Connected!");
            }
            else
            {
                Console.WriteLine("Connection failed!");
            }
        }
Ejemplo n.º 11
0
        public void ConnectResponseTest()
        {
            ConnectResponseMessage m = new ConnectResponseMessage(5371, 12345);
            ConnectResponseMessage d = (ConnectResponseMessage)UdpTrackerMessage.DecodeMessage(m.Encode(), 0, m.ByteLength, MessageType.Response);

            Check(m, MessageType.Response);

            Assert.AreEqual(0, m.Action, "#0");
            Assert.AreEqual(m.Action, d.Action, "#1");
            Assert.AreEqual(m.ConnectionId, d.ConnectionId, "#2");
            Assert.AreEqual(m.TransactionId, d.TransactionId, "#3");
            Assert.IsTrue(Toolbox.ByteMatch(m.Encode(), d.Encode()), "#4");
            Assert.AreEqual(12345, d.ConnectionId);
            Assert.AreEqual(5371, d.TransactionId);
        }
Ejemplo n.º 12
0
        public void Execute(TcpClient client, IMessage message)
        {
            ConnectResponseMessage connectResponseMessage = message as ConnectResponseMessage;

            if (connectResponseMessage.Success)
            {
                Program.IsConnected = true;
                Program.SessionId   = connectResponseMessage.SessionId;
                Console.WriteLine($"Connected! Session Id: {Program.SessionId}");
            }
            else
            {
                Console.WriteLine("Connection failed!");
            }

            Program.IsConnecting = false;
        }
Ejemplo n.º 13
0
        public void ConnectResponseTest()
        {
            var expectedMessage = new ConnectResponseMessage(5371, 12345);
            var actualMessage   =
                (ConnectResponseMessage)
                UdpTrackerMessage.DecodeMessage(expectedMessage.Encode(), 0, expectedMessage.ByteLength, MessageType.Response);

            Check(expectedMessage, MessageType.Response);

            Assert.AreEqual(0, expectedMessage.Action, "#0");
            Assert.AreEqual(expectedMessage.Action, actualMessage.Action, "#1");
            Assert.AreEqual(expectedMessage.ConnectionId, actualMessage.ConnectionId, "#2");
            Assert.AreEqual(expectedMessage.TransactionId, actualMessage.TransactionId, "#3");
            Assert.IsTrue(Toolbox.ByteMatch(expectedMessage.Encode(), actualMessage.Encode()), "#4");
            Assert.AreEqual(12345, actualMessage.ConnectionId);
            Assert.AreEqual(5371, actualMessage.TransactionId);
        }
        public void ConnectResponseMessage_TryDecode()
        {
            ConnectResponseMessage message;

            byte[] data = "00000000000033000000041727101980".ToByteArray();

            if (ConnectResponseMessage.TryDecode(data, 0, out message))
            {
                Assert.AreEqual(16, message.Length);
                Assert.AreEqual(0, (int)message.Action);
                Assert.AreEqual(13056, message.TransactionId);
                CollectionAssert.AreEqual(data, message.Encode());
            }
            else
            {
                Assert.Fail();
            }
        }
        protected virtual async Task ReceiveConnect(UdpClient client, ConnectMessage connectMessage, IPEndPoint remotePeer)
        {
            UdpTrackerMessage m;

            if (connectMessage.ConnectionId == ConnectMessage.InitialiseConnectionId)
            {
                m = new ConnectResponseMessage(connectMessage.TransactionId, CreateConnectionID(remotePeer));
            }
            else
            {
                m = new ErrorMessage(connectMessage.TransactionId, $"The connection_id was {connectMessage.ConnectionId} but expected {ConnectMessage.InitialiseConnectionId}");
            }

            byte[] data = m.Encode();
            try {
                await client.SendAsync(data, data.Length, remotePeer);
            } catch {
            }
        }
        public static UdpTrackerMessage DecodeMessage(byte[] buffer, int offset, int count, MessageType type)
        {
            UdpTrackerMessage m = null;
            var action = type == MessageType.Request ? ReadInt(buffer, offset + 8) : ReadInt(buffer, offset);
            switch (action)
            {
                case 0:
                    if (type == MessageType.Request)
                        m = new ConnectMessage();
                    else
                        m = new ConnectResponseMessage();
                    break;
                case 1:
                    if (type == MessageType.Request)
                        m = new AnnounceMessage();
                    else
                        m = new AnnounceResponseMessage();
                    break;
                case 2:
                    if (type == MessageType.Request)
                        m = new ScrapeMessage();
                    else
                        m = new ScrapeResponseMessage();
                    break;
                case 3:
                    m = new ErrorMessage();
                    break;
                default:
                    throw new ProtocolException(string.Format("Invalid udp message received: {0}", buffer[offset]));
            }

            try
            {
                m.Decode(buffer, offset, count);
            }
            catch
            {
                m = new ErrorMessage(0, "Couldn't decode the tracker response");
            }
            return m;
        }
        public void Execute(TcpClient client, IMessage message)
        {
            ConnectResponseMessage connectResponseMessage = message as ConnectResponseMessage;

            if (connectResponseMessage.Success)
            {
                Program.IsConnected = true;
                Program.SessionId   = connectResponseMessage.SessionId;
                DateTime timeStamp = DateTime.Now;

                Console.WriteLine($"{timeStamp} Connected! Session Id: {Program.SessionId}");
                Console.WriteLine("Type in your message. " +
                                  "Other options: \"/disconnect\"  \"/exit\" \"/users\"");
            }
            else
            {
                Console.WriteLine("Connection failed!");
            }

            Program.IsConnecting = false;
        }
Ejemplo n.º 18
0
        public void Execute(Server server, TcpClient client, IMessage message)
        {
            var registrationMessage = message as RegistrationMessage;

            bool authenticatedServerPassword = true;

            if (server.HasPassword())
            {
                authenticatedServerPassword = server.CheckPassword(registrationMessage.ServerPassword);
            }
            var tmpUserList = server.GetUsers();
            int newId       = (tmpUserList.Select(x => x.Id).Max()) + 1;
            var user        = new User()
            {
                Username = registrationMessage.Username,
                Password = registrationMessage.Password,
                Id       = newId
            };

            server.AddUsers(user);
            string userJson = JsonSerializer.Serialize(server.GetUsers());

            File.WriteAllText("users.json", userJson);
            bool authenticatedUser = true;

            bool authenticated = authenticatedServerPassword && authenticatedUser;
            ConnectResponseMessage connectResponseMessage = new ConnectResponseMessage();

            if (authenticated)
            {
                string sessionId = Guid.NewGuid().ToString();
                user.SessionIds.Add(sessionId);
                connectResponseMessage.SessionId = sessionId;
                server.AddClient(client);
                Console.WriteLine("Client connected.");

                if (user.SessionIds.Count == 1)
                {
                    // Send user count to all clients (broadcast)
                    UserCountMessage userCountMessage = new UserCountMessage
                    {
                        UserCount       = server.GetUsers().Count,
                        UserOnlineCount = server.GetUsers().Count(u => u.SessionIds.Count > 0),
                        UserNames       = server.GetOnlineUserNames()
                    };

                    string userCountMessageJson  = JsonSerializer.Serialize(userCountMessage);
                    byte[] userCountMessageBytes = System.Text.Encoding.UTF8.GetBytes(userCountMessageJson);

                    foreach (TcpClient remoteClient in server.GetClients())
                    {
                        remoteClient.GetStream().Write(userCountMessageBytes, 0, userCountMessageBytes.Length);
                    }
                }
            }

            connectResponseMessage.Success = authenticated;

            string json = JsonSerializer.Serialize(connectResponseMessage);

            byte[] msg = System.Text.Encoding.UTF8.GetBytes(json);
            client.GetStream().Write(msg, 0, msg.Length);

            var registrationResponseMessage = new RegistrationResponseMessage();

            foreach (User usr in server.GetUsers())
            {
                registrationResponseMessage.Users.Add(new ChatProtocol.User(usr.Id, usr.Username));
            }

            string jsonReg = JsonSerializer.Serialize(registrationResponseMessage);

            byte[] regMsg = System.Text.Encoding.UTF8.GetBytes(jsonReg);
            client.GetStream().Write(regMsg, 0, regMsg.Length);
        }
Ejemplo n.º 19
0
        public void Execute(Server server, TcpClient client, IMessage message)
        {
            var connectMessage = message as ConnectMessage;

            var authenticatedServerPassword = true;

            if (server.HasPassword())
            {
                authenticatedServerPassword = server.CheckPassword(connectMessage.ServerPassword);
            }

            var user = server.GetUsers().Find(u => u.Username == connectMessage.ClientUsername && u.Password == connectMessage.ClientPassword);
            var authenticatedUser = (user != null);

            var authenticated          = authenticatedServerPassword && authenticatedUser;
            var connectResponseMessage = new ConnectResponseMessage();

            if (authenticated)
            {
                var sessionId = Guid.NewGuid().ToString();
                user.SessionIds.Add(sessionId);
                user.Clients.Add(client);
                connectResponseMessage.SessionId = sessionId;
                server.AddClient(client);
                Console.WriteLine("Client connected.");
                if (user.SessionIds.Count == 1)
                {
                    // Send user count to all clients (broadcast)
                    var userCountMessage = new UserCountMessage
                    {
                        UserCount       = server.GetUsers().Count,
                        UserOnlineCount = server.GetUsers().Count(u => u.SessionIds.Count > 0),
                    };

                    var userCountMessageJson  = JsonSerializer.Serialize(userCountMessage);
                    var userCountMessageBytes = System.Text.Encoding.UTF8.GetBytes(userCountMessageJson);

                    foreach (TcpClient remoteClient in server.GetClients())
                    {
                        remoteClient.GetStream().Write(userCountMessageBytes, 0, userCountMessageBytes.Length);
                    }
                    Thread.Sleep(50);
                }
            }

            connectResponseMessage.Success = authenticated;

            var json = JsonSerializer.Serialize(connectResponseMessage);
            var msg  = System.Text.Encoding.UTF8.GetBytes(json);

            client.GetStream().Write(msg, 0, msg.Length);

            /*List<DirectChatMessage> messageList = server.GetMessages();
             * if (messageList != null)
             * {
             *  foreach (var savedMessage in messageList)
             *  {
             *      if (savedMessage.ToUserId == user.Id)
             *      {
             *          var directChatMessage = savedMessage;
             *          directChatMessage.SessionId = null;
             *          var directChatJson = JsonSerializer.Serialize(directChatMessage);
             *          var chatMsg = System.Text.Encoding.UTF8.GetBytes(directChatJson);
             *          client.GetStream().Write(chatMsg, 0, chatMsg.Length);
             *      }
             *  }
             * }*/
        }
Ejemplo n.º 20
0
        public void ConnectResponseTest()
        {
            var expectedMessage = new ConnectResponseMessage(5371, 12345);
            var actualMessage =
                (ConnectResponseMessage)
                UdpTrackerMessage.DecodeMessage(expectedMessage.Encode(), 0, expectedMessage.ByteLength, MessageType.Response);
            Check(expectedMessage, MessageType.Response);

            Assert.AreEqual(0, expectedMessage.Action, "#0");
            Assert.AreEqual(expectedMessage.Action, actualMessage.Action, "#1");
            Assert.AreEqual(expectedMessage.ConnectionId, actualMessage.ConnectionId, "#2");
            Assert.AreEqual(expectedMessage.TransactionId, actualMessage.TransactionId, "#3");
            Assert.IsTrue(Toolbox.ByteMatch(expectedMessage.Encode(), actualMessage.Encode()), "#4");
            Assert.AreEqual(12345, actualMessage.ConnectionId);
            Assert.AreEqual(5371, actualMessage.TransactionId);
        }
Ejemplo n.º 21
0
 public bool TryAcceptNewPlayer(ConnectRequestMessage connectRequestMessage, out ConnectResponseMessage responseMessage)
 {
     throw new NotImplementedException();
 }