protected virtual void SetLobbyPropertiesMessageHandler(IIncomingMessage message) { var data = message.Deserialize(new LobbyPropertiesSetPacket()); lobbies.TryGetValue(data.LobbyId, out ILobby lobby); if (lobby == null) { message.Respond("Lobby was not found", ResponseStatus.Failed); return; } var lobbiesExt = GetOrCreateLobbyUserPeerExtension(message.Peer); foreach (var dataProperty in data.Properties.ToDictionary()) { if (!lobby.SetProperty(lobbiesExt, dataProperty.Key, dataProperty.Value)) { message.Respond("Failed to set the property: " + dataProperty.Key, ResponseStatus.Failed); return; } } message.Respond(ResponseStatus.Success); }
private void AbortSpawnRequestHandler(IIncomingMessage message) { var prevRequest = message.Peer.GetProperty((int)MstPeerPropertyCodes.ClientSpawnRequest) as SpawnTask; if (prevRequest == null) { message.Respond("There's nothing to abort", ResponseStatus.Failed); return; } if (prevRequest.Status >= SpawnStatus.Finalized) { message.Respond("You can't abort a completed request", ResponseStatus.Failed); return; } if (prevRequest.Status <= SpawnStatus.None) { message.Respond("Already aborting", ResponseStatus.Success); return; } logger.Debug($"Client [{message.Peer.Id}] requested to terminate process [{prevRequest.Id}]"); prevRequest.Abort(); message.Respond(ResponseStatus.Success); }
protected virtual void GetCompletionDataRequestHandler(IIncomingMessage message) { var spawnId = message.AsInt(); if (!spawnTasksList.TryGetValue(spawnId, out SpawnTask task)) { message.Respond("Invalid request", ResponseStatus.Failed); return; } if (task.Requester != message.Peer) { message.Respond("You're not the requester", ResponseStatus.Unauthorized); return; } if (task.FinalizationPacket == null) { message.Respond("Task has no completion data", ResponseStatus.Failed); return; } // Respond with data (dictionary of strings) message.Respond(task.FinalizationPacket.FinalizationData.ToBytes(), ResponseStatus.Success); }
protected virtual void DestroyRoomRequestHandler(IIncomingMessage message) { var roomId = message.AsInt(); logger.Debug($"Client {message.Peer.Id} requested to destroy room server with id {roomId}"); if (!roomsList.TryGetValue(roomId, out RegisteredRoom room)) { logger.Debug($"But this room does not exist"); message.Respond("Room does not exist", ResponseStatus.Failed); return; } if (message.Peer != room.Peer) { logger.Debug($"But it is not the creator of the room"); message.Respond("You're not the creator of the room", ResponseStatus.Unauthorized); return; } DestroyRoom(room); logger.Debug($"Room {roomId} has been successfully destroyed"); message.Respond(ResponseStatus.Success); }
protected virtual void OnChatMessageHandler(IIncomingMessage message) { var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); string responseMsg; if (chatUser == null) { responseMsg = "Chat cannot identify you"; logger.Error(responseMsg); message.Respond(responseMsg, ResponseStatus.Unauthorized); return; } var packet = message.Deserialize(new ChatMessagePacket()); if (!TryHandleChatMessage(packet, chatUser, message)) { responseMsg = "Invalid message"; logger.Error(responseMsg); // If message was not handled message.Respond(responseMsg, ResponseStatus.NotHandled); return; } }
protected virtual void GetRoomAccessRequestHandler(IIncomingMessage message) { var data = message.Deserialize(new RoomAccessRequestPacket()); // Let's find a room by Id which the player wants to join if (!roomsList.TryGetValue(data.RoomId, out RegisteredRoom room)) { message.Respond("Room does not exist", ResponseStatus.Failed); return; } // If room requires the password and given password is not valid if (!string.IsNullOrEmpty(room.Options.Password) && room.Options.Password != data.Password) { message.Respond("Invalid password", ResponseStatus.Unauthorized); return; } // Send room access request to peer who owns it room.GetAccess(message.Peer, data.CustomOptions, (packet, error) => { if (packet == null) { message.Respond(error, ResponseStatus.Unauthorized); return; } message.Respond(packet, ResponseStatus.Success); }); }
private void SetMyPropertiesMessageHandler(IIncomingMessage message) { // Get lobby user peer extension var lobbyUser = GetOrCreateLobbyUserPeerExtension(message.Peer); // Get current lobby this user joined in var lobby = lobbyUser.CurrentLobby; if (lobby == null) { message.Respond("Lobby was not found", ResponseStatus.Failed); return; } // Properties to be changed var properties = new Dictionary <string, string>().FromBytes(message.AsBytes()); // Get member of lobby by its lobby user extension var member = lobby.GetMemberByExtension(lobbyUser); foreach (var dataProperty in properties) { // We don't change properties directly, // because we want to allow an implementation of lobby // to do "sanity" checking if (!lobby.SetPlayerProperty(member, dataProperty.Key, dataProperty.Value)) { message.Respond("Failed to set property: " + dataProperty.Key, ResponseStatus.Failed); return; } } message.Respond(ResponseStatus.Success); }
/// <summary> /// Handles a message from spawned process. Spawned process send this message /// to notify server that it was started /// </summary> /// <param name="message"></param> protected virtual void RegisterSpawnedProcessRequestHandler(IIncomingMessage message) { var data = message.Deserialize(new RegisterSpawnedProcessPacket()); // Try get psawn task by ID if (!spawnTasksList.TryGetValue(data.SpawnId, out SpawnTask task)) { message.Respond("Invalid spawn task", ResponseStatus.Failed); logger.Error("Process tried to register to an unknown task"); return; } // Check spawn task unique code if (task.UniqueCode != data.SpawnCode) { message.Respond("Unauthorized", ResponseStatus.Unauthorized); logger.Error("Spawned process tried to register, but failed due to mismaching unique code"); return; } // Set task as registered task.OnRegistered(message.Peer); // Invoke event OnSpawnedProcessRegisteredEvent?.Invoke(task, message.Peer); // Respon to requester message.Respond(task.Options.ToDictionary().ToBytes(), ResponseStatus.Success); }
private void UpdateDisplayNameRequestHandler(IIncomingMessage message) { var userExtension = message.Peer.GetExtension <IUserPeerExtension>(); if (userExtension == null || userExtension.Account == null) { message.Respond("Invalid session", ResponseStatus.Unauthorized); return; } var newProfileData = new Dictionary <string, string>().FromBytes(message.AsBytes()); try { if (profilesList.TryGetValue(userExtension.Username, out ObservableServerProfile profile)) { profile.GetProperty <ObservableString>((short)ObservablePropertiyCodes.DisplayName).Set(newProfileData["displayName"]); profile.GetProperty <ObservableString>((short)ObservablePropertiyCodes.Avatar).Set(newProfileData["avatarUrl"]); message.Respond(ResponseStatus.Success); } else { message.Respond("Invalid session", ResponseStatus.Unauthorized); } } catch (Exception e) { message.Respond($"Internal Server Error: {e}", ResponseStatus.Error); } }
/// <summary> /// /// </summary> /// <param name="message"></param> protected virtual void PermissionLevelRequestHandler(IIncomingMessage message) { var key = message.AsString(); var extension = message.Peer.GetExtension <SecurityInfoPeerExtension>(); var currentLevel = extension.PermissionLevel; var newLevel = currentLevel; var permissionClaimed = false; foreach (var entry in permissions) { if (entry.key == key) { newLevel = entry.permissionLevel; permissionClaimed = true; } } extension.PermissionLevel = newLevel; if (!permissionClaimed && !string.IsNullOrEmpty(key)) { // If we didn't claim a permission message.Respond("Invalid permission key", ResponseStatus.Unauthorized); return; } message.Respond(newLevel, ResponseStatus.Success); }
protected virtual void OnChatMessageHandler(IIncomingMessage message) { try { var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); // If peer has no user if (chatUser == null) { throw new MstMessageHandlerException("Chat cannot identify you", ResponseStatus.Unauthorized); } var packet = message.Deserialize(new ChatMessagePacket()); if (!TryHandleChatMessage(packet, chatUser, message)) { throw new MstMessageHandlerException("Invalid message", ResponseStatus.NotHandled); } } // If we got system exception catch (MstMessageHandlerException e) { logger.Error(e.Message); message.Respond(e.Message, e.Status); } // If we got another exception catch (Exception e) { logger.Error(e.Message); message.Respond(e.Message, ResponseStatus.Error); } }
/// <summary> /// Handles a request from user to join a lobby /// </summary> /// <param name="message"></param> protected virtual void JoinLobbyHandler(IIncomingMessage message) { var lobbyUser = GetOrCreateLobbyUserPeerExtension(message.Peer); if (lobbyUser.CurrentLobby != null) { message.Respond("You're already in a lobby", ResponseStatus.Failed); return; } var lobbyId = message.AsInt(); lobbies.TryGetValue(lobbyId, out ILobby lobby); if (lobby == null) { message.Respond("Lobby was not found", ResponseStatus.Failed); return; } if (!lobby.AddPlayer(lobbyUser, out string error)) { message.Respond(error ?? "Failed to add player to lobby", ResponseStatus.Failed); return; } var data = lobby.GenerateLobbyData(lobbyUser); message.Respond(data, ResponseStatus.Success); }
protected virtual void JoinLobbyTeamMessageHandler(IIncomingMessage message) { var data = message.Deserialize(new LobbyJoinTeamPacket()); var lobbiesExt = GetOrCreateLobbyUserPeerExtension(message.Peer); var lobby = lobbiesExt.CurrentLobby; if (lobby == null) { message.Respond("You're not in a lobby", ResponseStatus.Failed); return; } var player = lobby.GetMemberByExtension(lobbiesExt); if (player == null) { message.Respond("Invalid request", ResponseStatus.Failed); return; } if (!lobby.TryJoinTeam(data.TeamName, player)) { message.Respond("Failed to join a team: " + data.TeamName, ResponseStatus.Failed); return; } message.Respond(ResponseStatus.Success); }
protected virtual void OnGetUsersInChannelRequestHandler(IIncomingMessage message) { string responseMsg = string.Empty; var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); if (chatUser == null) { responseMsg = "Chat cannot identify you"; logger.Error(responseMsg); message.Respond(responseMsg, ResponseStatus.Unauthorized); return; } var channelName = message.AsString(); var channel = GetOrCreateChannel(channelName); if (channel == null) { responseMsg = "This channel is forbidden"; logger.Error(responseMsg); // There's no such channel message.Respond(responseMsg, ResponseStatus.Failed); return; } var users = channel.Users.Select(u => u.Username); message.Respond(users.ToBytes(), ResponseStatus.Success); }
protected virtual void OnPickUsernameRequestHandler(IIncomingMessage message) { try { if (!allowUsernamePicking) { throw new MstMessageHandlerException("Username picking is disabled", ResponseStatus.Failed); } var username = message.AsString(); if (username.Contains(" ")) { throw new MstMessageHandlerException("Username cannot contain whitespaces", ResponseStatus.Failed); } var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); if (chatUser != null) { throw new MstMessageHandlerException($"You're already identified as: {chatUser.Username}", ResponseStatus.Failed); } if (ChatUsers.ContainsKey(username)) { throw new MstMessageHandlerException("There's already a user who has the same username", ResponseStatus.Failed); } chatUser = CreateChatUser(message.Peer, username); if (!AddChatUser(chatUser)) { throw new MstMessageHandlerException("Failed to add user to chat", ResponseStatus.Failed); } // Add the extension message.Peer.AddExtension(chatUser); // Send response message.Respond(ResponseStatus.Success); } // If we got system exception catch (MstMessageHandlerException e) { logger.Error(e.Message); message.Respond(e.Message, e.Status); } // If we got another exception catch (Exception e) { logger.Error(e.Message); message.Respond(e.Message, ResponseStatus.Error); } }
protected virtual void StartLobbyGameMessageHandler(IIncomingMessage message) { var lobbiesExt = GetOrCreateLobbyUserPeerExtension(message.Peer); var lobby = lobbiesExt.CurrentLobby; if (!lobby.StartGameManually(lobbiesExt)) { message.Respond("Failed starting the game", ResponseStatus.Failed); return; } message.Respond(ResponseStatus.Success); }
protected virtual void GetLobbyInfoMessageHandler(IIncomingMessage message) { var lobbyId = message.AsInt(); lobbies.TryGetValue(lobbyId, out ILobby lobby); if (lobby == null) { message.Respond("Lobby not found", ResponseStatus.Failed); return; } message.Respond(lobby.GenerateLobbyData(), ResponseStatus.Success); }
protected virtual void OnJoinChannelRequestHandler(IIncomingMessage message) { try { // Get user from peer var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); // If peer has no user if (chatUser == null) { throw new MstMessageHandlerException("Chat cannot identify you", ResponseStatus.Unauthorized); } // Get channel name var channelName = message.AsString(); // Trying to create channel with given name var channel = GetOrCreateChannel(channelName); if (channel == null) { throw new MstMessageHandlerException("This channel is forbidden", ResponseStatus.Failed); } if (!channel.AddUser(chatUser)) { throw new MstMessageHandlerException("Failed to join a channel", ResponseStatus.Failed); } if (setFirstChannelAsLocal && chatUser.CurrentChannels.Count == 1) { chatUser.DefaultChannel = channel; } message.Respond(ResponseStatus.Success); } // If we got system exception catch (MstMessageHandlerException e) { logger.Error(e.Message); message.Respond(e.Message, e.Status); } // If we got another exception catch (Exception e) { logger.Error(e.Message); message.Respond(e.Message, ResponseStatus.Error); } }
protected virtual void OnJoinChannelRequestHandler(IIncomingMessage message) { var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); string responseMsg; if (chatUser == null) { responseMsg = "Chat cannot identify you"; logger.Error(responseMsg); message.Respond(responseMsg, ResponseStatus.Unauthorized); return; } var channelName = message.AsString(); var channel = GetOrCreateChannel(channelName); if (channel == null) { responseMsg = "This channel is forbidden"; logger.Error(responseMsg); // There's no such channel message.Respond(responseMsg, ResponseStatus.Failed); return; } if (!channel.AddUser(chatUser)) { responseMsg = "Failed to join a channel"; logger.Error(responseMsg); message.Respond(responseMsg, ResponseStatus.Failed); return; } if (setFirstChannelAsLocal && chatUser.CurrentChannels.Count == 1) { chatUser.DefaultChannel = channel; } message.Respond(ResponseStatus.Success); }
protected virtual void OnLeaveChannelRequestHandler(IIncomingMessage message) { try { // Get user from peer var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); // If peer has no user if (chatUser == null) { throw new MstMessageHandlerException("Chat cannot identify you", ResponseStatus.Unauthorized); } // Get channel name var channelName = message.AsString(); // Trying to get channel by name if (!ChatChannels.TryGetValue(channelName, out ChatChannel channel)) { throw new MstMessageHandlerException("This channel does not exist", ResponseStatus.Failed); } // Remove user from channel channel.RemoveUser(chatUser); if (setLastChannelAsLocal && chatUser.CurrentChannels.Count == 1) { chatUser.DefaultChannel = chatUser.CurrentChannels.First(); } message.Respond(ResponseStatus.Success); } // If we got system exception catch (MstMessageHandlerException e) { logger.Error(e.Message); message.Respond(e.Message, e.Status); } // If we got another exception catch (Exception e) { logger.Error(e.Message); message.Respond(e.Message, ResponseStatus.Error); } }
protected virtual void RegisterSpawnerRequestHandler(IIncomingMessage message) { logger.Debug($"Client [{message.Peer.Id}] requested to be registered as spawner"); if (!HasCreationPermissions(message.Peer)) { message.Respond("Insufficient permissions", ResponseStatus.Unauthorized); return; } var options = message.Deserialize(new SpawnerOptions()); var spawner = CreateSpawner(message.Peer, options); logger.Debug($"Client [{message.Peer.Id}] was successfully registered as spawner [{spawner.SpawnerId}] with options: {options}"); // Respond with spawner id message.Respond(spawner.SpawnerId, ResponseStatus.Success); }
protected virtual void OnGetCurrentChannelsRequestHandler(IIncomingMessage message) { var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); if (chatUser == null) { string responseMsg = "Chat cannot identify you"; logger.Error(responseMsg); message.Respond(responseMsg, ResponseStatus.Unauthorized); return; } var channels = chatUser.CurrentChannels.Select(c => c.Name); message.Respond(channels.ToBytes(), ResponseStatus.Success); }
/// <summary> /// Invokes when message received /// </summary> /// <param name="message"></param> protected virtual void OnMessageReceived(IIncomingMessage message) { try { handlers.TryGetValue(message.OpCode, out IPacketHandler handler); if (handler == null) { logger.Warn(string.Format($"Handler for OpCode {message.OpCode} does not exist")); if (message.IsExpectingResponse) { message.Respond(internalServerErrorMessage, ResponseStatus.NotHandled); return; } return; } handler.Handle(message); } catch (Exception e) { if (Mst.Runtime.IsEditor) { throw; } logger.Error($"Error while handling a message from Client. OpCode: {message.OpCode}, Error: {e}"); if (!message.IsExpectingResponse) { return; } try { message.Respond(internalServerErrorMessage, ResponseStatus.Error); } catch (Exception exception) { Logs.Error(exception); } } }
/// <summary> /// Handles kill request for all controllers filtered by ID /// </summary> /// <param name="message"></param> private static void KillProcessRequestHandler(IIncomingMessage message) { var data = message.Deserialize(new KillSpawnedProcessRequestPacket()); var controller = Mst.Server.Spawners.GetController(data.SpawnerId) as SpawnerController; if (controller == null) { if (message.IsExpectingResponse) { message.Respond("Couldn't find a spawn controller", ResponseStatus.NotHandled); } return; } controller.Logger.Debug($"Kill process requested for spawn controller [{controller.SpawnerId}]"); controller.KillRequestHandler(data.SpawnId); message.Respond(ResponseStatus.Success); }
protected virtual void RegisterRoomRequestHandler(IIncomingMessage message) { logger.Debug($"Client {message.Peer.Id} requested to register new room server"); if (!HasRoomRegistrationPermissions(message.Peer)) { logger.Debug($"But it has no permission"); message.Respond("Insufficient permissions", ResponseStatus.Unauthorized); return; } var options = message.Deserialize(new RoomOptions()); var room = RegisterRoom(message.Peer, options); logger.Debug($"Room {room.RoomId} has been successfully registered with options: {options}"); // Respond with a room id message.Respond(room.RoomId, ResponseStatus.Success); }
protected virtual void ValidateRoomAccessRequestHandler(IIncomingMessage message) { // Parse message var data = message.Deserialize(new RoomAccessValidatePacket()); // Trying to find room in list of registered if (!roomsList.TryGetValue(data.RoomId, out RegisteredRoom room)) { message.Respond("Room does not exist", ResponseStatus.Failed); return; } // if this message is not received from owner of room if (message.Peer != room.Peer) { // Wrong peer of room registrar message.Respond("You're not the registrar of the room", ResponseStatus.Unauthorized); return; } // Trying to validate room access token if (!room.ValidateAccess(data.Token, out IPeer playerPeer)) { message.Respond("Failed to confirm the access", ResponseStatus.Unauthorized); return; } var packet = new UsernameAndPeerIdPacket() { PeerId = playerPeer.Id }; // Add username if available var userExt = playerPeer.GetExtension <IUserPeerExtension>(); if (userExt != null) { packet.Username = userExt.Username ?? ""; } // Respond with success and player's peer id message.Respond(packet, ResponseStatus.Success); }
protected virtual void OnSetDefaultChannelRequestHandler(IIncomingMessage message) { try { var chatUser = message.Peer.GetExtension <ChatUserPeerExtension>(); // If peer has no user if (chatUser == null) { throw new MstMessageHandlerException("Chat cannot identify you", ResponseStatus.Unauthorized); } var channelName = message.AsString(); var channel = GetOrCreateChannel(channelName); if (channel == null) { throw new MstMessageHandlerException("This channel is forbidden", ResponseStatus.Failed); } // Add user to channel channel.AddUser(chatUser); // Set the property of default chat channel chatUser.DefaultChannel = channel; // Respond with a "success" status message.Respond(ResponseStatus.Success); } // If we got system exception catch (MstMessageHandlerException e) { logger.Error(e.Message); message.Respond(e.Message, e.Status); } // If we got another exception catch (Exception e) { logger.Error(e.Message); message.Respond(e.Message, ResponseStatus.Error); } }
/// <summary> /// Handles a request from game server to get a profile /// </summary> /// <param name="message"></param> protected virtual void GameServerProfileRequestHandler(IIncomingMessage message) { if (!HasPermissionToEditProfiles(message.Peer)) { message.Respond("Invalid permission level", ResponseStatus.Unauthorized); return; } var userId = message.AsString(); profilesList.TryGetValue(userId, out ObservableServerProfile profile); if (profile == null) { message.Respond(ResponseStatus.Failed); return; } message.Respond(profile.ToBytes(), ResponseStatus.Success); }
protected virtual void SaveRoomOptionsRequestHandler(IIncomingMessage message) { var data = message.Deserialize(new SaveRoomOptionsPacket()); if (!roomsList.TryGetValue(data.RoomId, out RegisteredRoom room)) { message.Respond("Room does not exist", ResponseStatus.Failed); return; } if (message.Peer != room.Peer) { // Wrong peer unregistering the room message.Respond("You're not the creator of the room", ResponseStatus.Unauthorized); return; } ChangeRoomOptions(room, data.Options); message.Respond(ResponseStatus.Success); }
/// <summary> /// /// </summary> /// <param name="message"></param> protected virtual async void GetAesKeyRequestHandler(IIncomingMessage message) { var extension = message.Peer.GetExtension <SecurityInfoPeerExtension>(); var encryptedKey = extension.AesKeyEncrypted; if (encryptedKey != null) { logger.Debug("There's already a key generated"); // There's already a key generated message.Respond(encryptedKey, ResponseStatus.Success); return; } // Generate a random key var aesKey = Mst.Helper.CreateRandomAlphanumericString(8); var clientsPublicKeyXml = message.AsString(); // Deserialize public key var sr = new System.IO.StringReader(clientsPublicKeyXml); var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); var clientsPublicKey = (RSAParameters)xs.Deserialize(sr); byte[] encryptedAes = await Task.Run(() => { using (var csp = new RSACryptoServiceProvider()) { csp.ImportParameters(clientsPublicKey); encryptedAes = csp.Encrypt(Encoding.Unicode.GetBytes(aesKey), false); // Save keys for later use extension.AesKeyEncrypted = encryptedAes; extension.AesKey = aesKey; return(encryptedAes); } }); message.Respond(encryptedAes, ResponseStatus.Success); }